面板退出java

时间:2011-04-18 19:05:07

标签: java swing frame exit

Frame fr;
...
fr.setDefaultCloseOperation(Frame.???)

我应该写什么而不是“???”关闭框架?

2 个答案:

答案 0 :(得分:6)

我认为您打算使用JFrame

JFrame fr;
...
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

使用(旧的)AWT Frame,您可以执行以下操作来关闭它:

final Frame frame = new Frame("Frame test");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        frame.dispose();
    }
});
frame.setVisible(true);

答案 1 :(得分:2)

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

有代码示例

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test {
    JFrame frame;

    public Test() {
        JButton button = new JButton("exit");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
            }
        });
        JPanel panel = new JPanel();
        panel.add(button);
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setLocation(200,200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new Test();        
    }
}