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);
}
}
}
Java6学习笔记3——利用Swing开发按钮、菜单
最新推荐文章于 2024-07-02 13:14:25 发布
本文介绍了一个使用Java Swing创建基本应用程序的例子,该程序包括菜单栏和按钮,并通过监听器实现程序退出功能。示例代码展示了如何创建窗口、设置菜单及按钮并响应用户的操作。
8万+

被折叠的 条评论
为什么被折叠?



