2011-05-30 66 views
0
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(); 
    } 

} 

退出似乎並沒有工作如何在實現動作偵聽器時設置不同的動作命令?

+0

這裏展示你的代碼,請。 – 2011-05-30 03:07:25

+1

請將您的代碼粘貼到此處,而不是在其他某個網站上。 StackOverflow在這裏是一個高質量問題和答案的倉庫;當pastie關上門或過期時會發生什麼?這將變得(更)無用,對未來的其他人沒有任何幫助。謝謝! – sarnold 2011-05-30 03:10:08

+0

我明白你的意思了,對不起,現在好點了? – gheystyle 2011-05-30 03:14:54

回答

1

我從來不喜歡「開關板」動作偵聽器,因爲偵聽器試圖做所有事情,並且由於難以修復錯誤而無所事事。更好的是,我認爲使用匿名內部類來保存簡單的代碼本身,或者如果將代碼路由到其他方法或者更復雜的話來調用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; 
    } 
2

首先,千萬不要用「==」比較字符串。使用equals(...)方法。

退出似乎並沒有工作

你爲什麼要檢查 「退出?」?

除非明確設置命令,否則操作命令默認爲按鈕的文本。