gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:31:55 35 4
gpt4 key购买 nike

我在 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);
}

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

感谢您的帮助

最佳答案

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

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

关于java - 如何从另一个类更改paintComponent的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53571475/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com