该程序使一个球从左上角滑到右下角并运行。但如果我改变路线
frame.getContentPane().add(ball);
从当前位置到for循环之后,为什么球没有出现在框架上。 我同意球不应该再移动,因为 for 循环中完成的所有移动甚至在我将球添加到 JFrame 之前就发生了,但我不明白为什么当我最终时球没有显示在屏幕上将其添加到框架中。 这是工作程序的代码,如果将上面提到的行移到for循环后面,球就不再显示
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Animate
{
private JFrame frame;
private int x,y;
public static void main(String args[])
{
Animate ballRoll = new Animate();
ballRoll.go();
}
public void go()
{
frame = new JFrame();
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyRoll ball = new MyRoll();
frame.getContentPane().add(ball);
for(x = 5;x<=350;x++)
{
y=x;
try
{
Thread.sleep(50);
}
catch(Exception e)
{
System.out.println("dsfsd");
}
ball.repaint();
}
}
class MyRoll extends JPanel
{
public void paintComponent(Graphics g)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(Color.ORANGE);
g.fillOval(x, y, 100, 100);
}
}
}
最佳答案
需要记住的一些要点:
不要使用有时会挂起整个 swing 应用程序的
Thread.sleep()
,而是尝试使用 Swing Timer最适合 Swing 应用。不要忘记在重写的
paintComponent()
方法中调用super.paintComponent()
。添加完所有组件后最后调用
frame.setVisible(true)
。使用
frame.pack()
而不是frame.setSize(500,500)
来根据组件的首选尺寸适合组件。重写
getPreferredSize()
以设置自定义绘画时JPanel
的首选大小。使用SwingUtilities.invokeLater()或EventQueue.invokeLater()确保EDT已正确初始化。
了解更多
示例代码:(根据您的自定义绘画进行更改)
private Timer timer;
...
timer = new javax.swing.Timer(50, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
y = ++x;
ball.repaint();
if (x > 350) {
timer.stop();
}
}
});
timer.setRepeats(true);
timer.start();
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Animate ballRoll = new Animate();
ballRoll.go();
}
});
}
class MyRoll extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...
}
@Override
public Dimension getPreferredSize() {
return new Dimension(..., ...);
}
}
关于java - 如果我在 for 循环之后添加球,为什么球不会出现在框架中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24340271/