Reputation: 33
i have a problem i can't solve.
I want this:
When i open the gui, i will show a random number and a button that says "change number".
Then, when the button is clicked, i want that the previous random number change into another random number and so on.
This is my code:
public class RandomDisplayPanel extends JPanel {
public RandomDisplayPanel() {
JPanel panel = new JPanel();
add(panel);
JPanel inside = new JPanel();
panel.setBackground(Color.yellow);
JButton sendButton = new JButton("Send");
Random generator = new Random();
int num;
num = generator.nextInt(100) +1;
JLabel numero = new JLabel("" + num);
inside.add(numero);
inside.add(sendButton);
panel.add(inside);
sendButton.addActionListener(new RandomDisplayPanel.RandomListener());
}
private class RandomListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Random generator = new Random();
int num;
num = generator.nextInt(100) +1;
}
}
}
How can i do that? thank you in advance :)
Upvotes: 1
Views: 3829
Reputation: 311
To get a random number you can use Math.random();
and multiply it with 10 and add 1 for example. (Then it is between 1 and 10)
To set the button text then use
Button myButton=(Button)this.findViewById(R.id.yourButtonsID);
myButton.setText(yourRandomNumber);
Upvotes: 0
Reputation: 37594
Add numero.setText(num + "");
inside your listener.
EDIT : Declare the JLabel numero
as a class variable and it will work.
Upvotes: 0
Reputation: 33726
You can pass the (JLabel) number to the listener as follow:
sendButton.addActionListener(new RandomDisplayPanel.RandomListener(number));
private class RandomListener implements ActionListener {
private JLabel target;
public RandomListener(JLabel target) {
this.target = target;
}
@Override
public void actionPerformed(ActionEvent e) {
Random generator = new Random();
int num;
num = generator.nextInt(100) +1;
this.target.setText(String.valueOf(num));
}
}
Hope this helps!
Upvotes: 2
Reputation: 968
You need to effectively call numero.setText(num) inside of your ActionPreformed method. I would recommend maybe adding a checking statement similar to this..
if(e.getSource() == sendButton) {
numero.setText(num);
}
There is another problem I see, being that you might not be able to know the values of numero or sendButton. Offhand you could make them public variables in your main class, or you could pass them as parameters.
Upvotes: 0