Button多次打开新的JFrame。我怎么阻止这个?

时间:2012-08-14 11:15:40

标签: java swing window jframe jpanel

我正在使用不同的类:一个拿着带有按钮的主JFrame,另一个拿着一个按下按钮时调用的新JFrame。

if( event.getSource() == noteBtn ) { MiniPad.pad(); return;}

(MiniPad.pad()引用新JFrame上的class和pad()方法)

当我在托管该按钮的JPanel上删除所有(),然后重新验证()和重绘()时,该按钮多次打开JFrame,这根本不是我想要它做的。

有没有办法告诉MiniPad类,你不能同时打开多个JFrame副本?顺便说一句,我会扩展JFrame,如果有任何帮助的话。

2 个答案:

答案 0 :(得分:4)

编辑:以下所有内容都是有效的编程知识,但您可能还需要考虑让MiniPad扩展JDialog类。我之前没有使用它,但它的实现看起来很像JFrame。您MiniPad课程实际上可能不需要做太多改动。文档在这里:http://docs.oracle.com/javase/7/docs/api/javax/swing/JDialog.html

如果您想知道原因,请查看Andrew Thompson的帖子here

-

根据我对您的问题的理解,MiniPad扩展了JFramepad()方法创建了MiniPad类的新实例。最简单的解决方案是将MiniPad类(至少通过pad()方法)转换为单例。单例是一种类,其中在任何给定时间只能存在一个实例(或对象)。通过调用静态方法(在本例中为pad()),您可以检查对象的实例是否已存在;如果是这样,只需使用现有对象:

public class MiniPad extends JFrame {

    //whatever code you have

    private static MiniPad padInstance = null; //the singleton instance of your MiniPad

    public static MiniPad pad() {
        if(padInstance == null)
            padInstance = new MiniPad();
        //If you want to reset the object every time you call the method for whatever reason, do it here
        pad.setVisible(true); // I believe this is all you want to do
    }
}

这应该做你想要的。通过调用pad()方法,只会显示一个MiniPad

但是,如果我读错了你的问题,请告诉我,我会修改我的答案。

单身人士信息: http://en.wikipedia.org/wiki/Singleton_pattern

答案 1 :(得分:3)

最佳解决方案是打开modal dialog而不是框架。有关详情,请参阅The Use of Multiple JFrames, Good/Bad Practice?