[英]Listeners to dynamically created Swing Components
I am dynamically creating jTABLES
. 我正在动态创建
jTABLES
。 The number of jTABLES
depends on the database. jTABLES
的数量取决于数据库。
while(rset.next())
{
//Create Scroll Pane
JScrollPane newScrollPane = new JScrollPane();
//Create Table
JTable newTable = new JTable();
//Add Table to Scroll Pane
newScrollPane.setViewportView(newTable);
//Add Scroll Pane to a Tabbed Pane
jTabbedPane1.addTab(rset.getString(1),newTable);
}
I need to add MouseListener
to each jTABLE
, it is basically the same Listener, same actions. 我需要将
MouseListener
添加到每个jTABLE
,它基本上是相同的侦听器,相同的操作。
while(rset.next())
{
//Table Created.....
newTable.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
String data = newTable.getValueAt(0,0).toString();
}
//More Abstract Methods...
});
}
Netbeans, forces me to make new Table final
, and as far as I know, that final
variables cannot be changed later, is there something wrong here? Netbeans迫使我将新Table设为
final
,据我所知, final
变量以后不能更改,这有什么问题吗? Am I doing this the right way? 我这样做正确吗?
When you are using a variable(outside variable) inside annonymous inner classes, it is necessary that it is declared final. 当您在匿名内部类中使用变量(外部变量)时,有必要将其声明为final。 That's why netbeans is forcing you to do it.
这就是netbeans强迫您这样做的原因。
Final variables can't be changed later but do you need to change the final local variables out of the while
loop? 最终变量以后不能更改,但是您是否需要在
while
循环之外更改最终局部变量?
If yes carete an array or list and store the references there. 如果是,插入数组或列表,然后将引用存储在那里。
final is required to use the reference in anonimous inner class (your listener). 在匿名内部类(您的侦听器)中使用引用需要final。
What you can do to avoid the final problem: 可以避免出现最后问题的方法:
Create another class that implements MouseListener. 创建另一个实现MouseListener的类。
class MyMouseListener extends MouseListener {
JTable table;
public MyMouseListener(JTable table) {
this.table = table;
}
Then use that table in any of the methods. 然后以任何一种方法使用该表。
public void mouseClicked(MouseEvent e) {
String data = table.getValueAt(0,0).toString();
}
then add that mouse listener to the table. 然后将该鼠标侦听器添加到表中。
myTable.addMouseListener(new MyMouseListener(myTable));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.