我的 jPanel 有一个问题。
我有一个按钮,它从字符串输入(数学公式)中输入 PNG 图像,然后它将在 jPanel 中重新绘制旧图像。问题就来了。图像已更改,但 jPanel 不会重新绘制,直到我手动调整应用程序窗口的大小。
看起来面板在调整大小之前不会重新绘制。但我不知道如何在该按钮中执行此操作。
I tried this https://stackoverflow.com/questions/6617077/jpanel-not-refreshing-upon-selection-with-jcombobox and this https://stackoverflow.com/questions/6912283/refreshing-picture-in-drawingpanel-extends-jpanel但没有变化。
顺便提一句。我在 netbeans 中使用 GUI 生成器。
我的代码...第一次尝试:
public class ImagePanel extends JPanel {
private String path;
Image img;
public ImagePanel() {
try {
//save path
path = "Example5.png";
//load image
img = ImageIO.read(new File(path));
} catch (IOException ex) {
}
}
@Override
public void paint(Graphics g) {
//draw the image
if (show) {
try {
if (img != null) {
img = ImageIO.read(new File(path));
g.drawImage(img, 0, 0, this);
}
} catch (IOException ex) {
}
} else {
show = true;
}
}
}
并在窗口类/按钮方法中:
imagePanel = new ImagePanel();
imagePanel.repaint();
imagePanel.updateUI();
第二次尝试:
public class ImagePanel extends JPanel {
private String path;
Image img;
ImagePanel(Image img) {
this.img = img;
}
public void setImg(Image img) {
this.img = img;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw image centered in the middle of the panel
g.drawImage(img, 0, 0, this);
}
}
和按钮:
imagePanel.setImg(new ImageIcon("2.png").getImage());
imagePanel.repaint();