重绘JPanel的一部分

use*_*190 0 java swing jpanel repaint paintcomponent

我需要在xy轴坐标系中绘制谷歌和雅虎访问时间.现在我绘制了xy轴坐标系.

public void paintComponent(Graphics gl) {
    Graphics2D g = (Graphics2D) gl;
    g.setColor(new Color(222, 222, 222));
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
    g.setColor(new Color(0, 0, 0));
    int x=15;
    int y=15;
    g.drawString("20", 0, 10);
    for(int i=1;i<=20;i++) {
        g.drawLine(x, y+(35*(i-1)), x, y+(35*i));
        g.drawString(""+(20-i), 0, y+(35*i));
    }
    for(int i=1;i<=10;i++) {
        g.drawLine(x+(70*(i-1)),715, x+(70*i), 715);
        g.drawString(""+i,  x+(70*i),730);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我需要动态重新绘制这个XY坐标系上的访问时间值.但我知道何时调用repaint().它将再次重新绘制()XY坐标.如何在不重新绘制XY坐标的情况下重新绘制访问时间值?

Hov*_*els 5

将GUI显示的稳定背景部分放入BufferedImage,然后在paintComponent(...)方法中绘制它.

例如,

// Warning: code has not been run nor compiled and may contain errors.
public class MyGui extends JPanel {
   public static final int BI_WIDTH = //..... ? the width of the image
   public static final int BI_HEIGHT = // .....? the height of the image
   private BufferedImage bImg;

   public MyGui() {
     bImg = makeImage();
     // ... other code
   }

   public BufferedImage makeImage() {
     BufferedImage bImg = new BufferedImage(BI_WIDTH, BI_HEIGHT, 
         BufferedImage.TYPE_INT_ARGB);
     Graphics2D g2 = bImg.createGraphics();

     // ... do your background drawing here, the display that doesn't change

     g2.dispose();
     return bImg;
   }

   public void paintComponent(Graphics g) {
     super.paintComponent(g);
     if (bImg != null) {
       g.drawImage(bImg, 0, 0, this);
     }
     // ...  draw the changing parts of your display
   }

   // note, if your image is going to fill up your JPanel, then it's
   // also a good idea to override the getPreferredSize() method to make sure 
   // that the JPanel's size is correct and matches that of the image:
   @Override
   public Dimension getPreferredSize() {
     return new Dimension(BI_WIDTH, BI_HEIGHT);
   }
Run Code Online (Sandbox Code Playgroud)

编辑:注意代码和评论getPreferredSize()