【问题标题】:Repaint never reaches paintComponent();重绘永远不会到达paintComponent();
【发布时间】:2017-10-17 11:37:52
【问题描述】:

swing 遇到了一个关于 java-graphics 的问题...我想在 jframe 上画一些东西,代码如下:

PaintUtil 类:

public class PaintUtil extends JPanel{

public PaintUtil(){
    this.setFocusable(true);
    this.requestFocus();
}

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        System.out.println("Repainted");

        g.drawstuff...
    }
}

主类:

public static PaintUtil util = new PaintUtil();

JFrame frame = new JFrame();
frame.setSize(500,600);
frame.setRezisable(false);
frame.add(util);
frame.setDefaultCloseOperation( 3 );
frame.getContentPane().setColor(Color.BLACK);
setup(); //This add some buttons
frame.setVisible(true);

util.repaint(); //not working
util.paintComponent(frame.getGraphics()); //works

你们能帮帮我吗?

【问题讨论】:

  • PaintUtil 扩展了什么?
  • PaintUtil 扩展 JPanel
  • 你的组件真的在屏幕上吗?
  • repaint 只不过是对RepaintManager 的请求,它将决定何时触发绘制周期。组件可能不被绘制的原因有很多,大多数处理优化,例如不绘制在屏幕上实现的组件或大小为0x0 的组件。我们当然可以继续“猜测”您问题的原因,或者您可以发送runnable example which demonstrates your actual problem
  • 在说“这不起作用”时,您至少可以更具体一点,为什么?怎么了 ?错误?你的预期结果是什么?!

标签: java swing graphics repaint


【解决方案1】:

没有错误,控制台中没有消息,什么都没有

frame.setLayout(null);

不要使用空布局。 Swing 旨在与布局管理器一起使用。摆脱这种说法。

默认情况下,面板的大小为 (0, 0),因此无需绘制任何内容。

您需要覆盖面板的 getPreferredSize() 方法,以便布局管理器可以完成其工作。

阅读 Custom Painting 上的 Swing 教程部分,了解更多信息和工作示例。

【讨论】:

  • 好的,现在我已经消除了空布局,但仍然存在同样的问题
  • 我应该打印完整的课程吗?但是,只有当您专注于我提出的问题而不是其他不好的问题时,我才知道;)
  • @Caipi,发布正确的minimal reproducible example 来说明问题。
  • 好吧,现在一切都需要了。 util.repaint();不工作和 frame.paintComponent(frame.getGraphics());有效,但不会删除旧的东西:(
  • @Caipi, Okey now there is everything nessesary - 不,它不完整。你没有覆盖 getPreferredSize(),所以你没有听我的建议或阅读教程。您不应该调用 repaint() 或 paintComponent()。看教程!!!下载工作代码并根据您的要求进行修改。
猜你喜欢
  • 2021-04-15
  • 2020-04-12
  • 2021-11-02
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多