Java6学习笔记3——利用Swing开发按钮、菜单

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Closer extends JFrame implements ActionListener {//实现了监听接口功能
public static void main(String arg[]) {
new Closer();
}
public Closer() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildMenu();
buildFrame();
setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(this);//添加监听对象
add(exitButton);
setSize(300,200);
}
private void buildMenu() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(this);
fileMenu.add(exitMenuItem);
setJMenuBar(menuBar);
}
public void actionPerformed(ActionEvent e) {//监听的相应动作
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
}
}
}

你可能感兴趣的:(java,swing)