JSlider
To use a slider, we need a few changes:
Look at code below:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;
//by Ahmed
//notice that I say implements changelistener not actionlistener, this is to say that I will be listening for changes to slider
public class SliderExample extends JApplet implements ChangeListener
{
//adding jslider takes in horizontal or vertical and min value, max value and initial value marked.
JSlider weightSlider= new JSlider (JSlider.HORIZONTAL, 100,200,150);
//init is a method that gets called automatically when the applet starts or initializes
//in init we are adding our swing components to the applet
public void init()
{
Container screen = getContentPane();
screen.setBackground(Color.white);
screen.setLayout (new FlowLayout() );
screen.add(weightSlider);
weightSlider.addChangeListener(this);
}
//change listener needs statechanged
public void stateChanged(ChangeEvent e)
{
Object source = e.getSource();
if (source==weightSlider)
{
int weight=weightSlider.getValue();
}
}
}
|