JTable焦点问题
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());
}};
选中一行在TextFiled中显示内容
可是这样的话第一次选中时能正确显示,但一个表中切换行时,TextFiled中的内容不跟着更新,还是原来的。
怎么办?
------解决方案--------------------实现了,不过会调用两次, 不过只设置TextFiled的内容倒还不影响,或你自己再想想办法
package untitled1;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2007</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
class DemoTable extends JTable{
public DemoTable(Object[][] a,Object [] b){
super(a,b);
}
public void valueChanged(ListSelectionEvent e)
{
System.out.println("OK");
}
}
//主要就是这里,自己重写的JTable类
public class Frame1 extends JFrame {
JPanel contentPane;
JPanel jPanel1 = new JPanel();
BorderLayout borderLayout1 = new BorderLayout();
JScrollPane jScrollPane1 = new JScrollPane();
Object[] data ={"one", "two", "three", "four"};
Object[][] d={{"five", "six", "seven", "eight"},
{"nine", "ten", "eleven", "twelve"},
};
DemoTable jTable1=new DemoTable(d,data);
public Frame1() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Component initialization.
*
* @throws
java.lang.Exception */
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(452, 369));
setTitle("Frame Title");
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(11, 5, 366, 262));
jPanel1.setLayout(borderLayout1);
contentPane.add(jPanel1);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jScrollPane1.getViewport().add(jTable1);
}
}
------解决方案--------------------我还以为要把table的值刷新后触发事件了
不要用addFocusListener,Focus事件只发生一次,除非你的Focus离开了jtable,日然后再重新选择jtable时才会触发,一旦聚焦在jtable以后就不会在触发focus事件了。所以可以改用addListSelectionListener
your_table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int hang=jTable1.getSelectedRow() ;
if (hang > -1) {
txtCode.setText(jTable1.getValueAt(hang,0).toString());
txtDetails.setText(jTable1.getValueAt(hang,1).toString());
}
}
});
如果是刷新表以后触发事件,可以用addTableModelListener
your_table.getTableModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
int hang=jTable1.getSelectedRow() ;
if (hang > -1) {
txtCode.setText(jTable1.getValueAt(hang,0).toString());
txtDetails.setText(jTable1.getValueAt(hang,1).toString());