Saturday, 31 January 2015

How to use JSlider in java

Slider is a component that allows a users to check a user numeric value easily bounded by minimum and maximum value graphically.

CONSTRUCTORS OF JSLIDER:

JSlider()
JSlider(int min,int max)
JSlider(int min,int max,value)
JSlider(int orientation)
JSlider(int orientation,int min,int max,int value)
JSlider(BoundedRangeModel)

Here orientation defines that slider is vertical or horizontal,maximum and minimum values defines the starting and ending points of jslider and value defines the from which value jslider is to be initially started

setPaintTicks in java:

void setPaintTicks(boolean) allow set or not print ticks on slider

setMajorTicksSpacing in java:

set the difference between values of major and minor ticks spacing.

CODING:

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

import javax.swing.event.*;
class myjframe1 extends JFrame implements ChangeListener{

JSlider slider1,slider2;
JTextField t1,t2;
public myjframe1() {

setTitle("Simple example");
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);        
FlowLayout f=new FlowLayout();
setLayout(f);
slider1 = new JSlider(JSlider.VERTICAL);
slider1.addChangeListener(this);
add(new JLabel("slider1"));
slider1.setPaintTrack(false);
slider1.setMajorTickSpacing(10);
slider1.setPaintTicks(true);
slider1.setPaintLabels(true);
add(slider1);
add(t1 = new JTextField("Slider Value"));

slider2 = new JSlider(100,300);
slider2.addChangeListener(this);
add(new JLabel("slider2"));
add(slider2);
add(t2 = new JTextField("Slider Value"));
}
public void stateChanged(ChangeEvent ev)
{
if(ev.getSource() == slider1)
{
t1.setText(""+slider1.getValue());
}
else
{
t2.setText(""+slider2.getValue());
}
}

}

class myslide
{
public static void main(String args[])
{
myjframe1 x= new myjframe1();
}
}

OUTPUT:


No comments:

Post a Comment