62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
public class MyPanel extends JPanel {
public MyPanel(){
JButton btn = new JButton("关闭窗口");
btn.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
//我想关闭窗口,应该怎么写?不要用System.exit(0);或System.exit(1);
}
});
this.add(btn);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new MyPanel());
f.setSize(400,300);
f.setVisible(true);
}
}
Container c = getParent();
while (!c instanceof JFrame) {
c = c.getParent();
}
public class MyPanel extends JPanel {
private static JFrame f;
public MyPanel(){
JButton btn = new JButton("关闭窗口");
btn.addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e) {
//我想关闭窗口,应该怎么写?不要用System.exit(0);或System.exit(1);
f.dispose();
}
});
this.add(btn);
}
public static void main(String[] args) {
f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new MyPanel());
f.setSize(400,300);
f.setVisible(true);
}
}