使用以颜色为参数的paintComponent绘制图形
Drawing graphics with paintComponent with color as parameter
我不得不多次画两个圆圈,每次都用不同的颜色。所以我想将颜色作为参数传递给 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);
}
}
在构造函数中传递颜色并将它们保存在class成员变量中。然后覆盖绘制组件以使用这些颜色绘制圆圈
因此在测试中 class 添加此代码
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;
}
我不得不多次画两个圆圈,每次都用不同的颜色。所以我想将颜色作为参数传递给 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);
}
}
在构造函数中传递颜色并将它们保存在class成员变量中。然后覆盖绘制组件以使用这些颜色绘制圆圈
因此在测试中 class 添加此代码
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;
}