2015-03-02 48 views
0

我試圖讓一個按鈕顯示出來,如果我按hit按鈕,如果z==21,但我試圖讓顯示出來的按鈕沒有顯示出來。這是一款BlackJack遊戲,但是我從中抽出了一小部分代碼,這部分不起作用。這裏是代碼:爲什麼我的actionListener不工作?

import java.awt.Color; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 




public class blackjack { 
// Creating static variables 

     static JFrame frame = new JFrame("BlackJack"); 
     static JButton hit = new JButton("Get results"); 
     static int z = 21; 
     static int y = 0; 
     static JButton mainMenu = new JButton("Main Menu"); 
     static JButton status = new JButton("BUSTED!"); 
     static JButton status2 = new JButton("YOU WON!!!"); 
     static JTextArea words = new JTextArea("the number is " + z); 


     static class Hit implements ActionListener{ 
      public void actionPerformed(ActionEvent e){ 
       if(z==21){ 
       status.setBounds(0, 0, 500, 500); 
       status.setVisible(true); 
       status.setBackground(Color.green); 
       status.setText("The number is 21! it works!"); 
       } else { 
        status.setVisible(true); 
        status.setBackground(Color.RED); 
        status.setText("It doesn't work... more problems"); 
        } 
      } 
     } 



     public static void main (String[] args){ 
      //JFrame properties 
      frame.setLayout(null); 
      frame.setVisible(true); 
      frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); 
      // Adding JVariables and setting bounds 
      status.setBounds(20, 50, 500, 150); 
      status2.setBounds(20, 50, 500, 150); 
      hit.setBounds(5, 110, 300, 50); 
      frame.add(hit); 
      hit.setVisible(true); 
      hit.setEnabled(true); 
      hit.addActionListener(new Hit()); 

      words.setBounds(0, 0, 100, 100); 
      frame.add(words); 
      frame.setSize(500, 500); 
    } 
} 

回答

0

你的ActionListener工作。但是您的按鈕狀態永遠不會添加到JFrame中。

+0

哦。咄。謝謝。 – CadeLikesToCode 2015-03-02 18:08:18

1

動作應該在按鈕之類的東西上使用addActionListener添加監聽器。你的代碼甚至不會爲我編譯。

+0

嗯,對我來說,這個例子沒有錯誤。 – pL4Gu33 2015-03-02 18:01:26

+0

這個'frame.add(hit);'因爲動作偵聽器不是組件而失敗。 – 2015-03-02 18:03:24

+0

命中是一個JButton。它應該工作。 – pL4Gu33 2015-03-02 18:05:44