从值为Int的另一个类更改JButton文本

时间:2017-08-12 05:44:07

标签: java getter-setter

如果你能帮助我,我们将很高兴。通过权利我有2个班级。第一个是UI(GameJPanel)类,我在其中声明了所有私有按钮等。第二个类是gameEngine(GameMechanismPlayer),它生成要在JButton“textFields”上设置的值。 gameEngine生成的值是整数。我正在努力,从第二课改变按钮文本,但我得到错误。我相信我应该使用UI类中的getter和setter。你能帮帮我..

public class GameJPanel extends JPanel 
{
    private static final long serialVersionUID = 1L;
    private JToggleButton die1, 
    private JButton rollDice;

    public GameJPanel()
    {
        //Dice Toggle Buttons       
        die1 = new JToggleButton("Die 1");
        die1.setBounds(300,350,70,25);
        add(die1);
        //Roll Dice
        rollDice = new JButton("Roll Dice");
        rollDice.setBounds(400,400,270,50);
        add(rollDice);

        rollDice.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                playGame.play();
            }       
        });
        setVisible(true); 
        setLayout(null);
        }

    public JToggleButton getDie1()
    {
        return die1;
    }

    public void setDie1(JToggleButton die1)
    {
        this.die1 = die1;
    }
}


public class GameMechanismPlayer
{
    private int[] randomDiceArrayNumber;
    private int dieIndexPosition;
    private Random randomDice;
    private boolean isPlayerOneTurn = true;
    GameJPanel uI = new GameJPanel();

    public GameMechanismPlayer()
    {
        play();     
    }

    public void play()
    {

        for(turn = 0 ; turn <= 3 || scoreSelected == true; turn++)
        {
            randomDice = new Random(); 
            randomDiceArrayNumber = new int [5];

            for(dieIndexPosition = 0; dieIndexPosition < randomDiceArrayNumber.length; dieIndexPosition++)
            {
                randomDiceArrayNumber[dieIndexPosition] = 1+randomDice.nextInt(6);
            }
            sumsMutipleByItsOwnNumber();

            if(isPlayerOneTurn = true)
            {
                //Here it is not working
                uI.setDie1(String.valueof(randomDiceArrayNumber[0]))
            }
        }
    }   
}

1 个答案:

答案 0 :(得分:0)

不兼容的类型!

  1. 您的定义:

    // this expects an argument of type JToggleButton
    public void setDie1(JToggleButton die1) {
        this.die1 = die1;
    }
    
  2. 您的来电声明:

    uI.setDie1(String.valueof(randomDiceArrayNumber[0])); // this is trying to pass a String to the method setDie1
    
  3. 相反,这样的事情(只是纠正语法)应该有效:

    uI.setDie1(new JToggleButton(String.valueof(randomDiceArrayNumber[0])));