gpt4 book ai didi

java - 重新绘制 JPanel 的一部分

转载 作者:行者123 更新时间:2023-12-01 08:13:13 25 4
gpt4 key购买 nike

我需要在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com