将按钮按下的变量传递给另一个类

时间:2014-09-26 22:11:32

标签: java

所以我试图将一个变量从一个类中的按钮传递到另一个类,并且无法弄明白。按下按钮创建一个随机数来模拟骰子掷骰子,将其添加到一个变量,然后该变量被传递给在其上构建游戏板的棋盘类,然后使用所述变量来确定棋盘上的哪个空间玩家开了。提前谢谢。

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;

            }
        }

    }
}


}

1 个答案:

答案 0 :(得分:1)

很简单;只需使用参考文献。

实例化您的类并传递参考:

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

这样您可以从YourClass类设置Board属性。 这很简单,你可以通过阅读基本的Java书籍来学习如何做到这一点。