1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderDemo extends JFrame implements ActionListener {
public static void main(String[] args) {
new SliderDemo();
}
protected JSlider slider1,slider2,slider3;
protected JButton getValue;
protected JLabel l1,l2;
protected JPanel p1,p2;
protected ChangeListener listener;
public SliderDemo() {
Container content = getContentPane();
content.setBackground(Color.white);
l1=new JLabel();
l2=new JLabel();
p1=new JPanel();
listener=new SliderListener(l1);
slider3 = new JSlider(2,15);
slider3.setBorder(BorderFactory.createTitledBorder("JSlider with Tick Marks & Labels"));
slider3.setMajorTickSpacing(3);
slider3.setMinorTickSpacing(1);
slider3.setPaintTicks(true);
slider3.setPaintLabels(true);
p1.add(slider3, BorderLayout.WEST);
p1.add(l1,BorderLayout.EAST);
getValue=new JButton("getValue");
slider3.addChangeListener(listener);
content.add(getValue,BorderLayout.EAST);
content.add(p1,BorderLayout.NORTH);
getValue.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o==getValue){
System.out.println("\n"+slider3.getValue());
}
}
}
class SliderListener implements ChangeListener {
JLabel l1;
public SliderListener(JLabel f) {
l1 = f;
}
public void stateChanged(ChangeEvent e) {
JSlider s1 = (JSlider)e.getSource();
l1.setText("Value " + s1.getValue());
}
} |
Partager