Avoid Multiple Frame opened

67 Views Asked by At

How to Forced Java J Frame application to run only one instance in windows? base on the image link below

[1]: https://i.stack.imgur.com/hKrNu.jpg`enter code here`

public Home() {

    initialize();   
    
}       
public void mouseClicked(MouseEvent e) {
    
}
    
private void initialize() {
    
            

    frame = new JFrame();
    frame.getContentPane().addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            
            
            
            
        }
    });
    frame.getContentPane().setBackground(Color.DARK_GRAY);
    frame.getContentPane().setLayout(null);
    
    txtUsername = new JTextField();
    txtUsername.setBorder(null);
    txtUsername.setBackground(Color.DARK_GRAY);
    txtUsername.setForeground(Color.WHITE);
    txtUsername.addFocusListener(new FocusAdapter() {
1

There are 1 best solutions below

2
John On

You initialize a new JFrame everytime you call the method initialize().

If you want your application to only build one JFrame, create the JFrame object outside the method only one time.

So there should be

JFrame frame = new JFrame();

one time only in your program.

If you want to always create a new JFrame intentionally. You can, before creating a new JFrame call

JFrame.dispose();

to close the previous JFrame