2016-10-10 73 views
0

我想我错过了一些非常明显的东西,但不知何故,这段代码确实给了我一个空的窗口,但它并没有画出红色的椭圆形。我错过了什么?用Java swing绘制一个简单的圆圈不起作用

public class Test extends JPanel { 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponents(g); 
     g = this.getGraphics(); 
     Graphics2D g2 = (Graphics2D) g; 

     // Anti-aliasing 
     g2.setColor(new Color(255, 0, 0)); 
     g2.fillOval(0, 0, 20, 20); 
    } 

    public static void main(String[] args) { 
     JFrame frame = new JFrame("Ball"); 
     Test panel = new Test(); 

     frame.getContentPane().add(panel); 
     frame.setPreferredSize(new Dimension(250, 200)); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     frame.pack(); 
     frame.setVisible(true); 
    } 

} 
+2

'克= this.getGraphics();'首先,移除无义。已经有一个有效的'Graphics'对象可以用来绘画。 –

+0

使用传递给paintComponent的图形。 –

回答

4

的paintComponent是不正确的,删除​​此​​

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D)g; 

    Ellipse2D.Double circle = new Ellipse2D.Double(xR, yR, diameter, diameter); 
    g2d.fill(circle); 
    ... 
}