簡體   English   中英

如何在實現 ActionListener 的 class 上關閉 JFrame

[英]How to close a JFrame on a class that implements ActionListener

我需要用另一個實現 ActionListener 的 class 關閉特定的 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();
                }
            }
        }); 
    }
}

我將使用這個 class 到那個 JFrame 上的 JButton。(就像 controller 到 JButton)

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

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

每個可搜索的方法。 我一直在尋找至少 5 個小時。

我們將從如何編寫 ActionListener 的基礎知識開始。 您發布的代碼甚至沒有實現actionPerformed(...)方法,因此它甚至無法編譯。

閱讀Swing 教程,了解 Swing 基礎知識。 也許從How to Use Lists部分開始。 ListDemo代碼顯示了如何使用內部 class 來定義 ActionListener。

你的 controller class 對我來說毫無意義。 你似乎讓它變得復雜。 例如,為什么要將按鈕作為參數傳遞,但還要在 class 中創建按鈕的新實例。

ActionListener 不會定義按鈕或將其作為參數傳遞。

您需要做的就是創建按鈕,將所有其他組件添加到框架中。 然后將 ActionListener 添加到您的按鈕。

那么你的 ActionListener 中的基本代碼將是:

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

一旦你開始工作並理解了基本概念,你可能想查看關閉應用程序,它提供了一個簡單的 API 來創建可用於任何框架的可重用代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM