如何在JPanel中添加背景图片?

发布于 2025-01-21 03:40:49 字数 1091 浏览 4 评论 0原文

我完全按照优秀的指南进行操作,但它不起作用,我想单击一个按钮来更改程序的背景。我很乐意更改图片

代码指南 https:/ /stackhowto.com/how-to-set-background-image-in-java-swing/

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Display an image in the background");
        final ImageIcon icon = new ImageIcon("background.png");
        JTextArea text = new JTextArea()
        {
             Image img = icon.getImage();
            // instance initializer
            {setOpaque(false);}
            public void paintComponent(Graphics graphics)
            {
                graphics.drawImage(img, 0, 0, this);
                super.paintComponent(graphics);
            }
        };
        JScrollPane pane = new JScrollPane(text);
        Container content = frame.getContentPane();
        content.add(pane, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(3);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}

I did exactly according to the excellent guide but it does not work, I want to click a button that will change the background of the program. I would love to make the picture change

Code Guide https://stackhowto.com/how-to-set-background-image-in-java-swing/

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Display an image in the background");
        final ImageIcon icon = new ImageIcon("background.png");
        JTextArea text = new JTextArea()
        {
             Image img = icon.getImage();
            // instance initializer
            {setOpaque(false);}
            public void paintComponent(Graphics graphics)
            {
                graphics.drawImage(img, 0, 0, this);
                super.paintComponent(graphics);
            }
        };
        JScrollPane pane = new JScrollPane(text);
        Container content = frame.getContentPane();
        content.add(pane, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(3);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文