java - 如何为骰子制作 Action 监听器按钮?

标签 java swing jbutton actionlistener dice

我正在制作一款棋盘游戏,我需要操作一个像骰子一样操作的按钮。在我的框架中,我有掷骰子按钮,它旁边是一个 JLabel,它将显示骰子的结果。问题是我有一个不同类中的骰子编码和另一个类中的按钮编码。我有一个操作类,它将保存操作监听器的代码。我该如何实现?下面是我的代码。

游戏 View 类:

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

Action 类:

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

最佳答案

在这样的简单示例中,我可以建议您使用匿名类的优点,该类实现像这样的 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 类中。

关于java - 如何为骰子制作 Action 监听器按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10132216/

相关文章:

java - 从文本字段矩阵获取文本

java - 更新 Java Swing 应用程序中的按钮状态

java - 按值的字母顺序排列 HashMap

java - 在控制台模式和图形模式之间切换

java - 如何在整个应用程序中引用顶级容器而不使其成为单例?

java - 无法更改 ActionListener 内的 JButton ActionCommand

java - 如何显示处理信息。在程序中?

java - Java JVM 中的内存交换到磁盘

java - 将 FileResource 转换为字符串

java - CSS 定位器选择 react 问题