有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何关闭实现ActionListener的类上的JFrame

我需要用另一个实现ActionListener的类关闭一个特定的JFrame

public class EditStudent extends JFrame {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    EditStudent frame = new EditStudent();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }); 
    }
}

我将使用这个类在JFrame上创建一个JButton。(就像是一个JButton的控制器)

public class EditFileController implements ActionListener {
    @SuppressWarnings("unused")
    private JButton btnEdit = new JButton();

    public EditFileController(JButton btnEdit) {
        super();
        EditStudent.btnEdit = btnEdit;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    Every searchable method. I've been searching for at least 5 hrs.

    我们从如何编写ActionListener的基础知识开始。您发布的代码甚至没有实现actionPerformed(...)方法,因此它甚至无法编译

    阅读Swing tutorial了解Swing基础知识。也许可以从How to Use Lists一节开始。代码显示了如何使用内部类来定义ActionListener

    你的控制器类对我来说毫无意义。你似乎让事情变得复杂了。例如,为什么要将按钮作为参数传递,但还要在类中创建按钮的新实例

    ActionListener不需要定义按钮或将其作为参数传递

    您只需创建一个按钮,将所有其他组件添加到框架中。然后将ActionListener添加到按钮中

    那么ActionListener中的基本代码是:

    Window window = SwingUtilities.windowForComponent(event.getSource());
    window.dispose();
    

    一旦你开始工作并理解了基本概念,你可能想看看Closing an Application,它提供了一个简单的API来创建可用于任何框架的可重用代码