所以我正在尝试编写一个D& D Dice滚轮,它可以拉出一个带有5个按钮的GUI,当按下该按钮时,该按钮会拉动该骰子。当我单击D4按钮时,它会拉出消息,每次单击时都会滚动1,依此类推其他按钮。我对此很困惑,我在3年内没有编码,并试图回到它,我觉得它很容易,但我不知道。我不知道为什么,但当它滚动任何骰子时,它会滚动1.如果我能得到任何帮助,那将是非常好的,我只是为了好玩而做这个
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GUIRNG implements ActionListener {
int d4 = rand.nextInt(4) + 1;
int d6 = rand.nextInt(6) + 1;
int d8 = rand.nextInt(8) + 1;
int d10 = rand.nextInt(10) + 1;
int d20 = rand.nextInt(20) + 1;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GUIRNG().createGui();
}
});
}
private enum Actions {
D4,
D6,
D8,
D10,
D20,
}
public void createGui() {
JFrame frame = new JFrame("D&D Dice Roller");
frame.setSize(700, 700);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.black);
frame.add(panel);
frame.getContentPane().add(panel, BorderLayout.WEST);
GridBagConstraints c = new GridBagConstraints();
JButton button1 = new JButton("D4");
button1.setActionCommand(Actions.D4.name());
button1.addActionListener(this);
d4 = rand.nextInt(4) + 1;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(40, 40, 40, 40);
panel.add(button1, c);
JButton button2 = new JButton("D6");
button2.setActionCommand(Actions.D6.name());
button2.addActionListener(this);
d6 = rand1.nextInt(6) + 1;
c.gridx = 0;
c.gridy = 1;
panel.add(button2, c);
JButton button3 = new JButton("D8");
button3.setActionCommand(Actions.D8.name());
button3.addActionListener(this);
d8 = rand.nextInt(8) + 1;
c.gridx = 0;
c.gridy = 2;
panel.add(button3, c);
button3.addActionListener(this);
JButton button4 = new JButton("D10");
button4.setActionCommand(Actions.D10.name());
button4.addActionListener(this);
d10 = rand.nextInt(10) + 1;
c.gridx = 0;
c.gridy = 3;
panel.add(button4, c);
button4.addActionListener(this);
JButton button5 = new JButton("D20");
button5.setActionCommand(Actions.D20.name());
button5.addActionListener(this);
d20 = rand.nextInt(20) + 1;
c.gridx = 0;
c.gridy = 4;
panel.add(button5, c);
button5.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == Actions.D4.name()) {
JOptionPane.showMessageDialog(null, "You rolled: "+d4);
}
if (e.getActionCommand() == Actions.D6.name()) {
JOptionPane.showMessageDialog(null, "You rolled: "+d6);
}
if (e.getActionCommand() == Actions.D8.name()) {
JOptionPane.showMessageDialog(null, "You rolled: "+d8);
}
if (e.getActionCommand() == Actions.D10.name()) {
JOptionPane.showMessageDialog(null, "You rolled: "+d10);
}
if (e.getActionCommand() == Actions.D20.name()) {
JOptionPane.showMessageDialog(null, "You rolled: "+d20);
}
}
}
'
答案 0 :(得分:2)
按下按钮时,你永远不会重新掷骰子。你在createGui中设置一次骰子的值,而不是再次设置。如果要在单击按钮时更改骰子的值,则每次按下按钮时都应重新生成其值(I.E. in actionPerformed)。