java - 如何在 JPanel 中刷新/重新加载图像

标签 java swing jpanel background-image repaint

当数据提交到数据库时,我需要重新加载 JPanel 的背景图像。 我创建 JPanel 来填充数据库中的图像。当我更新图像并提交时,背景会自动更改。 我也尝试使用 repaint() 和 revalidate() 但它不起作用。 它必须重新启动应用程序并再次运行,它才能工作。

这是我在 JPanel 中显示背景的代码。

public void getLogo(Company company, PanelCompany view) {
        JPanel panel = new BackgroundImage(company.getLogoBlob());
        panel.revalidate();
        panel.setVisible(true);
        panel.setBounds(10, 10, 120, 120);
        view.getPanelPhoto().add(panel);
}

这是我的助手类:

public class BackgroundImage extends JPanel{
    private Image image;

    public BackgroundImage (InputStream input) {
        try {
            image = ImageIO.read(input);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics grphcs) {
        super.paintComponent(grphcs);
        Graphics2D gd = (Graphics2D) grphcs.create();
        gd.drawImage(image, 0, 0, getWidth(), getHeight(), this);
        gd.dispose();
    }
}

有什么解决办法吗?感谢您之前的关注:)

最佳答案

首先,您的辅助类应该设置它自己的大小。

其次,您应该只使用 JPanelGraphics 实例。

public class BackgroundImage extends JPanel{
    private Image image;

    public BackgroundImage (InputStream input) {
        try {
            image = ImageIO.read(input);
            setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics grphcs) {
        super.paintComponent(grphcs);
        Graphics2D g2d = (Graphics2D) grphcs;
        g2d.drawImage(image, 0, 0, getWidth(), getHeight(), this);
    }
}

现在您的调用将如下所示。

public void getLogo(Company company, PanelCompany view) {
        JPanel panel = new BackgroundImage(company.getLogoBlob());
        view.getPanelPhoto().add(panel);
}

您的 PanelCompany必须使用布局管理器。这是Oracle's Visual Guide to Layout Managers .

选择一个。

关于java - 如何在 JPanel 中刷新/重新加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15377842/

相关文章:

java - JPanel ActionMethod 显示时

java - 如何在后台运行 selenium webdriver?

java - 应用 list 中的属性缺少 Android 命名空间前缀

java - GridBagLayout 中 JScrollView 中的组件绘制得太小

java - 如何在 JTable Cell 中显示多行

Java:如何控制JPanel的纵横比?

java - 为什么在构造的 JPanel 中表达了组件的某些属性,而没有表达其他属性?

java - 在 Java 中使用 ScheduledExecutorService 定期运行任务

java - 从 servlet 调用异步方法

java - 如何翻转绘制矩形以使其绘制出来?