今天我们来学习一下java swing中的表格怎么来使用
在用swing技术开发系统的时候, 有时候会需要用到表格,那么我们来看看表格是怎么使用的
public class Table1 extends JFrame implements ActionListener{
private JPanel panelBody = null;
private JTable table = null;
private JScrollPane scrollPane = null;
private DefaultTableModel tableModel = null;
private JButton button = null;
private void init() {
this.panelBody = (JPanel) this.getContentPane();
this.panelBody.setLayout(new BorderLayout());
//二维数组 表格中数据
String[][] data = new String[][] {{"aaa","aaa","aaa"},{"bbb","bbb","bbb"},{"ccc","ccc","ccc"}};
//一维数组 表格标题
String[] title = new String[] {"name","address","number"};
this.tableModel = new DefaultTableModel(data, title);
this.table = new JTable(this.tableModel);
this.scrollPane = new JScrollPane(table);
this.button = new JButton("Button");
this.button.addActionListener(this);
this.panelBody.add(this.button,BorderLayout.SOUTH);
this.panelBody.add(this.scrollPane, BorderLayout.NORTH);
this.setTitle("测试");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Table1() {
this.init();
}
public static void main(String[] args) {
Table1 table1 = new Table1();
table1.setBounds(50, 50, 300, 500);
table1.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.button) {
// System.out.println(this.tableModel.getColumnCount());//得到列数
// System.out.println(this.tableModel.getRowCount());//得到行数
// System.out.println(this.table.getSelectedColumnCount());//得到选中的列数
// System.out.println(this.table.getSelectedRowCount());//得到选中的行数
System.out.println(this.tableModel.getValueAt(this.table.getSelectedRow(), 0));
this.tableModel.removeRow(this.table.getSelectedRow());//删除某一行
}
}
}
在这里 我想声明一下,Table必须和TableModel结合一起使用,因为要操作表格中的数据 只能使用TableModel,还有,要显示标题,必须使用ScrollPane,然后把表格加到scrollPane,最后把ScrollPanej加到panelBody上,否则标题加不上去
结果如下:
当我点击ccc的时候,点击button 可以看到 ccc被删除了