【问题标题】:Append Code to method将代码附加到方法
【发布时间】:2015-10-16 16:55:00
【问题描述】:

我是初学者,对 Java 还不是很熟悉,所以解决这个问题可能很简单。

我有一个包含main 方法的MainClass。这个 MainClass 创建了一个 JFrame,里面可以有各种 JPanel。我有一个名为 CommandInput 的类,它创建一个包含 JTextArea 的 JPanel。现在我希望当用户关闭 MainClass 的 JFrame 时,它​​会询问他是否要保存更改。由于 JFrame 中的 JPanel 不同,我真的不想将它包含在 MainClass 中。我知道像 CommandInput 这样的每个“子类”都可以将 windowListener 添加到 MainClass 的 JFrame 中,但这对我来说似乎并不高效:

public class CommandInput {
    public CommandInput(JFrame mainFrame) {
        mainFrame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override //Overwrites the normal behavior of this method
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                System.out.println("Closing Event triggered and detected by CommandInput object");
            }
        });
    }
}

我是否应该在 MainClass 中有一个 WindowAdapter 并将此代码添加到其 windowClosing 方法中?如果是这样,我该怎么做?

【问题讨论】:

  • 不小心评论了,不知道怎么删除cmets :P
  • 感谢@Storm- 的链接,但这并不能完全解决我的问题。我有子类应该将自己的代码添加到 MainClass 的 JFrame 的 windowClosing 事件中,而不需要它们都添加额外的 WindowListener,这可能吗?

标签: java swing events


【解决方案1】:

我现在解决了这个问题,每个子类添加一个接口的匿名内部类,其中包含一个方法,如果 JFrame 可以关闭到一个列表,则该方法返回。仅当列表中的所有匿名内部类都返回 true 时,JFrame 才会关闭:

public interface ClosingListener {
    public boolean allowClosing();
}

public MainClass {
    private ArrayList<ClosingListener> closingListeners = new ArrayList<ClosingListener>();

    public MainClass() {
        JFrame frame = new JFrame();
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                boolean canClose = true;
                for (ClosingListener closingListener : closingListeners) {
                    if (!closingListener.allowClosing()) {
                        canClose = false;
                        break;
                    }
                }

                if (canClose) {
                    System.exit(0);
                }
            }
        });
    }

    public void addClosingListener(ClosingListener closingListener) {
        closingListeners.add(closingListener);
    }
}

【讨论】:

    【解决方案2】:

    也许你需要这个

    addWindowListener(new WindowAdapter(){
                    public void windowClosing(WindowEvent e){
                    int choice = JOptionPane.showConfirmDialog(null, "Save changes?");
                    if(choice==0) System.exit(0);
                    }
    });
    

    【讨论】:

    • 不抱歉,我宁愿寻求一种方法来修改他的 windowClosing 方法,而不是为 JFrame 的每个组件添加一个新的 WindowListener 到 JFrame。
    猜你喜欢
    • 2015-04-17
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多