简体   繁体   中英

How i don't show same window more than one at a time

In my project, I create some buttons. When a button is clicked then a frame is appeard. But when I click the same button then the same window is come again. It will decrease my project quality. I want that when next time the same button is clicked then the frame is not come because the frame is already visible. How can I do that?

It depends on how you've implemented it. Instead of creating a new frame every time, keep a reference to it, and if it's already been created just show the existing one.

Here's a simple example. It's a frame that has two buttons. One of them creates a new frame every time, and the other one creates a frame the first time you click it, and any time after that will just show that one frame.

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

class test {

  public static void main(String[] args) {

    JFrame main = new JFrame("Test");

    JButton btnAlways = new JButton("Always");
    JButton btnOnce = new JButton("Once");

    btnAlways.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          JFrame frame = new JFrame(new Date().toString());
          frame.setSize(400, 300);
          frame.setVisible(true);
        }
      }
    );

    btnOnce.addActionListener(
      new ActionListener() {
        JFrame frame = null;

        public void actionPerformed(ActionEvent e) {
          if (frame == null) {
            frame = new JFrame(new Date().toString());
            frame.setSize(400, 300);
          }
          frame.setVisible(true);
        }
      }
    );

    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.getContentPane().add(btnAlways, BorderLayout.NORTH);
    main.getContentPane().add(btnOnce, BorderLayout.SOUTH);
    main.setSize(300, 100);
    main.setVisible(true);

  }
}

The listener for btnOnce has a frame field initially set to null . The first time you click the button, it will go through the if (...) {...} , create a frame, and assign it to the frame field, so that subsequent invocations don't have to, rather they will use the stored value.

一种可能的方式是使用SingleTone设计图案用于使用所述帧class..access getInstance()方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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