1 import java.awt.*;
2 import java.util.HashMap;
3 import javax.swing.*;
4 import javax.swing.event.ChangeEvent;
5 import javax.swing.event.ChangeListener;
6
7 public class TestJSlider
8 {
9 public TestJSlider()
10 {}
11 public static void main(String args[])
12 {
13 //构建一个窗体容器
14 JFrame frame = new JFrame("test");
15 frame.setLayout (null);
16 frame.setSize (400,400);
17 //构建一个测试容器
18 TestPanel panel = new TestPanel();
19 panel.setBounds (100,100,300,300);
20 frame.add (panel);
21 //构建一个滚动条
22 JSlider slider = new JSlider ();
23 //设置滑块的标尺距离
24 slider.setMajorTickSpacing (5);
25 //设置滑块自动接近
26 slider.setSnapToTicks (true);
27 //设置是否在滑块上显示标尺
28 slider.setPaintTicks(true);
29 slider.setOrientation (JSlider.HORIZONTAL);
30 slider.setBounds (0,0,300,100);
31 frame.add (slider);
32
33 frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
34 frame.setVisible (true);
35 //构建一个事件鉴听
36 SliderListener listener = new SliderListener(slider,panel);
37 slider.addChangeListener (listener);
38 }
39 }
40 class SliderListener implements ChangeListener
41 {
42 private JSlider slider;
43 private TestPanel panel;
44 public SliderListener(JSlider slider,TestPanel panel)
45 {
46 super();
47 this.slider = slider;
48 this.panel = panel;
49 }
50 public void stateChanged(ChangeEvent e)
51 {
52 if(e.getSource ()==slider)
53 {
54 panel.setHeight (slider.getValue ());
55 panel.setWidth (slider.getValue ());
56
57 }
58 }
59 }
60 class TestPanel extends JPanel
61 {
62 private int w = 100;
63 private int h = 100;
64 public TestPanel()
65 {
66 super();
67 }
68 public void setWidth(int a)
69 {
70 this.w = a;
71 repaint();
72 }
73 public void setHeight(int b)
74 {
75 this.h = b;
76 repaint();
77 }
78 public void paintComponent(Graphics g)
79 {
80 super.paintComponent (g);
81 g.fillOval (0,0,w,h);
82 }
83 }
84
posted on 2007-02-06 16:01
-274°C 阅读(366)
评论(0) 编辑 收藏 所属分类:
JAVA