gpt4 book ai didi

java - 使用paintComponent以颜色为参数绘制图形

转载 作者:行者123 更新时间:2023-12-01 21:28:12 24 4
gpt4 key购买 nike

我必须多次绘制两个圆圈,每次都使用不同的颜色。所以我想将颜色作为参数传递给paintComponent 方法。但如果我这样做,父类(super class) JPanel 的方法将不会被重写。我应该怎么办?这是我的代码:

public class Test extends JPanel{

Ellipse2D oval;

public void paintComponent(Graphics g){
super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;

oval = new Ellipse2D.Double(137, 0, 40, 40);
g2.setPaint(Color.black); //color I want to pass as argument
g2.fill(oval);

oval = new Ellipse2D.Double(420, 0, 40, 40);
g2.setPaint(Color.red); //color I want to pass as argument
g2.fill(oval);
}
}

我想在调用构造函数时传递颜色:

public class MyFrame extends JFrame {
Test t1, t2;

public MyFrame(){
//setSize, setTitle...

t1 = new Test(); // would pass the colors in here
t2 = new Test(); // would pass the colors in here

add(t1);
add(t2);
setVisible(true);
}
}

最佳答案

在构造函数中传递颜色并将它们保存在类成员变量中。然后覆盖绘制组件以使用这些颜色来绘制圆

因此在 Test 类中添加此代码

private java.awt.Color insideColor;
private java.awt. Color outsideColor;

public class Test (java.awt.Color inside, java.awt.Color outside){
this.insideColor = inside;
this.outsideColor = outside;
}

关于java - 使用paintComponent以颜色为参数绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780864/

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