How to use Slider Bar in java

In this program, we will learn the slider in java & also perform the various operation with sliders. we change the color of the text area with the slider bar in Java. If we want to use the slider bar in our program then we will have to use JSlider in our program.

Java program to change color of the text area using slider bar

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

class SliderTest implements ChangeListener
{
  JFrame fr;
  JTextArea ta;
  JSlider s1,s2,s3;
  
  SliderTest()
  {
    fr=new JFrame();
    fr.setLayout(null);
    fr.setSize(700,700);
    
    ta=new JTextArea();
    ta.setBounds(50,50,300,300);
    fr.add(ta);
    
    s1=new JSlider(0,255);
    s1.setBounds(50,370,300,50);
    fr.add(s1);
    
    
    s2=new JSlider(0,255);
    s2.setBounds(50,440,300,50);
    fr.add(s2);
    
    
    s3=new JSlider(0,255);
    s3.setBounds(50,510,300,50);
    fr.add(s3);

    
    s1.addChangeListener(this);
    s2.addChangeListener(this);
    s3.addChangeListener(this);
    s1.setMajorTickSpacing(50);
    s1.setPaintTicks(true);
    s1.setPaintLabels(true);
    fr.setVisible(true);
  }
  public void stateChanged(ChangeEvent e)
  {
    int v1=s1.getValue();
    int v2=s2.getValue();
    int v3=s3.getValue();
    Color c=new Color(v1,v2,v3);
    ta.setBackground(c);
    /*ta.setText(v1+":"+v2":"+v3);*/
  
  }
  
    
    
    public static void main(String s[])
    {
      new SliderTest();
    }
}

In this program, we will have to use a swing class & use SetMajorTickSpacing for the spacing between ticks. We also add the action listener on the slider bar we have used three slider bars. All thing is to perform on the applet.

Learn more tutorials,

Explanation of slider bar program in Java

 public void stateChanged(ChangeEvent e)
{
int v1=s1.getValue();
int v2=s2.getValue();
int v3=s3.getValue();
Color c=new Color(v1,v2,v3);
ta.setBackground(c);
/*ta.setText(v1+":"+v2":"+v3);*/
}

V1 is the variable and stored the value which is set on the slider bar 1.
V2 is the variable and stored the value which is set on the slider bar 2.
v3 is the variable and stored the value which is set on the slider bar 3.



The output of the program: Change text area color in java using slider

Here is the screenshot of the output of an example slider bar program in Java.

slider bar program in java example

Output of slider bar program in Java

Read more articles,

Leave a Reply

Your email address will not be published. Required fields are marked *