menutest.java

来自「Java the UML Way 书中所有源码」· Java 代码 · 共 53 行

JAVA
53
字号
/*
 * MenuTest.java  E.L. 2001-08-22
 *
 */
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class WindowWithMenu extends JFrame {
  private Container guiContainer;

  public WindowWithMenu() {
    setTitle("MenuTest");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    guiContainer = getContentPane();

    MenuListener theListener = new MenuListener();

    JMenu theMenu = new JMenu("Color");
    JMenuItem menuItem = new JMenuItem("Yellow");
    theMenu.add(menuItem);
    menuItem.addActionListener(theListener);

    menuItem = new JMenuItem("Red");
    theMenu.add(menuItem);
    menuItem.addActionListener(theListener);

    menuItem = new JMenuItem("Blue");
    theMenu.add(menuItem);
    menuItem.addActionListener(theListener);

    JMenuBar menuBar = new JMenuBar();
    menuBar.add(theMenu);
    setJMenuBar(menuBar);
  }

  private class MenuListener implements ActionListener {
    public void actionPerformed(ActionEvent event) {
      String command = event.getActionCommand();
      if (command.equals("Yellow")) guiContainer.setBackground(Color.yellow);
      else if (command.equals("Red")) guiContainer.setBackground(Color.red);
      else guiContainer.setBackground(Color.blue);
    }
  }
}

class MenuTest {
  public static void main(String[] args) {
    WindowWithMenu window = new WindowWithMenu();
    window.setSize(300, 200); // pack() gives a very little window!
    window.setVisible(true);
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?