Skip to content

How to increment numbers using Event Listeners and Widget Viewer in Java?

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));
                              String rval = jright.getText();
                              int newrVal = Integer.parseInt(rval) + 1 + (int)(Math.random() * (10));

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?



left value is processed correcty, the right value is calculated correctly too … but stored in the ui-element of the left value …


=> overwriting the just previously correct left value, resetting it. just replace with

User contributions licensed under: CC BY-SA
8 People found this is helpful