我正在尝试创建一个使用messageBox的方法,考虑到程序退出或按下“X”按钮的情况,询问是否记录更改并将其绑定以保存代码。如果没有更改,则不显示任何消息。
我明白我需要使用布尔值,但是我失败了。 其余部分将与结果相关联。
package nbu.university.scheduler.messageBox;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class ClosingFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public ClosingFrame() {
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
int showConfirmDialog = JOptionPane.
showConfirmDialog(ClosingFrame.this, "Do you want to save changes?");
if (showConfirmDialog == JOptionPane.YES_OPTION) {
final JOptionPane optionPane = new JOptionPane("Has been save", JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION, null, new Object[]{}, null);
final JDialog dialog = new JDialog();
dialog.setTitle("Message");
dialog.setModal(true);
dialog.setContentPane(optionPane);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.pack();
//create timer to dispose of dialog after 1 seconds
Timer timer = new Timer(1000, new AbstractAction() {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent ae) {
dialog.dispose();
}
});
timer.setRepeats(false);//the timer should only go off once
//start timer to close JDialog as dialog modal we must start the timer before its visible
timer.start();
pack();
dialog.setVisible(true);
System.out.println("saved");
System.exit(0);
} else if (showConfirmDialog == JOptionPane.NO_OPTION) {
System.out.println("not saved");
System.exit(0);
} else {
System.out.println("aborted");
// do nothing
}
}
});
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater((Runnable) new ClosingFrame());
}
}
这是我正在尝试这样做的表中的代码
private void exit()
{
this.dispose();
}
@Override
protected void processWindowEvent(WindowEvent e)
{
if (e.getID() == WindowEvent.WINDOW_CLOSING)
{
exit();
}
else
{
super.processWindowEvent(e);
}
}
............................................... ................................
public void getClassSchedulerModel(int classType, int classNumber)
{
if (classType == 0)
{
int count = bachelorClassesSchedulesHolder.getComponentCount();
if (classNumber < count)
{
if (bachelorClassesSchedulesHolder.getComponent(classNumber) instanceof JTabbedPane)
{
JTabbedPane component = (JTabbedPane)bachelorClassesSchedulesHolder.getComponent(classNumber);
rewriteTableRow(component);
}
}
}
if (classType == 1)
{
int count = masterClassesSchedulesHolder.getComponentCount();
if (classNumber < count)
{
if (masterClassesSchedulesHolder.getComponent(classNumber) instanceof JTabbedPane)
{
JTabbedPane component = (JTabbedPane)masterClassesSchedulesHolder.getComponent(classNumber);
rewriteTableRow(component);
}
}
}
}