So I currently have a program that has 2 windows extending JFrame
.
The Main window has a button opening a new window (Window 2). Window2
has its own defined class with widgets and listeners. At the moment if I press the button in the Main frame more than once whilst the second window is still open then it would switch to that window, without creating a new one (which is exactly what I want).
The 2nd window also has some widgets, a search field and a table that's populated according to what the user types in the JTextField
. The problem is that once I close Window2
and press the button in the Main window to re-open it, the same window appears with the previously entered text in the search field and the populated table.
The thing is, I want to make it so that once Window2
is closed and re-opened then I create a completely new instance of Window2
with an empty search field and table. I thought this would work with JFrame.DISPOSE_ON_CLOSE
but it didn't.
A bit of my code might explain this better:
public class MainWindow extends JFrame{
/*
* create widgets and panels in Main window
*/
private Window2 ww = null;
Button.addActionListener(new ActionListener() { // the button that opens
//a new window
@Override
public void actionPerformed(ActionEvent e) {
if (ww==null) { //creating the new window here
ww = new Window2();
ww.setTitle("Window2");
ww.setSize(600, 400);
}
ww.setVisible(true);
});
}
/*
* Window 2
*/
public class Window2 extends JFrame {
//add widgets and listeners
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
There are a number of ways you might achieve this, the simplest would be to check to see if the window is visible or not, for example...
public void actionPerformed(ActionEvent e) {
if (ww==null || !ww.isVisible()) {
ww = new Window2();
ww.setTitle("Window2");
// You should be using pack
ww.setSize(600, 400);
}
ww.setVisible(true);
}
Now, having said that, it's generally discouraged to use multiple frames in this way, as it's confusing to users, especially when they might already have multiple windows open doing other things, the other frames can become "lost".
You should consider using a modal dialog, forcing the user to complete the work with the dialog and close it when they have finished. This will stop the user from interacting with the parent window until the dialog is closed or make use of a CardLayout
or JTabbedPane
, allowing you to switch between views based on your needs.