문제

My circles change color, but while the smallest one always remains red, the largest does not remain blue. Whenever I attempt to change my code from what it is now, all circles become the same color, and just change shade when the slider is moved. I would like there to just be more shades in between the red and blue as the slider increases. Could you please explain the changes I need to make? I understand everything I'm doing, except the color changing part.

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();
}
}
도움이 되었습니까?

해결책

Simply replace:

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

by:

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

You don't want to work with stepSize at this point, using count should do the trick :)
I hope it helps!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top