gpt4 book ai didi

java - 用Java swing画一个简单的圆不起作用

转载 作者:行者123 更新时间:2023-12-01 18:02:17 25 4
gpt4 key购买 nike

我认为我错过了一些非常明显的东西,但不知何故,这段代码确实给了我一个空窗口,但它没有绘制红色椭圆形。我错过了什么?

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

}

最佳答案

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

关于java - 用Java swing画一个简单的圆不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com