代码改变世界

一个JSlider的例子

2011-05-25 11:24  Rollen Holt  阅读(9065)  评论(3编辑  收藏  举报

关于JSlider,大家可以先去这里看看它的API  http://download.oracle.com/javase/tutorial/uiswing/components/slider.html

运行结果为:image 大家可以在此基础上尝试加上刻度,呵呵微笑

  1: /**
  2:  * 窗口中使用三个JLabel、三个JSlider和三个JTextField,
  3:  * 三个JLabel分别显示“红”、“绿”、“蓝”,三个JSlider的取值范围设定为从0到255,
  4:  * 三个JTextField分别显示对应JSlider的当前值,
  5:  * 程序中用三个JSlider选定的值作为参数构造一个颜色,将窗口的背景色设定为该颜色。
  6:  */
  7: 
  8: /**
  9:  * @author Rolen Holt
 10:  * @version 25/5/2011
 11:  */
 12: import java.awt.*;
 13: 
 14: import javax.swing.*;
 15: import javax.swing.event.ChangeEvent;
 16: import javax.swing.event.ChangeListener;
 17: 
 18: import java.awt.event.*;
 19: 
 20: public class JSliderDemo extends JFrame implements ChangeListener{
 21: 	
 22: 	JTextField textField1;
 23: 	JTextField textField2;
 24: 	JTextField textField3;
 25: 	
 26: 	JLabel label1;
 27: 	JLabel label2;
 28: 	JLabel label3;
 29: 	
 30: 	JSlider slider1;
 31: 	JSlider slider2;
 32: 	JSlider slider3;
 33: 	
 34: 	JPanel panel;
 35: 	
 36: 	JSliderDemo(){
 37: 		setTitle("JSliderDemo");
 38: 		setSize(500,500);
 39: 		setVisible(true);
 40: 		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 41: 		
 42: 		label1=new JLabel("");
 43: 		label2=new JLabel("绿");
 44: 		label3=new JLabel("");
 45: 		
 46: 		textField1=new JTextField(5);
 47: 		textField2=new JTextField(5);
 48: 		textField3=new JTextField(5);
 49: 		
 50: 		slider1=new JSlider(JSlider.HORIZONTAL,0,255,125);
 51: 	
 52: 		
 53: 		slider2=new JSlider(JSlider.HORIZONTAL,0,255,125);
 54: 	
 55: 		
 56: 		slider3=new JSlider(JSlider.HORIZONTAL,0,255,125);
 57: 
 58: 		
 59: 		panel=new JPanel();
 60: 		
 61: 		panel.add(label1);
 62: 		panel.add(slider1);
 63: 		panel.add(textField1);
 64: 		panel.add(label2);
 65: 		panel.add(slider2);
 66: 		panel.add(textField2);
 67: 		panel.add(label3);
 68: 		panel.add(slider3);
 69: 		panel.add(textField3);
 70: 		add(panel);
 71: 
 72: 		slider1.addChangeListener(this);
 73: 		slider2.addChangeListener( this);
 74: 		slider3.addChangeListener( this);
 75: 	}
 76: 	
 77: 	public void stateChanged(ChangeEvent event){
 78: 		if((JSlider)event.getSource()==slider1){
 79: 			String str=""+slider1.getValue();
 80: 			textField1.setText(str);
 81: 		}
 82: 		if((JSlider)event.getSource()==slider2){
 83: 			String str=""+slider2.getValue();
 84: 			textField2.setText(str);
 85: 		}
 86: 		if((JSlider)event.getSource()==slider3){
 87: 			String str=""+slider3.getValue();
 88: 			textField3.setText(str);
 89: 		}
 90: 		panel.setBackground(new Color(slider1.getValue(),slider2.getValue(),slider3.getValue()));
 91: 	}
 92: 	
 93: 	public static void main(String[] args){
 94: 		new JSliderDemo();
 95: 	}
 96: }
 97: