標籤:java
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 stubif ((e.getSource() == menu1) )System.exit(1);}});//使用按鈕關閉final JButton but1 = new JButton("關閉");but1.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif (e.getSource() == but1)System.exit(1);}});//使用系統關閉test.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {// TODO Auto-generated method stubsuper.windowClosing(e);if (e.getSource() == test)System.exit(1);}});test.add(but1);test.setVisible(true);test.pack();}}
那些年,一起學的Java 8-3