import java.awt.GridLayout; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; public class Test { public static void main (String[] args){ final JFrame test= new JFrame(); test.setLayout(new GridLayout(3,2)); final Menu menu = new Menu("文件"); MenuBar menubar = new MenuBar(); final MenuItem menu1 = new MenuItem("关闭"); menu.add(menu1); menubar.add(menu); test.setMenuBar(menubar); //使用菜单关闭 menu1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if ((e.getSource() == menu1) ) System.exit(1); } }); //使用按钮关闭 final JButton but1 = new JButton("关闭"); but1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (e.getSource() == but1) System.exit(1); } }); //使用系统关闭 test.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub super.windowClosing(e); if (e.getSource() == test) System.exit(1); } }); test.add(but1); test.setVisible(true); test.pack(); } }
时间: 2024-11-06 09:22:48