So I’m trying to make the JLabel work in this code. I can get the button and Action Listener to work but not the Label.
MyDice is where I create the Panels and buttons.
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));
}
}
And the MyRoll is where I got the Action Listener that does something when I click the buttons.
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);
}
}
However, this last part does not work. Any ideas why?
Use a JLabel and set the Label Message in your logic
REVISION for the updated CODE POSTED
You should set up the Label outside of the Logic, added to the Panel with initial empty value and then on your logic you change the Label’s Value
i.e
That way you are not constantly adding a JLabel to your Panel