最近幫朋友做了個GUI,其中用到了JTable,這個以前不怎麼用,這次因爲業務需要查閱資料,學到不少,因爲知識點較爲零碎,現總結一下,方便以後查閱。
1:表的創建
Object [][]cells=new Object[0][0]; //創建一個初始行列都爲0的表
String[] colname={"代碼","名稱"}; //列名
table=new JTable(cells,colname); //實例化
2:得到當前選中行 int hang=table.getSelectedRow() ;
3: 得到某行某列的字符串形式內容 String str=table.getValueAt(0,0).toString(); //例中得到0行0列的單元格內容
4:添加焦點監聽器 addFocusListener(new FocusListener(){});
裏面常重寫兩個方法來實現自己的需求
public void focusGained(FocusEvent e){} //得到焦點時的動作
public void focusLost(FocusEvent e) { //當點擊表以外其他可以聚焦的組件時的失去焦點動作
if (!e.isTemporary()) {
jTable1.clearSelection();
}
}
5:比如要使選中行的內容動態的顯示在一個文本框中時,因爲當在一個表中切換行時焦點始終在表中,文本框不能隨着切換而動態改變,只會顯示第一次聚焦表時的內容,除非點擊別處使表失去焦點再點回表重新獲得焦點,文本框纔會改變。那麼要在表中連續切換行時實現文本框的動態改變怎麼辦?至今我沒有找到好的解決途徑,我的方法是每次選中某行觸發獲得焦點事件的最後使焦點移到表以外的地方,那麼即使連續點擊其他行,都相當於從表外移進的,文本框都會動態顯示。這點要結合4中的監聽器如:
jTable1.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent e) {
int hang=jTable1.getSelectedRow() ;
txtCode.setText(jTable1.getValueAt(hang,0).toString());
txtDetails.setText(jTable1.getValueAt(hang,1).toString());
txtDetails.requestFocus(true);
}
public void focusLost(FocusEvent e) {
if (!e.isTemporary()) {
jTable1.clearSelection();
}
}
});
6:移出某一行 ((DefaultTableModel)jTable1.getModel()).removeRow(0);//例中爲移除第0行
7:得到表的行數 int count=((DefaultTableModel)jTable1.getModel()).getRowCount();
8:給表增加行 ,可用Vector,如:
Vector vector=new Vector();
vector.add(rs.getString(1).toString());
vector.add(rs.getString(2).toString());
((DefaultTableModel)jTable1.getModel()).addRow(vector);
9:使某一行處於高亮被 選中狀態
jTable1.setRowSelectionInterval(int n,int m); //使從n行到m行處於被選中狀態,如果只選中一行,則n和m值相等。如:jTable1.setRowSelectionInterval(0,0); //使首行選中