Java JFrame扩展不更新,除非重新调整大小

时间:2015-11-05 02:00:45

标签: java swing jframe

我有一个类,Game,它扩展了JFrame,我使用它的paint方法来完成我的所有绘图。每当我添加要绘制的新东西(Piece)时,需要调整窗口大小以获得要添加的内容。这是为什么?我试图在绘图后调用setVisisble(true),但是没有修复它。

其次,当我使用drawBottomText(g)绘制字符串时,它显示效果很好,但是如果我更改正在绘制的字符串,则仍会显示旧字符串。调整窗口大小,使其覆盖“旧”窗口。字符串擦除它。

我希望paint()像绘制循环一样工作,其中擦除了最后一帧中的旧图像,并且只显示了此次迭代所显示的内容。显然,这种心态并不准确。

public class Game extends JFrame implements  MouseListener 
{
...
   public void paint (Graphics g){
       drawBottomText(g);

       board.drawBoard(g);

    }

    private void drawBottomText(Graphics g){
        Graphics2D g2 = (Graphics2D)g;

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        Font font = new Font("Serif", Font.PLAIN, 20);
        g2.setFont(font);

        g2.drawString(bottomString, 40, FRAME_HEIGHT - 20); 
    }
 ...
}

     public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;
      BasicStroke stroke = new BasicStroke(10);
      g2.setStroke(stroke);

      if (isAnX){
          drawX(g2);
      }
      else {
          drawO(g2);
      }
   }

这是由board.drawBoard(g)

调用的绘制代码
public class Piece extends JComponent{
...
   private void drawO(Graphics2D g2){
       g2.setColor(Color.blue);
       Ellipse2D.Double ellipse = new Ellipse2D.Double(xPos  - IMG_WIDTH/2 * shrinkBy, yPos - IMG_HEIGHT/2 * shrinkBy, IMG_WIDTH * shrinkBy, IMG_HEIGHT * shrinkBy);
       g2.draw(ellipse);
   }

   private void drawX(Graphics2D g2){
       g2.setColor(Color.red);
       Point2D.Double topRight = new Point2D.Double(xPos + IMG_WIDTH/2 * shrinkBy, yPos - IMG_HEIGHT/2 * shrinkBy);
       Point2D.Double bottomLeft = new Point2D.Double(xPos - IMG_WIDTH/2 * shrinkBy, yPos + IMG_HEIGHT/2 * shrinkBy);
       Point2D.Double bottomRight = new Point2D.Double(xPos + IMG_WIDTH/2 * shrinkBy, yPos + IMG_HEIGHT/2 * shrinkBy);
       Point2D.Double topLeft = new Point2D.Double(xPos - IMG_WIDTH/2 * shrinkBy, yPos - IMG_HEIGHT/2 * shrinkBy);

       Line2D.Double botRightToTopLeft = new Line2D.Double(topRight, bottomLeft);
       Line2D.Double botLeftToTopRight = new Line2D.Double(topLeft, bottomRight);
       g2.draw(botRightToTopLeft);
       g2.draw(botLeftToTopRight);

   }
...
}

使用这种绘制方法(扩展JFrame并使用paint()),为什么需要调整窗口的大小以便渲染新的绘图以及为什么旧的字符串会被粘住?

1 个答案:

答案 0 :(得分:0)

正如@Andrew Thompson和@MadProgrammer在评论中所说,最好在JPanel上进行自定义绘画,然后将JPanel添加到你的JFrame中。在paintComponent()方法中绘制图形,并在更改绘制内容时调用JPanel类中的repaint()。遵循这种定制绘画方法可以解决问题中陈述的问题。