java怎么实现表格的行删除
- 提问者网友:战皆罪
- 2021-05-02 02:03
- 五星知识达人网友:孤独的牧羊人
- 2021-05-02 02:37
public class Table extends JFrame {
private JPanel jContentPane = null;
private JScrollPane jScrollPane = null;
private JTable viewtable = null;
private JButton jButton = null;
public JCheckBox checkbox = new JCheckBox("取消");
DefaultTableModel dtm = null;
String[] columnNames = { "第一列", "第二列", "第三列", "取消"};
Object[][] data = {
{ "第一列", "第二列", "第三列",checkbox },
{ "第一列", "第二列", "第三列",checkbox },
{ "第一列", "第二列", "第三列", checkbox },
{ "第一列", "第二列", "第三列", checkbox },
{ "第一列", "第二列", "第三列", checkbox } };
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setBounds(new java.awt.Rectangle(40,40,650,120));
jScrollPane.setViewportView(getViewtable());
}
return jScrollPane;
}
private JTable getViewtable() {
checkbox.addActionListener(listener);
if (viewtable == null) {
viewtable = new JTable();
dtm=new DefaultTableModel(data,columnNames);
viewtable=new JTable(dtm);
viewtable.getColumn("取消").setCellRenderer(new ButtonRenderer());
viewtable.getColumn("取消").setCellEditor(
new DefaultCellEditor(checkbox));
}
return viewtable;
}
ActionListener listener = new
ActionListener() {
public void actionPerformed(ActionEvent event) {
if (checkbox.isSelected()){
dtm.removeRow(viewtable.getSelectedRow());
checkbox.setSelected(false);
}
}
};
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setText("删除");
jButton.setBounds(new java.awt.Rectangle(289,180,120,28));
jButton.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e){
int numrow=viewtable.getSelectedRows().length;
for (int i=0;i<numrow;i++){
dtm.removeRow(viewtable.getSelectedRow());
}
}
});
}
return jButton;
}
public static void main(String[] args) {
Table table = new Table();
table.setVisible(true);
// TODO Auto-generated method stub
}
public Table() {
super();
initialize();
}
private void initialize() {
this.setSize(772, 300);
this.setContentPane(getJContentPane());
this.setTitle("JFrame");
}
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJScrollPane(), null);
jContentPane.add(getJButton(), null);
}
return jContentPane;
}
}
class ButtonRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value == null)
return null;
return (Component) value;
}
}