簡體   English   中英

為什么我的actionListener不起作用?

[英]Why isn't my actionListener working?

如果z==21 ,我想按一下hit顯示一個按鈕,但是我想顯示的按鈕卻沒有顯示。 這是針對BlackJack游戲的,但我從其中抽出了一些代碼,該代碼不起作用。 這是代碼:

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);
    }
}

應該在按鈕之類的東西上使用addActionListener添加動作監聽器。 您的代碼甚至沒有為我編譯。

您的動作偵聽器有效。 但是您的按鈕狀態永遠不會添加到JFrame中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM