我想要一个可以通过使用给定的 x、y、颜色参数调用其方法来重新创建的圆。但我很难这样做。我想将 JComponent 用作对象而不是组件。
public class OlympicRingsComponent extends JComponent {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.translate(10, 10);
g2.setStroke(new BasicStroke(7));
Ellipse2D.Double circle = new Ellipse2D.Double(0,0,100,100);
g2.setPaint(Color.BLUE);
g2.draw(circle);
}}
这段代码工作正常。但我希望能够调用一个方法来创建一个新的椭圆。
public class OlympicRingsComponent extends JComponent {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.translate(10, 10);
g2.setStroke(new BasicStroke(7));
ring(10 , 20 , "Blue");
}
public void ring(int x , int y , String color) {
Ellipse2D.Double circle = new Ellipse2D.Double( x , y ,100,100);
g2.setPaint(Color.getColor(color));
g2.draw(circle);
}}
最佳答案
需要向 ring()
方法添加 graphics2D
参数,如下所示:
public void ring(int x , int y , String color, graphics2D g2) {
Ellipse2D.Double circle = new Ellipse2D.Double( x , y ,100,100);
g2.setPaint(Color.getColor(color));
g2.draw(circle);
}
并使用graphics2D
参数调用ring()
:
ring(10 , 20 , "Blue", g2);
我认为这应该有效。
关于Java - 调用paintComponent方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22180008/