Java 猜词游戏 repaint() 方法无法正常工作

5

我一直在制作一个猜单词游戏,以便自学Java。我已经将其放置在主体框架中。

this.add(new PaintSurface(), BorderLayout.CENTER);

我有:

private class PaintSurface extends JComponent {
    Shape found = null;

    public PaintSurface(){
        JOptionPane.showMessageDialog(null, "Repainting");
        Shape s;
        msgbox("LL: " + intLivesLost);
        switch(intLivesLost){
        //draw the Hanged man
        case 10:
            //Face + KILL
        case 9:
            //2nd Arm
        case 8:
            //1st Arm
        case 7:
            //2nd Leg
        case 6:
            //1st Leg
        case 5:
            //Body
        case 4:
            //Head
            shapes.add(s);
        case 3:
            //Horizontal Bar
            s = new Line2D.Float(100, 450, 250, 450);
            shapes.add(s);
            //Rope
            s = new Line2D.Float(250, 450, 250, 500);
            shapes.add(s);
        case 2:
            //Vertical Bar
            s = new Line2D.Float(100, 450, 100, 670);
            shapes.add(s);
        case 1:
            //Stand
            s = new Line2D.Float(40, 670, 460, 670);
            shapes.add(s);
            break;
        default:
            break;          
        }
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setStroke(new BasicStroke(4));
        g2.setColor(Color.BLACK);

        for (Shape count : shapes){
            g2.draw(count);
        }
    }
}

我正在使用:

repaint();

在整个项目中,每次帧更新、新字母猜测、错误猜测或新游戏时,都需要更新框架。
当应用程序首次运行时,会弹出JOptionPane.showMessageDialog(null,“重绘”)窗口,因此我知道它已被调用。随后,“重绘”弹出窗口不再出现,因此我知道repaint()调用没有起作用。我知道代码到达了repaint()调用,因为我在其之前和之后放置了JOptionPane.showMessageDialog。
我尝试过以下方法,但没有成功:
- removeAll(); - revalidate(); - getContentPane()。repaint();
非常感谢您提供的任何提示和建议。
编辑:如您所建议,我尝试将代码放入“paint”中,认为这是以前的方式,但仍然无法工作。谢谢。

"public PaintSurface() {...}" 是PaintSurface类的构造函数。当使用 "new PaintSurface()" 创建PaintSurface时,它才会被调用。你创建shapes对象的逻辑应该放在其他地方(可能是paint方法,但我不确定,因此这不是一个答案;)" - user6073886
2个回答

1
  1. 不要覆盖paint方法,根据你的需求覆盖paintComponent或update方法。
  2. 看起来你对paint、repaint和update方法有些困惑。如果你在做游戏,请阅读这篇文章:https://www.guiguan.net/repaint-paint-and-update/。repaint()会导致整个组件的重绘,因此可能会出现性能问题。

0

我已经解决了,将绘图放在单独的面板上,现在一切都正常工作。 感谢您的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接