0

I am making a GUI in Java and I was wondering how you could make a GUI Window that is already opened reappear to the front of the desktop.

For example, if I press a button the first time, it would open a new window. Every time afterwards that I try to click the button, it just makes the already existing window reappear to the front instead of making a brand new window appear. If I were to close the window and click the button again, it would proceed to create another new window.

Mathew Jacob
  • 35
  • 1
  • 5
  • General idea - to create a singleton instance of this window. If it;s null - create one, else - bring to the front. – Ivan Pronin Jun 01 '17 at 19:55

2 Answers2

0

Here's how I would do it. Create your child JFrame once, and keep it hidden. Whenever the button is pressed, if the child JFrame is hidden, show it, and bring the child frame to the front.

final JFrame child = ...
child.setVisible(false);
child.setDefaultCloseOperation(HIDE_ON_CLOSE);
button.addEventListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        // Show the frame
        child.setVisible(true);
        // Move frame to front
        child.toFront();
        child.repaint();
    }
});
Samuel
  • 16,923
  • 6
  • 62
  • 75
0

That's because, from what I understand, you only have one instance of your window and by pressing a button you are making that same window, reappear at its initial position on the screen.

Write a method that creates an instance of your JFrame with everything you want to include on it. Then add that method to be executed, every time your button is clicked(or pressed) and set your previous window to setVisible(false).

Then every time you press the button you can have a new window appear on the screen. Be careful though, if you are using global variables for what you want to do inside your initial window, using the same variables to initialize the new window, would not give you the result you want. Make sure to use local variables, so when you press the button you can 'reset' everything.

It would be extremely helpful if you posted your code for us to see. It's quite hard trying to understand how your program works, just by your question.

Soutzikevich
  • 991
  • 3
  • 13
  • 29