java - 重新绘制 JPanel 的一部分

标签 java swing jpanel repaint paintcomponent

我需要在 x-y 轴坐标系中绘制 google 和 yahoo 访问时间。现在我已经画出了x-y轴坐标系。

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);
    }
}

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

最佳答案

将 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);
   }

编辑:注意有关getPreferredSize()的代码和注释

关于java - 重新绘制 JPanel 的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15706886/

相关文章:

java - Apache POI 锁定单元格但允许调整列大小

java - 通配符和类型变量有什么区别?

java - 动态创建的 JTabbedPane

java - 调整大小时,2D 对象被 JFrame 边缘遮挡

java - GridLayout + 鼠标监听器

java - 将 JPanel 添加到 Javafx

java - JFrame 文本组件未正确显示

Java 库验证 URL 并从字符串中删除 URL 参数

java - 在 Java Swing 中,当工作流程非线性时如何在 JPanel 之间切换?

java - 如何知道资源是否在 jsr-196 auth 模块中受到保护?