如果在for循环后添加球,为什么球没有出现在框架中?

如果在for循环后添加球,为什么球没有出现在框架中?,第1张

如果在for循环后添加球,为什么球没有出现在框架中? 需要记住的几点:
  1. 不要
    Thread.sleep()
    在某个时候挂起整个Swing应用程序,而尝试使用最适合Swing应用程序的Swing Timer。

了解更多如何使用Swing计时器

  1. 不要忘记调用

    super.paintComponent()
    覆盖的
    paintComponent()
    方法。

  2. frame.setVisible(true)
    添加完所有组件后,最后调用。

  3. 根据组件的首选大小使用

    frame.pack()
    代替
    frame.setSize(500,500)
    组件的大小。

  4. 覆盖

    getPreferredSize()
    以设置
    JPanel
    自定义绘画的首选大小。

  5. 使用SwingUtilities.invokeLater()或EventQueue.invokeLater() 来确保正确初始化了EDT。

阅读更多

* [为什么要在main方法中使用SwingUtilities.invokeLater?](https://stackoverflow.com/questions/15302085/why-to-use-swingutilities-invokelater-in-main-method)* [SwingUtilities.invokeLater](https://stackoverflow.com/questions/7196889/swingutilities-invokelater)* [我们是否应该在Java桌面应用程序中使用EventQueue.invokeLater进行GUI更新?](https://stackoverflow.com/questions/3541373/should-we-use-eventqueue-invokelater-for-any-gui-update-in-a-java-desktop-applic)

示例代码:改成按你的风俗画

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4919563.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存