我必须多次画两个圆圈,每次都用不同的颜色。所以我想将颜色作为参数传递给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);
}
}
答案 0 :(得分:3)
传递构造函数中的颜色并将它们保存在类成员变量中。然后重写paint组件以使用这些颜色绘制圆圈
所以在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;
}