我有两个类 GUI(呈现我的主要 JFrame)和打印类(由 JButton 在 GUI 类上调用)。现在在我的 GUI 类上我有 JTextArea 和一个方法:
void setOutput(String data)
{
// output is JTextArea
output.setText(data);
}
但是,数据是在 Print JFrame 中提供的,其中我有一个带有 Action 监听器的 JButton:
sizOpt.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
// textfield is a JTextField component
String data = textfield.getText();
// My problem is here i need to invoke the setOutput
// method in GUI to output the string however i cant call that method in
// any way but making it static or calling new GUI which will create a new
// Instance of GUI class
GUI.setOutput(data);
}
});
最佳答案
答案:根本不要在这里使用 static 任何东西。
唯一应该是静态的是您的 main 方法,可能就是这样。如果您需要在 GUI 上调用方法,请在可视化 GUI 的实例 上调用它,而不是作为静态方法调用。通常,棘手的部分是获取有效引用,您不应该创建新的 GUI 对象是正确的,但同样不要尝试执行非工作静态解决方案。获取有效引用的一些方法是通过构造函数参数或 setter 方法。
即,
public class PrintJFrame extends JFrame {
private GUI gui;
public PrintJFrame(GUI gui) {
this.gui = gui;
}
// ...
}
现在,在您的 ActionListener 中,您可以在 gui 变量持有的正确 GUI 引用上调用一个方法。接下来我们将讨论为什么您应该避免让类扩展 JFrames 和类似的 GUI 组件。 接下来我们'
关于java - 分配非静态变量的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13597491/