有 Java 编程相关的问题?

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

java删除重复的JFrame

我有一个JFrame,上面有一个JButton。当点击JButton时,它将创建一个新的框架,因此有两个可见的框架。我想要的是,当我再次单击JButton时,它不会创建一个新的JFrame,而是将旧的框架带到前面

如何检查只创建一个新帧?还是有别的办法


共 (4) 个答案

  1. # 1 楼答案

    最简单的方法是让按钮或按钮的父级跟踪是否创建了新帧。最好的方法是保持对框架的引用

    例如

    public class MyGUI {
    
        private JFrame primaryFrame;
        private JFrame secondFrame;
        private JButton someButton;
    
        public void setupAndDisplay() {
            // initialise the button
            someButton = new JButton("some button");
            someButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    someButtonAction();
                }
            });
    
            // initialise primary JFrame
            primaryFrame = new JFrame("first frame");
            primaryFrame.add(someButton);
            primaryFrame.setVisible(true);
        }
    
        // Like most swing stuff this method is not thread safe, as it expects to 
        // only be called on the EventDispatchThread.
        private void someButtonAction() {
            if (secondFrame == null) { // no frame created yet, so create a new one
                secondFrame = new JFrame("second frame");
                secondFrame.setVisible(true);
            } else { // already have a frame, so bring it to the front
                secondFrame.toFront(); 
            }
        }
    }
    

    这可能不是最好的做事方式。如果你想做一些非常简单的事情,比如一个对话框窗口,那么API很可能有更简单的方法来帮助你。因此,在选择这条道路之前,你应该探索自己的选择,并考虑需要做些什么

    注意。我还没有测试这段代码,只是为了说明如何设置

  2. # 2 楼答案

    你把visible设置为false就这样

  3. # 3 楼答案

    boolean hasWindow = false;
    
    if(hasWindow){
    // show existing window
    hasWindow = true;
    } else {
    // create a new window
    hasWindow = true;
    }
    

    类似于这样的东西