如何更改for循环中的设置颜色?

时间:2014-02-03 20:20:44

标签: java colors draw fill

我的圆圈会改变颜色,但是最小的圆圈总是保持红色,最大的圆圈不会保持蓝色。每当我尝试从现在改变代码时,所有圆圈都会变成相同的颜色,只需在移动滑块时更改阴影。当滑块增加时,我希望红色和蓝色之间有更多的阴影。你能解释我需要做出的改变吗?我理解我正在做的一切,除了变色部分。

public class SliderLab1 extends JFrame {
JSlider slider;
GPanel graphicsPanel;

public SliderLab1() {
  super("Slider/Shapes Demo");
  setDefaultCloseOperation(
     JFrame.EXIT_ON_CLOSE );

  JPanel outerPanel = new JPanel();
  graphicsPanel = new GPanel();  //for shapes
  JPanel sliderPanel = new JPanel();

  setup(sliderPanel);

  outerPanel.add(graphicsPanel);
  outerPanel.add(sliderPanel);
  add(outerPanel);
  pack();
  setVisible(true);
}

private void setup(JPanel p) {
  slider = new JSlider(
        JSlider.VERTICAL,4,20,8);
  slider.setMinorTickSpacing(1);
  slider.setMajorTickSpacing(4);
  slider.setPaintTicks(true);
  slider.setPaintLabels(true);
  slider.addChangeListener( new SLstn() );

  p.add(slider);
}

private class SLstn implements ChangeListener {
  public void stateChanged(ChangeEvent e) {
     int x = slider.getValue();
     System.out.println(x);
     graphicsPanel.setCount(x);
     graphicsPanel.repaint();
  }
}

private class GPanel extends JPanel {
  int count = 8;
  int size = 400;
  int stepSize = (int)size/count;

  public GPanel() {
     setPreferredSize(
        new Dimension(size,size));
     setBackground(Color.BLACK);
  }

  public void setCount(int n) {
     count=n;
     stepSize = (int)size/count;
  }
  public void paint(Graphics g) {
     super.paint(g);
     Graphics2D g2d = (Graphics2D)g; 
     g2d.setStroke(new BasicStroke(3) );         

     for(int i = count; i>=0; i--){
        Color myC = new Color(((255/stepSize)*(stepSize-i)), 0, (255/stepSize)*i );
        g.setColor(myC);


        for (int j = 0; j <= count; j++) {
           g.drawOval(0,(size-(stepSize*i)),stepSize*i,stepSize*i);
           g.fillOval(0,(size-(stepSize*i)),stepSize*i,stepSize*i);   
        }

     }

  }

}

public static void main(String[] args) {
  new SliderLab1();
}
}

1 个答案:

答案 0 :(得分:0)

简单地替换:

Color myC = new Color(((255/stepSize)*(stepSize-i)), 0, (255/stepSize)*i );

由:

final Color myC = new Color(((255 / count) * (count - i)), 0, (255 / count) * i);

此时您不想使用stepSize,使用count应该诀窍:) 我希望它有所帮助!