如何从另一个类更改paintComponent的颜色

时间:2018-12-01 13:56:57

标签: java swing colors paintcomponent

我在OvalShape.java的面板上有一个椭圆形的组件,我想更改其颜色

public class OvalShape extends JPanel {
private int diameter = 100;
private Color myColor = Color.RED;

//create the actual panel
public OvalShape() {
    Dimension size = getPreferredSize();
    size.width = 300;
    size.height= 300;
    setPreferredSize(size);
    setBorder(BorderFactory.createLoweredSoftBevelBorder());
}

public void setMyColor(Color theColor) {
    this.myColor = theColor;
}

//create the oval
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillOval(0, 0, diameter, diameter);
    g.setColor(myColor);
}

//method for setting the diameter
public void setDiameter(int newDiameter) { //method to create diameter
    //if diam invalid set to 10
    diameter = (newDiameter >=0 ? newDiameter : 10);
    repaint(); //repaint panel
}

}

来自OvalPanel.java的

我希望能够更改颜色。这是该类的样子

public class OvalPanel extends JPanel {
public int diameter = 100; //default diameter of the oval
public JSlider diamSlider;
public JLabel diamLabel;
public OvalShape ovalShape;

public OvalPanel() {

    Dimension size = getPreferredSize();
    size.width = 500;
    setPreferredSize(size);

    //create components
    diamSlider = new JSlider(SwingConstants.HORIZONTAL, 0, 300, 100);
    diamSlider.setSnapToTicks(true);
    diamSlider.setMajorTickSpacing(100);
    diamSlider.setMinorTickSpacing(25);
    diamSlider.setPaintTicks(true);
    diamSlider.setPaintLabels(true);

    diamLabel = new JLabel("Diameter = " + diameter);
    ovalShape = new OvalShape();
    ovalShape.setDiameter(diamSlider.getValue());
    ovalShape.setMyColor(Color.RED);

    //set listeners
    diamSlider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            diamLabel.setText("Diameter = " + diamSlider.getValue());
            ovalShape.setDiameter(diamSlider.getValue());
        }
    });


    //set layout
    setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    ////////first row////////
    gbc.gridx = 0;
    gbc.gridy = 0;
    add(ovalShape, gbc);

    ////////second row////////
    gbc.gridx = 0;
    gbc.gridy = 1;
    add(diamSlider, gbc);

    ////////third row////////
    gbc.gridx = 0;
    gbc.gridy = 2;
    add(diamLabel, gbc);
}

但是我真的不明白为什么这不起作用。椭圆形刚变成黑色。我尝试应用与创建直径滑块时相同的理论,因为我能够使用OvalPanel.java中的滑块更改椭圆的直径

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

g.fillOval(0, 0, diameter, diameter);
g.setColor(myColor);

在绘制椭圆形之前,需要设置颜色。