【问题标题】:Java - Calling a paintComponent MethodJava - 调用paintComponent方法
【发布时间】:2014-03-04 18:28:06
【问题描述】:

我想要一个可以通过使用给定的 x,y,color 参数调用其方法来重新创建的圆。但我这样做有困难。我想将 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);
}}

【问题讨论】:

  • 我认为至少你应该将 g2 对象传递给 ring() 方法。

标签: java swing object methods paintcomponent


【解决方案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);
}

并使用graphics2D 参数调用ring()

ring(10 , 20 , "Blue", g2);

我认为应该可以。

【讨论】:

  • 非常感谢。这行得通。不过,我怎么能从另一个班级访问它?比如说,OlympicRingsComponent r = new OlympicRingsComponent(); r.ring(10 , 20 , "蓝色", g2);
  • @Neoaptt:这是一个不同的问题。一般来说,你创建一个类,用draw方法来绘制类创建的对象。
  • 您可以在OlympicRingsComponent 对象上调用repaint() 方法。它将使用适当的Graphics 对象在内部调用paint() 方法。 OlympicRingsComponent r = new OlympicRingsComponent();r.repaint();
猜你喜欢
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多