[英]How to listen to a JFrame window closing from its parent JFrame in Java Swing
My program launches a JFrame from an already running parent JFrame. 我的程序从已经运行的父JFrame启动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. 除了一个条件外,第二个JFrame具有自第一个JFrame的自治权-我要求在(且仅当)第二个JFrame打开时才能禁用父JFrame中的按钮,以防止启动其他JFrame。
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? 所以我的问题是,如何才能从父JFrame监听第二个JFrame的“存在”,以便操纵我的按钮是否处于活动状态?
My parent JFrame launches the secondary JFrame as follows: 我的父级JFrame按如下方式启动辅助JFrame:
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. 在第二个JFrame启动后禁用该按钮。
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. 因此,现在我该如何从第一个JFrame监听第二个JFrame的窗口状态,以便重新启用btn_open按钮。
One way is to add a WindowListener
to the second frame. 一种方法是将WindowListener
添加到第二帧。 You can call button.setEnabled()
every time the frame closes or opens. 每当框架关闭或打开时,您都可以调用button.setEnabled()
。 (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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.