我尝试编写一个代码来从左上角到右下角绘制一个椭圆形运行。但是当我运行程序时,它会在应用程序上显示空白屏幕。 为什么会这样?
这是我的代码:
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
答案 0 :(得分:1)
您应该覆盖paintComponent()
而不是paintComponents()
。
所以将public void paintComponents() {...}
更改为public void paintComponent() {...}
但仅仅是提示:
尝试使用Timers而不是Threads。总是尽量不要乱摇摆线。在您的情况下,您可以使用javax.swing.Timer以50 ms的间隔调用重绘:
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 t
和int counter
是您班级的成员变量。
祝你好运。
答案 1 :(得分:0)
您没有致电super.paintComponent(g);
,也需要拨打paintComponents
而不是repaint
方法。请尝试使用以下代码。我希望它有所帮助:)
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
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.paintComponents(drawPanel.getGraphics());
try {
Thread.sleep(50);
} catch (Exception ex) {
}
}
} // close go() method
class MyDrawPanel extends JPanel {
@Override
public void paintComponents(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.drawOval(50, 50, 50, 50);
g.setColor(Color.green);
g.fillOval(x, y, 40, 40);
}
} // close inner class
} // close outer class