标签:
失去焦点退出编辑状态;
table.setClientPerpoty("terminateEditOnFocusLost",true);
设置部分列不可编辑;
自定义tableModel重写 isCellEditable 方法;
刷新Jtable的数据:
table.setModle(modle);
删除数据:
model.remove(int row);
获取jtable 中的值:
jtable1.getValueAt();
排序 sorter
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(dtm);
jtable1.setRowSorter(sorter);
具体实现看代码:窗体启动时,没有显示内容。
package com.bdc; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; public class JTableTest extends JFrame { String[][] data={{"aaa","111"},{"bbb","222"},{"ccc","333"}}; String[] cols= {"user","password"}; DefaultTableModel dtm; JTable jtable1; public JTableTest() { //设置基本属性 setAlwaysOnTop(true); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(300,300); //添加组件 jtable1= new JTable(dtm); jtable1.putClientProperty("terminateEditOnFocusLost", true); //失去焦点时退出编辑状态,点击修改按钮时才能获取修改后的值; add(jtable1); JScrollPane jsp= new JScrollPane(jtable1); add(jsp); JPanel jp1=new JPanel(); add(jp1,BorderLayout.SOUTH); JButton listAll=new JButton("显示所有"); jp1.add(listAll); JButton delete=new JButton("删除"); jp1.add(delete); JButton modify=new JButton("修改"); jp1.add(modify); //添加事件监听; listAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //自定义一个TableModel,重新isCellEditable,设定为第一列不可编辑; dtm=new DefaultTableModel(data,cols){ @Override public boolean isCellEditable(int row, int column) { return column==1?true:false; } }; //创建一个排序器,设为table的排序属性; 点击列名时即可实现排序功能。 TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(dtm); jtable1.setRowSorter(sorter); jtable1.setModel(dtm); } }); delete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int a=jtable1.getSelectedRow(); dtm.removeRow(a); //删除某一行; jtable1.setModel(dtm); } }); modify.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int aa=jtable1.getSelectedRow(); int bb=jtable1.getSelectedColumn(); if (aa==-1) { return; } JOptionPane.showMessageDialog(JTableTest.this, "成功修改为"+jtable1.getValueAt(aa, bb)); } }); } public static void main(String[] args) { new JTableTest().setVisible(true); } }
标签:
原文地址:http://www.cnblogs.com/iplain/p/5862294.html