java - 为什么我的 actionListener 不工作?

标签 java swing jbutton actionlistener

如果我按下hit按钮,如果z==21,我试图显示一个按钮,但我试图显示的按钮没有出现。这是一个二十一点游戏,但我从中提取了一些代码,即不起作用的部分。这是代码:

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 在按钮等内容上添加操作监听器。你的代码甚至无法为我编译。

关于java - 为什么我的 actionListener 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816291/

相关文章:

java - Android OpenCV 在应用程序中显示两个(前+后)摄像头

java - byte[] 到 String 和 String 到 byte[]

java - 整数的罗马表示

java - Jhipster 角色有什么用?

屏幕上任意位置的 Java 鼠标移动

java - SwingUtilities.InvokeLater 和 ButtonListeners

java - 使用 FlowLayout 将 JPanel 添加到 JFrame

java - 在多个 JFrame 之间切换

Java无法将JPanel内的JTextField作为JScrollPane中的视口(viewport)来关注

java - 如何使角组件在 JScrollPane 中始终可见