简体   繁体   中英

Listeners to dynamically created Swing Components

I am dynamically creating jTABLES . The number of jTABLES depends on the database.

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.

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? 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. That's why netbeans is forcing you to do it.

Final variables can't be changed later but do you need to change the final local variables out of the while loop?

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).

What you can do to avoid the final problem:

Create another class that implements 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM