Reputation: 3115
My program launches a JFrame from an already running parent JFrame. The second JFrame has autonomy from the first except for one condition - I require a button in the parent JFrame to be disabled when (and only when) the second JFrame is open to prevent additional JFrames being launched.
So my question is, how can I listen to the second JFrame's 'existence' from the parent JFrame in order to manipulate whether my button is active or not?
My parent JFrame launches the secondary JFrame as follows:
try {
second_frame Jframe = new second_frame(variable);
Jframe.second_frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
followed by:
btn_open.setEnabled(false);
to disable the button once the second JFrame has been launched.
So how can I now listen to the second JFrame's window status from the first JFrame in order to re-enable the btn_open button.
Upvotes: 1
Views: 1317
Reputation: 4188
One way is to add a WindowListener
to the second frame. You can call button.setEnabled()
every time the frame closes or opens. (There are implemented methods for that)
Here is an example:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Example {
JButton button = new JButton("Open");
public static void main(String args[]) {
new Example();
}
public Example() {
JFrame frame = new JFrame();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new secondFrame();
}
});
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
class secondFrame extends JFrame implements WindowListener {
public secondFrame() {
setSize(200, 200);
setVisible(true);
addWindowListener(this);
}
@Override
public void windowActivated(WindowEvent arg0) {
}
@Override
public void windowClosed(WindowEvent arg0) {
}
@Override
public void windowClosing(WindowEvent arg0) {
button.setEnabled(true);
}
@Override
public void windowDeactivated(WindowEvent arg0) {
}
@Override
public void windowDeiconified(WindowEvent arg0) {
}
@Override
public void windowIconified(WindowEvent arg0) {
}
@Override
public void windowOpened(WindowEvent arg0) {
button.setEnabled(false);
}
}
}
Upvotes: 2