我有一个java应用程序,每次点击一个按钮时会产生1-11之间的随机数,而我的问题是我想每次点击时总结生成的nubmers按钮,例如,如果我点击按钮三次,那么我想要通过单击按钮每次创建的所有三个随机数的总和。 对不起,我的英语不好,我会非常乐意帮忙。每次点击一个按钮计算生成的随机数
这里是我的代码:
public class Game extends JFrame implements ActionListener{
private static JFrame frame;
private static JPanel p;
private static JButton b;
private static JButton choose;
private static JLabel random;
private static JLabel sumRandom;
public static void main(String[] args) {
Game bl= new Game();
bl.gui();
}
public void gui(){
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 500);
frame.setLocation(500, 200);
frame.setTitle("Blackjack");
p= new JPanel();
p.setLayout(null);
p.setBackground(Color.GRAY);
b = new JButton("Start play");
b.setBounds(450, 50, 200, 50);
b.addActionListener(this);
choose= new JButton("choose");
choose.setBounds(100, 50, 200, 50);
choose.addActionListener(this);
random= new JLabel("");
random.setBounds(200, 150, 200, 50);
sumRandom= new JLabel("");
sumRandom.setBounds(30, 150, 200, 50);
//text.setText();
p.add(sumRandom);
p.add(random);
p.add(b);
frame.add(p);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()== b){
p.add(choose);
b.setEnabled(false);
}
if(e.getSource()== choose){
int randomNumbers = (int)(Math.random() * 11 + 1);
random.setText(String.valueOf(random));
int sum= randomNumbers++;
sumRandom.setText(String.valueOf(sum));
}
}
}
全球....?在java中没有这样的东西..如果你考虑一个全局类的静态变量,那么你也错了......因为当你卸载的类遇到问题时。重新定义你的答案。你的意思是一个实例变量或静态变量,可以被类中的所有方法访问。 –