Search code examples
javaadditionjslider

adding two numbers given by JSliders


suppose we want to add two numbers (0 <= n <= 20) that user specify with two JSliders and print it. the problem is when i assign JSliders' value to x and y variables, they just don't hold the new value and hold 0 (at first they're initialized with 0), here is the code:

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class GUIJframe extends JFrame {

    private JPanel jp1 = new JPanel();
    private JTextField jtf = new JTextField();
    private JTextField jtf2 = new JTextField();
    private JSlider js1 = new JSlider(0,20);
    private JSlider js2 = new JSlider(0,20);
    private int x = 0;
    private int y = 0;

    public GUIJframe () {

        setSize(400,400);
        setLocation(200,200);
        setLayout(new GridLayout(5,1));
        add(js1);
        add(jtf);
        add(js2);
        add(jtf2);
        Handler h = new Handler();
        Handler2 h2 = new Handler2();
        js1.addChangeListener(h);
        js2.addChangeListener(h2);
        setVisible(true);
        System.out.println(x + y);

    }

    private class Handler implements ChangeListener {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider js = (JSlider) e.getSource();

            jtf.setText( "" + js.getValue() );
            x = js.getValue();
        }
    }
    private class Handler2 implements ChangeListener {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider js = (JSlider) e.getSource();

            jtf2.setText( "" + js.getValue() );
            y = js.getValue();
        }
    }
}

Solution

  • You are printing x+y only one time when both x,y are zeros, it's before you even move the sliders. You can add System.out.println(x + y); in Handler or Handler1 then if you move slider it will display the sum.