import java.awt.*;
public class Scrollbar1
{
public static void main(String[] args) throws Exception
{
Frame frame=new Frame("调制颜色");
Label lColor=new Label("0,0,0");
Panel pColor=new Panel();
pColor.setBackground(new Color(0,0,0));
Scrollbar sRed=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,256);
Scrollbar sGreen=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,256);
Scrollbar sBlue=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,256);
frame.setLayout(new GridLayout(5,1));
frame.add(lColor);
frame.add(pColor);
frame.add(sRed);
frame.add(sGreen);
frame.add(sBlue);
frame.pack();
frame.setVisible(true);

Color col;
int nRed,nGreen,nBlue;
while(true)
                {
nRed=sRed.getValue();
nGreen=sGreen.getValue();
nBlue=sBlue.getValue();
pColor.setBackground(new Color(nRed,nGreen,nBlue));
lColor.setText(nRed+","+nGreen+","+nBlue);
Thread.sleep(1000);
}
         这段程序可以运行,只是我不理解这段程序为什么要死循环,我把while删了,只留下括号里的代码,但运行后,滚动条可以拉但是不能传递getValue值,为什么要循环啊 }
}

解决方案 »

  1.   

    因为你的输出要实时反映滚动条的位置变化,所以要用循环不断地进行监测,不然输出就得不到实时更新了。不过这个程序写的相当蹩脚,应该用AjustmentListener来进行事件监听,而不是用循环来做。而且,就算一定要用循环,也应该放到一个单独的线程中。
      

  2.   

    帮你整理了一下,供参考:
    import java.awt.*;
    import java.awt.event.*;public class Scrollbar1 extends Frame implements AdjustmentListener { private Label lColor;
    private Panel pColor;
    private Scrollbar sRed, sGreen, sBlue; public Scrollbar1() {
    super("调制颜色");
    lColor = new Label("0,0,0");
    pColor = new Panel();
    pColor.setBackground(new Color(0, 0, 0));
    sRed = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);
    sGreen = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256);
    sBlue = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256); sRed.addAdjustmentListener(this);  // 添加事件监听
    sGreen.addAdjustmentListener(this);  // 添加事件监听
    sBlue.addAdjustmentListener(this);  // 添加事件监听 setLayout(new GridLayout(5, 1));
    add(lColor);
    add(pColor);
    add(sRed);
    add(sGreen);
    add(sBlue);
    pack();
    setVisible(true);
    } public void adjustmentValueChanged(AdjustmentEvent e) {  // 监听程序
    int nRed, nGreen, nBlue;
    nRed = sRed.getValue();
    nGreen = sGreen.getValue();
    nBlue = sBlue.getValue();
    pColor.setBackground(new Color(nRed, nGreen, nBlue));
    lColor.setText(nRed + "," + nGreen + "," + nBlue);
    } public static void main(String[] args) throws Exception {
    new Scrollbar1();
    }
    }