gpt4 book ai didi

另一个类中的 Java jbutton

转载 作者:行者123 更新时间:2023-11-30 03:29:13 26 4
gpt4 key购买 nike

我正在尝试在类中创建一个按钮,从表中删除某些内容。当它不在单独的类(class)中时,我可以让它工作。但是,当我尝试将代码移至新类并在主方法中创建该类的对象时,该按钮不起作用。我对使用 Swing 还很陌生,因此我们将不胜感激。

public abstract class RemoveButton extends frame implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
if (table.getSelectedRow() == -1) {
if (table.getRowCount() == 0) {
Mess.setText("Table is empty");
} else {
Mess.setText("You need to select");
}
} else {
model.removeRow(table.getSelectedRow());
}
}
}
}

此类是用于删除访客的按钮。我扩展了框架,因为那是我的大部分变量所在的地方。从这里开始,我不太确定如何将其调用到我的主要方法并使其正常工作。所有导入均已添加。

最佳答案

我要在这里猜测,因为目前编写的问题不完整,所以我们被迫这样做,但我怀疑您滥用了继承。我猜你的主 GUI 由框架类(应该重新命名以符合 Java 标准,以便它的第一个字母是大写)保存,并且这样做是为了让这个类可以调用方法和访问字段的框架类。如果是这样,那么您使用继承的目的是错误的,因为RemoveButton 持有的“frame”实例是唯一的,并且与显示的框架实例完全不同。

相反,您应该向此类传递对实际显示的框架对象的引用,然后根据需要调用该对象的方法。

例如,

// why abstract? I've removed that
// no longer extends frame
public class RemoveButton implements ActionListener {
// I've renamed your frame class to "MyFrame"
private MyFrame myFrame;

// constructor that allows you to pass in MyFrame reference
public RemoveButton(MyFrame myFrame) {
this.myFrame = myFrame; // assign to field
}

public void actionPerformed(ActionEvent evt) {
JTable table = myFrame.getTable(); // give MyFrame this method
DefaultTableModel model = (DefaultTableModel) table.getModel();
// .... etc
}
}

更简洁的方法是使用 MVC 设计模式,但这需要更多的前期工作。

关于另一个类中的 Java jbutton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29451067/

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