[英]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.