日期:2014-05-20  浏览次数:20736 次

用JSlider设置Color(未达到效果)
我那个小例子的目的是通过red、blue、green三个块来设置Color的三分量,
可是老达不到预期的结果!

//源码
import   javax.swing.*;
import   javax.swing.event.*;
import   java.awt.*;
import   java.awt.event.*;

public   class   MyColorSliderTest
{
public   static   void   main(String[]   args)
{
MyColorSliderFrame   frame=new   MyColorSliderFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

/**
      MyColorSliderFrame
*/
class   MyColorSliderFrame   extends   JFrame
{
public   MyColorSliderFrame()
{
setTitle( "My   Color   Slider   Test ");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);

//初始化暂存颜色的变量
red=green=blue=256/2;

//sliderPanel
sliderPanel=new   JPanel();
sliderPanel.setLayout(new   GridLayout(3,1));

//事件监听器
listener=new   ChangeListener()
{
public   void   stateChanged(ChangeEvent   event)
{
JSlider   slider=(JSlider)event.getSource();
int   value=slider.getValue();

//这种算法,我并不是很认同,但又找不到时别的方法
if((value!=red)&&(value==blue)&&(value==green))
{
red=value;
demoPanel.setBackground
(new   Color(value,green,blue));
}
else
{
if((value!=green)&&(value==red)
&&(value==blue))
{
green=value;
demoPanel.setBackground
(new   Color(red,value,blue));
}
else
{
blue=value;
demoPanel.setBackground
(new   Color(red,green,value));
}
}
}
};

//redSlider
JSlider   redSlider=new   JSlider(0,255,256/2);
addSlider(redSlider, "red ");

//greenSlider
JSlider   greenSlider=new   JSlider(0,255,256/2);
addSlider(greenSlider, "green ");

//blueSlider
JSlider   blueSlider=new   JSlider(0,255,256/2);
addSlider(blueSlider, "blue ");

demoPanel=new   JPanel();
demoPanel.setBackground(new   Color(128,128,128));
add(sliderPanel,BorderLayout.CENTER);
add(demoPanel,BorderLayout.SOUTH);
}

//添加Slider
public   void   addSlider(JSlider   s,String   description)
{
s.addChangeListener(listener);
JPanel   panel=new   JPanel();
panel.add(s);
panel.add(new   JLabel(description));
sliderPanel.add(panel);
}

private   JPanel   demoPanel;
private   JPanel   sliderPanel;
private   ChangeListener   listener;
private   int   red,green,blue;

public   static   final   int   DEFAULT_WIDTH=400;
public   static   final   int   DEFAULT_HEIGHT=400;

}


------解决方案--------------------
你的那个处理颜色的算法确实不怎么对,只要把你程序里面的 "事件监听器 "以下的程序换成我这个就好使了,代码如下:
//事件监听器
listener=new ChangeListener()
{
int redValue = 256/ 2, greenValue = 256 / 2, blueValue = 256 /2;
public void stateChanged(ChangeEvent event)
{
JSlider slider=(JSlider)event.getSource();
//这种算法,我并不是很认同,但又找不到时别的方法
if(slider == redSlider)
redValue = redSlider.getValue();
if(slider == greenSlider)