【问题标题】:JPanel rapidly toggling isDisplayable()JPanel 快速切换 isDisplayable()
【发布时间】:2016-03-14 12:20:43
【问题描述】:

基本上,我正在编写基于扫雷的游戏,并且很难让网格正确渲染。网格的类扩展 JPanel,并正确添加到 JFrame。

这是我的渲染方法:

public void buildTexture(){
    if(this.isDisplayable()){
        System.out.println("Can display panel");
        image = this.createImage(this.getWidth(), this.getHeight());
        Graphics g = image.getGraphics();
        g.setColor(Color.gray);
        g.fillRect(0, 0, image.getWidth(this), image.getHeight(this));
        Tile[][] t = getCurrentSide();
        for(int a = 0; a < t.length; a++){
            for(int b = 0; b < t.length; b++){
                if(t[a][b].visible){
                    Image i = t[a][b].getCurrentImage();
                    g.drawImage(i, 20*a, 20*b, this);
                }
            }
        }
        this.prepareImage(image, this);
        g.dispose();
    }else{
        System.out.println("Cannot display panel");
    }
}

image是一个Image,声明为:

image = createImage(getWidth(), getHeight());

上面的方法被这个线程调用,在构造函数中定义并启动。

Thread repainter = new Thread(){

        @Override
        public void run() {
            while (repaint) {
                buildTexture();
                repaint();
                try {
                    sleep(20);//50 ticks a second
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }

    };
    repainter.start();

基本上,问题如下:使用此代码,输出如下所示:

Cannot display panel
Can display panel
Can display panel
Cannot display panel
Cannot display panel
Can display panel
Cannot display panel
Can display panel
Can display panel
Cannot display panel
Cannot display panel
Can display panel
Can display panel
Cannot display panel
Can display panel
Cannot display panel
Can display panel
Cannot display panel

我已验证 getCurrentSide()getCurrentImage() 可以按预期工作。 我还验证了 JFrame 是否可见、已启用、可聚焦且有效。

编辑:澄清一下,我希望它只输出“可以显示面板”

编辑:我用计时器替换了线程。切换现在不那么随机了,它现在切换每次迭代。

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖minimal reproducible exampleShort, Self Contained, Correct Example
  • 你应该使用 javax.swing.Timer 而不是你用来刷新的线程循环
  • 根据您的构建层次结构,很多东西可能会发疯——您想始终显示“可以显示面板”吗?还是严格交替?我不能相信 isDisplayable() - 也许你可以使用别的东西
  • 我使用 isDisplayable() 是因为,如果组件不可显示,this.createImage() 将返回 null。所以,我希望它总是说“可以显示面板”
  • 只是一个想法,但您可能刷新得太快,Swing 无法处理。 50hz 相当快,试着放慢速度,看看切换是否继续。

标签: java swing jpanel rendering


【解决方案1】:

我没有使用线程/定时器来调用 repaint() 和 buildTexture(),而是将 buildTexture() 放在了 paintComponent(Graphics) 中,并使用了传递给该方法的图形。这完全解决了我遇到的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-13
    • 2018-09-28
    • 2011-01-12
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多