/ / Java Swingで単純な円を描くことができない - java、swing、awt、java-2d

Java swingを使って単純な円を描くことはできません - java、swing、awt、java-2d

私は本当に明白な何かを見逃していると思いますが、どういうわけかこのコードは私に空のウィンドウを与えますが、それは赤い楕円形を描画しません。何が足りないの?

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);
}

}

回答:

回答№1は4

その paintComponent 正しくない、これを削除 g = this.getGraphics();

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);
...
}