gpt4 book ai didi

java - 将变量从按钮按下传递到另一个类

转载 作者:行者123 更新时间:2023-12-01 12:29:21 25 4
gpt4 key购买 nike

所以我试图将一个变量从一个类中的按钮按下传递到另一个类,但不太明白。按下按钮会创建一个随机数来模拟掷骰子,将其添加到一个变量中,然后将该变量传递给构建有游戏板的板类,然后使用所述变量来确定板上的哪个空间播放器已开启。预先感谢您。

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.util.Random;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;


public class Game extends JPanel{
private JLabel lblP1Name, lblP2Name, lblRules, lblDiceRoll;
private JTextField txtP1Name, txtP2Name;
private JButton diceRoll;
private JRadioButton rdP1, rdP2;
private int dice;
private static int countP1;
private int countP2;
private JPanel panelNorth;

private void groupButton( ) {

ButtonGroup bg1 = new ButtonGroup( );

bg1.add(rdP1);
bg1.add(rdP2);

}
public Game() throws FileNotFoundException {
setLayout (new BorderLayout());




rdP1 = new JRadioButton("Player 1");
rdP2 = new JRadioButton("Player 2");
ButtonListener listener = new ButtonListener();
Player1 player1 = new Player1(countP1);
Player2 player2 = new Player2(countP2);
Board board = new Board();
Rules rules = new Rules();
JButton diceRoll = new JButton("Roll the dice!");
panelNorth = new JPanel();
panelNorth.setLayout(new GridLayout(1,3));
lblRules = new JLabel(rules.toString());

add(panelNorth, BorderLayout.NORTH);
panelNorth.add(rdP1);
panelNorth.add(diceRoll);
panelNorth.add(rdP2);

Card card = new Card();

add(player1, BorderLayout.WEST);
add(player2, BorderLayout.EAST);
add(lblRules, BorderLayout.SOUTH);
add(board, BorderLayout.CENTER);
diceRoll.addActionListener(listener);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent diceRoll){
Random random = new Random();
dice = random.nextInt(6)+1;


if(rdP1.isSelected()){
countP1 = countP1+dice;
if(countP1>48){
countP1=countP1-48;

}
}else if(rdP2.isSelected()){
countP2 = countP2+dice;
if(countP2>48){
countP2=countP2-48;

}
}

}
}


}

最佳答案

很简单;只需使用引用即可。

实例化您的类并传递引用:

Board board = new Board();
YourClass yourClass = new YourClass(board);

这样您就可以从 YourClass 类中设置 Board 属性。这真的很简单,您只需阅读基础的 Java 书籍就可以学会如何做到这一点。

关于java - 将变量从按钮按下传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26069021/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com