gpt4 book ai didi

java - 图形应用程序仅显示空白屏幕

转载 作者:行者123 更新时间:2023-11-30 08:03:18 24 4
gpt4 key购买 nike

我尝试编写一段代码来绘制从左上到右下的椭圆形。但是当我运行程序时,它在应用程序上显示空白屏幕。为什么会发生这种情况?

这是我的代码:

import javax.swing.*;
import java.awt.*;

public class SimpleAnimation {
int x = 70;
int y = 70;

public static void main(String[] arg){
SimpleAnimation gui = new SimpleAnimation();
gui.go();
}

public void go(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(drawPanel);
frame.setSize(300, 300);
frame.setVisible(true);

for (int i = 0; i < 130; i++){
x++;
y++;

drawPanel.repaint();

try{
Thread.sleep(50);
} catch(Exception ex){}
}
} // close go() method

class MyDrawPanel extends JPanel{
@Override
public void paintComponents(Graphics g) {
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
} // close inner class
} // close outer class

最佳答案

您应该重写 paintComponent() 而不是 paintComponents()

因此将 public void PaintComponents() {...} 更改为 public void PaintComponent() {...}

但只是为了提示:

尝试使用计时器而不是线程。始终尽量不要弄乱 Swing 线。在您的情况下,您可以使用 javax.swing.Timer 以 50 毫秒的间隔调用重绘:

counter = 0;
t = new Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(counter>=130)
t.stop();

counter++;
x++;
y++;
drawPanel.repaint();
}
});
t.start();

javax.swing.Timer tint counter 是类的成员变量。

祝你好运。

关于java - 图形应用程序仅显示空白屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31559436/

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