我想要一个可以通过使用给定的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);
}}
答案 0 :(得分:1)
需要将graphics2D
参数添加到ring()
方法,如下所示:
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);
}
并使用ring()
参数调用graphics2D
:
ring(10 , 20 , "Blue", g2);
我认为这应该有用。