作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想创建一个石头/剪刀/布游戏并添加功能来实现一个按钮,该按钮使用户可以选择重玩游戏而无需重新运行程序,但是当我按下“再做一次”时"按钮计算机的随机选择总是相同的,如何做到从数组中选择一个新的随机字符串。
JButton button1 = new JButton("The choice");
JButton button2 = new JButton("Do it again");
JTextField tekst1 = new JTextField(20);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(tekst1);
c.add(button1);
c.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!hasBeenClicked) {
button1.addActionListener(new ActionListener() {
String[] arr={"rock", "paper", "scissors"};
Random r=new Random();
int randomNumber=r.nextInt(arr.length);
public void actionPerformed(ActionEvent evt) {
tekst1.setText(arr[randomNumber]);
}
});
} else {
tekst1.setText("");
}
hasBeenClicked = ! hasBeenClicked;
}
});
最佳答案
发生这种情况是因为您在单击事件之外生成了一个随机数。将其移动到下面几行的方法中:
button1.addActionListener(new ActionListener() {
String[] arr={"rock", "paper", "scissors"};
Random r=new Random();
public void actionPerformed(ActionEvent evt) {
int randomNumber=r.nextInt(arr.length);
tekst1.setText(arr[randomNumber]);
}
});
关于java - 如何制作 JButton,按下时会执行新操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769181/
我创建了一个分支来开发新功能。由于这个新功能完全是作为一个新项目开发的,唯一可能的冲突来源是解决方案文件。 随着功能的开发,主分支更新了几次。当我完成开发和测试时,我做了: git checkout
我是一名优秀的程序员,十分优秀!