所以我试图让 JLabel 在这段代码中工作。我可以让按钮和动作监听器工作,但不能让标签工作。MyDice 是我创建面板和按钮的地方。
public class MyDice
{
public static void main(String[] args)
{
JFrame frame = new JFrame("MyDice v1.0");
frame.setSize(800,600);
frame.setLocation(560, 240);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(new Color(200,200,200));
panel.setSize(800,600);
frame.add(panel);
panel.setVisible(true);
JButton button_d4 = new JButton("Roll d4");
panel.add(button_d4);
button_d4.addActionListener (new MyRoll(4,panel));
}
}
MyRoll 是我在单击按钮时获得动作监听器的地方。
public class MyRoll implements ActionListener
{
int dice;
JPanel panel;
public MyRoll (int dice, JPanel panel)
{
this.dice = dice;
this.panel = panel;
}
public void actionPerformed(ActionEvent e)
{
rollDice(dice,1);
}
public void rollDice (int dice, int times)
{
int r=0;
for (int i=0; i<times;i++)
{
double rand = Math.random();
rand = rand*dice + 1;
r = (int) rand;
}
System.out.println("You rolled "+r+" out of "+dice);
JLabel output = new JLabel();
output.setText("You rolled "+r+" out of "+dice);
panel.add(output);
}
}
但是,这最后一部分不起作用。任何想法为什么?