如何在实现动作侦听器时设置不同的动作命令?

时间:2011-05-30 03:04:39

标签: java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Menu extends JFrame implements ActionListener{    

    // Create the components and global variables
    JButton newGameButton = new JButton("New Game");
    JButton instructionGameButton = new JButton("Instructions");
    JButton exitButton = new JButton("Exit");
    JLabel mylabel = new JLabel("Welcome to Blackjack");

    public Menu()
    {

        // Create the window
        super("ThreeButtons");
        setSize(300,100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        //Creating the container for the components and set the layout
        Container content = getContentPane();
        FlowLayout layout = new FlowLayout();
        content.setLayout(layout);

        //Adding the event listener
        newGameButton.addActionListener(this);
        instructionGameButton.addActionListener(this);
        exitButton.addActionListener(this);

        //Adding of components
        content.add(mylabel);
        content.add(newGameButton);
        content.add(instructionGameButton);
        content.add(exitButton);


        setContentPane(content);

    }

    //Add the event handler
    public void actionPerformed(ActionEvent event)
    {
    if (event.getActionCommand()=="New Game")
    new lol4();

    if (event.getActionCommand()=="Instructions")
    //new Instructions();

    if (event.getActionCommand()=="Quit ?")
    System.exit(0);


    }


    public static void main (String[] args)
    {
        //Create an instance of my class
    new Menu();
    }

}

退出似乎不起作用

2 个答案:

答案 0 :(得分:2)

首先,永远不要使用“==”来比较字符串。使用equals(...)方法。

  

退出似乎不起作用

为什么要检查“退出?”?

除非您明确设置命令,否则action命令默认为按钮的文本。

答案 1 :(得分:1)

我从不喜欢“switch-board”动作监听器,其中监听器试图做所有事情,并且由于难以修复错误而无法做任何事情。更好的我认为使用匿名内部类来自己保存简单代码,或者如果将代码路由到其他方法更复杂,或者如果更复杂,则调用Controller的方法。

例如:

  newGameButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        newGameActionPerformed(); // delegate this to a class method
     }
  });

  instructionGameButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        // call a controller object's methods
        if (myController != null) {
           myController.instructionGameAction();
        }
     }
  });

  exitButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        Menu.this.dispose(); // simple code can be called in-line
     }
  });

和班上的其他地方:

   private void newGameActionPerformed() {
      // TODO add some code here!
   }

   public void setController(MyController myController) {
      this.myController = myController;
   }