JAVA Swing 中的表格

今天我们来学习一下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被删除了
在这里插入图片描述

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值