【问题标题】:why paint method not being called in snake game为什么在蛇游戏中不调用绘画方法
【发布时间】:2014-06-20 21:46:10
【问题描述】:
@SuppressWarnings("serial")
class GUI extends JPanel implements ActionListener
{

    public void paint(Graphics g)
    {
        super.paint(g);
        System.out.println("In here...");
        g.drawRect(frame.getWidth()/2,frame.getHeight()/2,(frame.getWidth()/2)+5,(frame.getHeight()/2+5));
        g.setColor(Color.BLACK);
        g.fillRect(frame.getWidth()/2,frame.getHeight()/2,(frame.getWidth()/2)+5,(frame.getHeight()/2+5));
    }

    @Override
    public void actionPerformed(ActionEvent ae) 
    {
        if(ae.getSource() == slow)
        {
            this.setMotionToSnake(slowMotion);  
            this.repaint();
        }

}
}

我正在编写一个蛇游戏程序。在执行该绘制方法时,不会调用该方法。 解释代码: 我在我的框架中添加了一个菜单栏 在该菜单栏中,开始是一个菜单,其中包含 3 个子菜单,即慢、中、快。 每当我说慢动作时,蛇的动作就决定了,现在我应该能够在框架中看到一个矩形框(至少)。 这就是我在那里调用重绘方法的原因。

除了 this.repaint() 我还使用了 frame.repaint() / 只是 repaint()。 但是方法没有被调用。

感谢您的帮助。

【问题讨论】:

  • 也供参考--->我使用流布局管理器frame.setLayout(new FlowLayout());
  • Searching 在发布之前可能会有所帮助,例如有this question
  • 1) 为了尽快获得更好的帮助,请发布MCVE(最小完整且可验证的示例)。 2)public void paint(Graphics g) { super.paint(g); 应该是public void paintComponent(Graphics g) { super.paintComponent(g);

标签: java swing actionlistener paintcomponent repaint


【解决方案1】:

我正在使用流布局管理器 frame.setLayout(new FlowLayout());

FlowLayout 尊重添加到面板的所有组件的大小。您正在创建一个自定义组件,默认情况下您的组件的大小为 (0, 0),因此无需绘制任何内容。

覆盖您的自定义组件的getPreferredSize() 以返回适合您的组件的维度。

此外,自定义绘画是通过覆盖 paintComponent(...) 方法而不是 paint() 方法来完成的。

阅读 Custom Painting 上的 Swing 教程部分,了解更多信息和展示如何执行此操作的工作示例。

【讨论】:

    猜你喜欢
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多