Search code examples
javajslider

How to move jslider its start position to end postion automatically when pressing a button in java


I have a code below

               jSlider1.setValue(0); 
               int i =0;
               while (i <= jSlider1.getMaximum()) {


                    jSlider1.setValue(i);


            // JOptionPane.showMessageDialog(rootPane,"deded");
             Thread.sleep(2000);
              i++;
        }

What I want is I want to move JSlider automatically its min to max value. I have writeen above code. But I can not get the output. But when I remove the comment of "JOptionPane.showMessageDialog(rootPane,"deded"); " , It's work properly with the message. Please help me. I am in big trouble. I like to have a sample code if any one know the sollution. Thank you


Solution

  • I am assuming you have create some JPanel or JFrame where you add this slider so,

    final JSlider jSlider1 = new JSlider();
        jSlider1.setValue(0);
        jSlider1.setMaximum(100);
        jSlider1.setBounds(0, 50, 300, 50);
        final Timer increaseValue = new Timer(50, new ActionListener() {// 50 ms interval in each increase.
            public void actionPerformed(ActionEvent e) {
                if (jSlider1.getMaximum() != jSlider1.getValue()) {
                    jSlider1.setValue(jSlider1.getValue() + 1);
                } else {
                    ((Timer) e.getSource()).stop();
                }
            }
        });
        panel.add(jSlider1);
        JButton moveSlider = new JButton("Start");
        moveSlider.setBounds(10, 106, 55, 30);
        moveSlider.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                increaseValue.start();
            }
        });
        panel.add(moveSlider);