gpt4 book ai didi

java - Jtable ListSelectionListener 不响应 jtable 操作,而是响应同一个类中的另一个 jtable 操作

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:22 30 4
gpt4 key购买 nike

我正在编写一个应用程序包,其中包含一个主类,其中主方法与GUI类分开,GUI类包含一个带有jtabbedpane的jframe,它有两个选项卡,第一个选项卡包含一个jtable,称为jtable1,第二个选项卡包含3个表,称为jtable2,jtable3和jtable4,我已在GUI类构造函数中添加了该构造函数,该构造函数在主类的新实例中被调用,我已在此GUI类构造函数中添加了一个ListSelectionListener第一个 jtable :

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

幸运的是,它运行得很好,对于这样的选择,我还在 GUI 类构造函数中的 jtabbedpane 添加了 ChangeListener,它也运行得很好:

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

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

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

毫无疑问,问题是什么以及如何解决?但如果它不简单,概率是什么或者我该如何解释更多?

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

感谢您的关注和关心

最佳答案

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

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

}

});

关于java - Jtable ListSelectionListener 不响应 jtable 操作,而是响应同一个类中的另一个 jtable 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47569142/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com