设计一个窗口,窗口标题为 “姓名+‘的Java窗口’”,该窗口中包括:一个菜单“系统菜单”,一个Label标签,两个按钮Button1和Button2。当选择菜单时,在标签中显示文字:“系统菜单被选择”;点击按钮Button1时,在button2上显示Button1被点击了多少次。
package javaForm.Form1;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class MainWindow extends JFrame{
private static final long serialVersionUID = 1L;
JMenuBar bar;
JMenu menu;
JLabel label;
JButton button1;
JButton button2;
JPanel panel;
public MainWindow(String title) {
//组件
bar = new JMenuBar();
menu = new JMenu("系统菜单");
label = new JLabel("label");
button1 = new JButton("button1");
button2 = new JButton("button2");
panel = new JPanel();
//组件属性及事件设置
menu.addMenuListener(new MenuActionListener(label));
button1.addActionListener(new ButtonActionListener(button2));
//组件组合至窗口
bar.add(menu);
panel.add(label);
panel.add(button1);
panel.add(button2);
this.setJMenuBar(bar);
this.add(panel);
//窗口属性设置
this.setTitle(title);
this.setLocation(400, 300);
this.setSize(500, 300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MainWindow window = new MainWindow("测试的java窗口");
}
}
package javaForm.Form1;
import javax.swing.JLabel;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class MenuActionListener implements MenuListener {
private JLabel label;
public MenuActionListener(JLabel label) {
this.label = label;
}
@Override
public void menuSelected(MenuEvent e) {
label.setText("系统菜单被选择");
}
@Override
public void menuDeselected(MenuEvent e) {
label.setText("label");
}
@Override
public void menuCanceled(MenuEvent e) {
label.setText("label");
}
}
package javaForm.Form1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class ButtonActionListener implements ActionListener{
private JButton button2;
private int clickCount;
public ButtonActionListener(JButton button2) {
this.button2 = button2;
}
@Override
public void actionPerformed(ActionEvent e) {
clickCount ++;
this.button2.setText("" + clickCount);
}
}