我想这样做,这样当我关闭我的 GUI 时,它会在我的主类中运行一个方法,但之后也会关闭?
请帮忙谢谢
假设您使用的是 Java Swing:
JFrame frame = new JFrame();
frame.setTitle("Project Planner");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
exitProcedure();
}
});
.
public void exitProcedure() {
frame.dispose();
System.exit(0);
}
只需在 dispose 方法之前添加您想要执行的操作。
为此,您需要注册WindowListener
到相关的JFrame
. 并覆盖该windowClosing()
方法。
编辑
从字符串数组中随机选择一个字符串,您可以使用java.util.Random API。例如,这里是一个数组,String
每次JFrame
关闭时,String
都会从该数组中随机挑选出 a 并在方法中打印callMeBeforeExit
。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.BorderLayout;
import java.util.Random;
class WorkBeforeClose extends JFrame
{
String[] strings = {
"Hello",
"World",
"Java",
"OOPs"
};
public void showGUI()
{
setTitle("Close me");
getContentPane().add(new JLabel("Close me"),BorderLayout.NORTH);
addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent evt)
{
callMeBeforeExit();
System.exit(0);//Don't write this line if you don't want your program to exit
}
});
setSize(200,200);
setVisible(true);
}
private void callMeBeforeExit()
{
Random random = new Random();
int i = random.nextInt(strings.length - 1);//Defines the Range of numbers to be chosen randomly.
System.out.println(strings[i]);
}
public static void main(String st[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
WorkBeforeClose wbc = new WorkBeforeClose();
wbc.showGUI();
}
});
}
}
尝试WindowAdapter
在 GUI 的addWindowListener()
方法中实现。