繁体   English   中英

如何判断JFrame窗口是否已经打开?

[英]How to tell if a JFrame window has already been opened?

我有一个带有ButtonJFrame ,可以打开另一个JFrame 但我想按钮只打开第二帧一次 问题是,每次单击它都会得到框架的新实例。 肯定是一个非常普遍的问题,因为我正在关注一本有关如何创建此GUI的书。 我发现作者没有提到此“功能”很奇怪。

那么如何避免打开新框架的多个副本呢?

您应该保留对您第一次打开的子框架的引用。 在第二次您首先检查您是否有参考,然后决定创建一个新框架或将焦点放在现有的打开框架上。

示例作为对OP注释的答案 (类似于@AlexanderTorstling的其他答案,但未立即创建子框架):

class MainFrame extends JFrame {
  private JFrame subFrame = null;

  MainFrame() {
    ...
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
         if (subFrame == null) {
           subFrame = new JFrame();
           ...
         }
         subFrame.setVisible(true);
      }
    });    
  }
}

此示例还具有一个优点,即如果关闭了主框架,则可以通过注册的WindowAdapter关闭子帧。

不要让按钮每次都创建一个新的JFrame,而是让第二个JFrame成为第一个JFrame的成员,只让按钮调用jframe2.setVisible(true);

class JFrame1 {
   JFrame2 jframe2=...;
   JButton button=...;

   JFrame1() {
     ...
     button.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
         jframe2.setVisible(true);
       }
     });
     ...
   }
}

更新!

尝试这个:

JFrame frame2 = new JFrame(); // instance variable

...

//when button is clicked
button.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        if(!frame2.isVisible())
            frame2.setVisible(true);
    }
});

确保像这样手动处理所有JFrame的关闭:

frame2.addWindowListener(new WindowAdapter() {

    @Override
    public void windowClosing(WindowEvent e) {
        // handle closing the window
        frame2.setVisible(false);
        frame2.dispose();
    }
});

而不是使用JFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

希望这可以帮助。

  please try this one 

  JFrame frame2 = new JFrame(); // instance variable
   boolean secondWindowIsOpne = false;

   ...

  //when button is clicked
  button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
    if(secondWindowIsOpne == false){
        frame2.setVisible(true);
        secondWindowIsOpne  = true;
    }
    else{
      System.out.println("This Window is already running");

  }
   });

    make sure you are handling the closing of all of the JFrames manually like this: 
   frame2.addWindowListener(new WindowAdapter() {

@Override
public void windowClosing(WindowEvent e) {
    // handle closing the window
      secondWindowIsOpne = false;
    frame2.setVisible(false);
    frame2.dispose();
}

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM