【发布时间】:2020-08-23 03:40:24
【问题描述】:
我正在开发一个非常复杂的多层 Swing GUI,我现在遇到的主要问题是让 JButton ActionListener 在单独的 JFrame 上执行 setVisible() 并立即 dispose() 当前框架。由于我的代码很长,重要的是 main、JFrame 和 ActionListener 都被拆分为单独的类文件。我为我的问题写了一个非常简化的版本,分成 4 个小类文件。他们在这里:
文件 1:
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame g1 = new GUI1();
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
}
}
文件 2:
import javax.swing.*;
public class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1() {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener());
add(panel);
add(button);
}
}
文件 3:
import javax.swing.*;
public class GUI2 extends JFrame {
JPanel panel;
JLabel label;
public GUI2() {
super("GUI2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("I'm alive!");
add(panel);
add(label);
}
}
文件 4:
import java.awt.event.*;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GUI2.setVisible(true);
GUI1.dispose();
}
}
如您所见,ActionListener 的唯一功能是将 GUI2 设置为可见并处理 GUI1,但它运行错误“非静态方法 (setVisible(boolean) 和 dispose()) 无法从静态上下文”。我认为这是因为这两种方法都试图引用在 main 中创建的对象,这是静态的。我的困惑是如何解决这个问题,而不是将所有内容组合到一个类中。
有什么建议吗?谢谢!
编辑: 这是编译到一个文件中的上述代码......虽然它返回完全相同的错误。
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame g1 = new GUI1();
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
}
}
class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1() {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener());
add(panel);
add(button);
}
}
class GUI2 extends JFrame {
JPanel panel;
JLabel label;
public GUI2() {
super("GUI2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("I'm alive!");
add(panel);
add(label);
}
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GUI2.setVisible(true);
GUI1.dispose();
}
}
【问题讨论】:
-
"一个单独的 JFrame" 1) 见The Use of Multiple JFrames, Good/Bad Practice? 2) 为尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 * 看注释。 3) 更具体地说.. “在单独的 JFrame 上执行 setVisible() 并立即对当前 JFrame 进行 dispose()。” 使用
CardLayout,如 this answer 所示。 -
* 注意:这里的问题不是代码量,而是有4个
public类。将带有main(String[])方法的类保留为公共,将其他类降级为默认访问(即删除public说明符)并将它们粘贴到主类之后以启用单个复制/粘贴以查看它的工作(或失败)。
标签: java swing actionlistener