java swing 退出程序_基本的Java Swing,如何退出和处理你的应用程序/ JFrame

使用这样的代码处理JFrame的好方法是什么?我想处理窗口退出和窗口关闭.

我知道我们不应该使用System.exit();

public class JavaCellularAutomataSquare {

public static final String TITLE = "Cellular Automata - Squaring Example";

private int maxWidth = 600;

private int maxHeight = 600;

public void launch() {

final JFrame frame = new JFrame(TITLE);

frame.setLocation(20,20);

frame.setPreferredSize(new Dimension(maxWidth,maxHeight));

frame.setResizable(false);

frame.setFocusable(true);

final JPanel panel = new JPanel();

panel.setLocation(20,20);

panel.setVisible(true);

panel.setPreferredSize(new Dimension(maxWidth,maxHeight));

panel.setFocusable(true);

panel.setBackground(Color.white);

// Panel setup,toggle visibility on frame

frame.add(panel);

frame.pack();

frame.setVisible(true);

}

}

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ClosingFrame extends JFrame {

private JMenuBar MenuBar = new JMenuBar();

private JFrame frame = new JFrame();

private static final long serialVersionUID = 1L;

private JMenu File = new JMenu("File");

private JMenuItem Exit = new JMenuItem("Exit");

public ClosingFrame() {

File.add(Exit);

MenuBar.add(File);

Exit.addActionListener(new ExitListener());

WindowListener exitListener = new WindowAdapter() {

@Override

public void windowClosing(WindowEvent e) {

int confirm = JOptionPane.showOptionDialog(frame,"Are You Sure to Close this Application?","Exit Confirmation",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,null);

if (confirm == JOptionPane.YES_OPTION) {

System.exit(0);

}

}

};

frame.addWindowListener(exitListener);

frame.setDefaultCloSEOperation(EXIT_ON_CLOSE);

frame.setJMenuBar(MenuBar);

frame.setPreferredSize(new Dimension(400,300));

frame.setLocation(100,100);

frame.pack();

frame.setVisible(true);

}

private class ExitListener implements ActionListener {

@Override

public void actionPerformed(ActionEvent e) {

int confirm = JOptionPane.showOptionDialog(frame,null);

if (confirm == JOptionPane.YES_OPTION) {

System.exit(0);

}

}

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

ClosingFrame cf = new ClosingFrame();

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值