2

ボードゲームを作っているので、サイコロのように動くボタンを操作する必要があります。私のフレームには、サイコロを投げるボタンがあり、その隣にはサイコロの結果を表示するJLabelがあります。問題は、別のクラスのサイコロと別のクラスのボタンのコーディングがあることです。アクションリスナーのコードを保持するアクションクラスがあります。どうすれば実装できますか?以下は私のコードです。

GameViewクラス:

 public void gui()
    {
        BorderLayout borderlayout = new BorderLayout();      
        
        //Creates the frame, set the visibility to true, sets the size and exit on close
        JFrame frame = new JFrame("Games");
        frame.setVisible(true);
        frame.setSize(600,400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        //Creates the Throw Dice button
        Panel p = new Panel();
        p.setLayout(new GridLayout());
        p.add(new Button("Throw Dice"));
        p.add(new Label("Dice Draw")); //This is where I want the dice result to be shown when hit the button
        p.setBackground(new Color(156, 93, 82));
        frame.add(p, BorderLayout.SOUTH);

サイコロクラス:

public class Dice
{   
    //stores the dice result in the variable
    private int diceResult;

    /**
     * Constructor for objects of class Dice
     */
    public Dice()
    {
        this.diceResult = diceResult;
    }

    /**
     * Generates a random number between 1 and 5
     */
    public void randomGenerator ()
    {
        Random dice = new Random();
        diceResult = dice.nextInt(5)+1;
        System.out.println(diceResult);
    }
}

アクションクラス:

public class Action
{
    public void actionPerformed (ActionEvent e) 
    {
    }
}
4

1 に答える 1

3

このような簡単な例では、このように実装する匿名クラスの利点を使用することをお勧めしますActionListener

    BorderLayout borderlayout = new BorderLayout();      

    //Creates the frame, set the visibility to true, sets the size and exit on close
    JFrame frame = new JFrame("Games");
    frame.setVisible(true);
    frame.setSize(600,400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    //Creates the Throw Dice button
    Panel p = new Panel();
    p.setLayout(new GridLayout());

    final Dice dice = new Dice();
    Button button = new Button("Throw Dice");
    final Label label = new Label("Dice Draw");

    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dice.randomGenerator();
            label.setText(Integer.toString(dice.getDiceResult()));
        }
    });

    p.add(button);
    p.add(label); //This is where I want the dice result to be shown when hit the button
    p.setBackground(new Color(156, 93, 82));
    frame.add(p, BorderLayout.SOUTH);

getDiceResultまた、クラスにメソッドを追加する必要がありますDice

于 2012-04-12T21:49:06.670 に答える