Jtable ListSelectionListener不响应jtable操作并响应另一个jtable操作,在同一个类中

问题描述 投票:1回答:1

我正在编写一个应用程序包,其中包含一个主类,其中主要方法是从GUI类中分离出来的,GUI类包含一个带有jtabbedpane的jframe,它有两个选项卡,第一个选项卡包含一个jtable,称之为jtable1,第二个tab包含3个表,称之为jtable2,jtable3和jtable4,我已经在主类的新实例中调用的GUI类构造函数中添加了,我在这个GUI类构造函数中添加了一个ListSelectionListener到第一个jtable:

    jTable1.getSelectionModel().addListSelectionListener((ListSelectionEvent event) -> {
        // do some actions here, for example
        /* my code */
    });

并且通过良好的命运,它对这样的选择非常有效,并且我还将ChangeListener添加到GUI类构造函数中的jtabbedpane,该构造函数也非常有效:

  jTabbedPane1.addChangeListener((ChangeEvent e) -> {
        /* my code */
  });

但是当我试图在GUI类构造函数中将ListSelectionListener添加到第一个表(我们称之为jtable2)时,在第二个选项卡中包含三个表并将ListSelectionListener添加到它们中,它不响应任何选择,并且将ListSelectionListener添加到jtable2的代码是:

    jTable2.getSelectionModel().addListSelectionListener((ListSelectionEvent event) -> {
        System.out.println("jTable2 Selected");
        /* mycode */
    });

毫无疑问,问题是问题是什么以及如何解决?但如果不简单,可能性是什么,或者我如何解释更多?

注意:ListSelectionListener的添加将在第二个选项卡(jtable3和jtable4)中的其他表上完成,并且它将被添加到愿意创建的其他计划选项卡并包含表

感谢您的关注和关怀

java swing jtable listselectionlistener
1个回答
0
投票

问题是在jTabbedPane更改中重新创建未侦听的操作的jtable,因为在每个选项卡更改中,我重新创建jtable以使用其他选项卡的jtables中新输入的信息更新它:

 jTabbedPane1.addChangeListener((ChangeEvent e) -> {
   if(jTabbedPane1.getSelectedIndex() == 1)
   {
         jTable2 = new javax.swing.JTable(){
               DefaultTableCellRenderer renderRight =
               new DefaultTableCellRenderer();

               { // initializer block
                   renderRight.setHorizontalAlignment(SwingConstants.RIGHT);
               }

               @Override
               public TableCellRenderer getCellRenderer (int arg0, int arg1)                                       
               {
                   return renderRight;
               }
               public boolean isCellEditable(int row, int column) {
                   return false;
               };


           }});

           jTable2.setAutoCreateRowSorter(true);
           jTable2.setFont(new java.awt.Font("Traditional Arabic", 0, 23));
           jTable2.setRowHeight(25);

           DefaultTableModel workersJtableForFamilyModel = 
           new DefaultTableModel();

           /* update model with columns and rows, and set it */
    }

 });

因此,问题在于重新创建jtable,因此内存中的已侦听和观察的jtable对象会因指向和侦听而丢失,因此解决方案是更新jtable的模型而不创建新的jtable对象,然后将其设置为jtable:

 jTabbedPane1.addChangeListener((ChangeEvent e) -> {
   if(jTabbedPane1.getSelectedIndex() == 1)
   {    
           DefaultTableModel workersJtableForFamilyModel = 
           new DefaultTableModel();

           /* Feed the model with new columns and rows */
           /* write updated Model prepration statements */

           /* set the updated model to the jtable */
           jTable2.setModel(workersJtableForFamilyModel);

    }

 });
© www.soinside.com 2019 - 2024. All rights reserved.