如果我按下hit
按钮,如果z==21
,我正试图按下按钮,但我尝试显示的按钮没有显示。这是一个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);
}
}
答案 0 :(得分:1)
应该使用addActionListener
在按钮之类的东西上添加动作侦听器。你的代码甚至不能为我编译。
答案 1 :(得分:0)
你的actionlistener有效。但是您的按钮状态永远不会添加到JFrame。