标签:
编写该JTable的TableModel的String getColumnName(int columnIndex)方法
//传进来的是列的索引值
//返回该列的列名/
/给JTable设置好TableModel后,这个方法由系统自动调用
//显示在JTable中
public String getColumnName(int columnIndex){
return "你想要设置的对应列的列名";
}
eg.:
public String getColumnName(int columnIndex){
if(columnIndex == 1)
return "索引值为 1 的列的名字";
if(columnIndex == 2)
return "索引值为 2 的列的名字";
...
}
package swing.table; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.TableColumnModel; public class TestTable extends JFrame { private static final long serialVersionUID = 1L; JTable tb; JPanel p = new JPanel(); public TestTable() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(112, 0); setSize(700, 420); final Object[] columnNames = { "档案号", "姓名", "年龄", "性别", "婚姻状况", "职业", "联系电话" }; Object[][] rowData = { { "010110", "张三", "28", "男", "已婚", "教师", "13686562936" }, { "010110", "李四", "28", "男", "已婚", "教师", "13686562936" } }; tb = new JTable(rowData, columnNames) { private static final long serialVersionUID = 1L; // 添加部分1 public boolean isCellEditable(int row, int column) { return false; } }; tb.setPreferredScrollableViewportSize(new Dimension(639, 232)); // tb.setEnabled(false); tb.setRowHeight(20); tb.setRowSelectionAllowed(true); tb.setSelectionBackground(Color.lightGray); tb.setSelectionForeground(Color.white); tb.setGridColor(Color.black); tb.setShowGrid(true); tb.setShowHorizontalLines(true); tb.setShowVerticalLines(true); tb.setBackground(Color.white); // 添加部分2 tb.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) {// 双击鼠标 if (e.getClickCount() == 2) { int colummCount = tb.getModel().getColumnCount(); // 列数 for (int i = 0; i < colummCount; i++){ System.out.print(tb.getModel().getColumnName(i)+":"); System.out.print(tb.getModel().getValueAt(tb.getSelectedRow(), i).toString() + " "); } System.out.println(); } } } }); JScrollPane pane = new JScrollPane(tb); pane.setBackground(Color.white); p.add(pane); add(p); setVisible(true); } public static void main(String[] args) { new TestTable(); } }
标签:
原文地址:http://www.cnblogs.com/softidea/p/4535890.html