【发布时间】:2016-10-13 08:20:14
【问题描述】:
我必须多次绘制两个圆圈,每次都使用不同的颜色。所以我想将颜色作为参数传递给 paintComponent 方法。但如果我这样做,超类 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);
}
}
【问题讨论】:
-
如何将两种颜色作为变量存储在测试中。然后通过构造函数来设置颜色。
-
顺便说一句,您可能希望保存 Graphics 对象的初始颜色,然后将其更改为您想要的颜色,最后在完成后将其重置。只是一个习惯,我不必对绘制的颜色感到惊讶
标签: java swing graphics colors paintcomponent