I’m writing a WidgetViewer GUI where when the “go up/up” button is pushed, a random number between 1 and 10 (inclusive) is generated and added to the left label, and another random number between 1 and 10 (inclusive) is generated and added to the right label.
The widgets required are: a button labeled “go up/up”, a label initialized to 0 (left label), and a label initialized to 0 (right label).
This is what I have so far:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Jbutton;
import javax.swing.JLabel;
public class UpDown {
private JLabel jleft;
private JLabel jright;
public UpDown() {
WidgetViewer wv = new WidgetViewer();
jleft = new JLabel("0");
jright = new JLabel("0");
JButton upUp = new JButton("go up/up");
upUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String lval = jleft.getText();
int newlVal = Integer.parseInt(lval) + 1 + (int)(Math.random() * (10));
jleft.setText(String.valueOf(newlVal));
String rval = jright.getText();
int newrVal = Integer.parseInt(rval) + 1 + (int)(Math.random() * (10));
jleft.setText(String.valueOf(newrVal));
}
});
}
However, when I run this and when I click the button, it only shows a new number each time without adding to it. How can I make it increment each time?
Advertisement
Answer
left value is processed correcty, the right value is calculated correctly too … but stored in the ui-element of the left value …
jleft.setText(String.valueOf(newrVal));
=> overwriting the just previously correct left value, resetting it. just replace with
jright.setText(String.valueOf(newrVal));