[英]table generation runtime and mouse click event with jtable
您好開發人員,我在jframe中使用兩個按鈕和一個表,當我單擊按鈕時,應生成具有不同行數的新表,並且在單擊表行時,當我單擊時,它應再次顯示行和列數另一個按鈕應創建具有新行數的新表,再次單擊該表應顯示行號和列號
我正在使用以下代碼。 第一次創建表時,它會生成正確的結果,但是當再次創建表時,在單擊任何行時,它將給出行號和列號-1。 和數組索引超出范圍異常我的代碼plz幫助有什么問題
JTable table;
JScrollPane jsp;
Button b1 = new JButton("1");
Button b2 = new JButton("2");
add(b1);
add(b2);
b1.addActionListener (this);
b1.addActionListener (this);
public void actionPerformed(ActionEvent ae) {
int i = 0;
if (ae.getActionCommand().equals("1")) {
i = 1;
}
if (ae.getActionCommand().equals("2")) {
i = 2;
}
String title[] = {""};
Object obj[][] = new Object[i][1];
table = new JTable(obj, title);
jsp = new JScrollPane(table);
add(jsp);
table.addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me) {
// first time it returns the true result but on new table creation
//i and j are returned -1 .
int i = table.getSelectedRow();
int j = table.getSelectedColumn();
System.out.println("i is" + i);
System.out.println("j is" + j);
}
此示例還有其他一些問題,但是要解決您的直接問題,您需要獲取MouseEvent
的源並對其進行操作:
public void mouseClicked(MouseEvent me) {
// first time it returns the true result but on new table creation
//i and j are returned -1 .
JTable table = (JTable)me.getSource();
int i = table.getSelectedRow();
int j = table.getSelectedColumn();
System.out.println("i is" + i);
System.out.println("j is" + j);
}
問題出在您的ActionListener
您正在將table
重新分配給新表(未選擇任何行)。 因此,如果您單擊第一個表,它仍將對第二個表(未選擇任何行)進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.