Java 如何使一个按钮在按下时执行新操作

Java 如何使一个按钮在按下时执行新操作,java,swing,random,jbutton,Java,Swing,Random,Jbutton,我想创建一个石头/布/剪刀游戏,并添加一个功能来实现一个按钮,该按钮允许用户选择重播游戏,而无需重新运行程序,但当我按下“再次执行”按钮时,计算机的随机选择总是一样的,如何从数组中选择一个新的随机字符串 JButton button1 = new JButton("The choice"); JButton button2 = new JButton("Do it again"); JTextField tekst1 = new JTextField(20); Container c = get

我想创建一个石头/布/剪刀游戏,并添加一个功能来实现一个按钮,该按钮允许用户选择重播游戏,而无需重新运行程序,但当我按下“再次执行”按钮时,计算机的随机选择总是一样的,如何从数组中选择一个新的随机字符串

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

移动
int randomNumber=r.nextInt(arr.length)进入已执行的操作

移动
int randomNumber=r.nextInt(arr.length)编码为已执行的操作

之所以发生这种情况,是因为您在单击事件之外生成了一个随机数。将其移动到下面几行的方法:

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

发生这种情况是因为在单击事件之外生成了一个随机数。将其移动到下面几行的方法:

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

谢谢你修好了谢谢你修好了