代码之家  ›  专栏  ›  技术社区  ›  Roger

Java-调用paintComponent方法

  •  0
  • Roger  · 技术社区  · 11 年前

    我希望有一个圆,可以通过使用给定的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);
    }}
    
    1 回复  |  直到 11 年前
        1
  •  1
  •   Sourabh Bhat    11 年前

    需要添加 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);
    }
    

    并呼叫 环() 使用 图形2D 参数:

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

    我认为这应该行得通。