使用background将其他组件添加到JFrame [英] Add other components to JFrame with background

查看:152
本文介绍了使用background将其他组件添加到JFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的JFrame中添加背景图片,但是当我使用下面的代码执行此操作时,我无法添加其他元素,如JLabel或JTextField。

I want to add a background image to my JFrame but when I do it using the code below, I'm unable to add other elements like JLabel or JTextField.

ImageIcon icon = new ImageIcon("src/images/back.jpg");
backImage = icon.getImage();
BackgroundImagePanel contentPane = new BackgroundImagePanel();
contentPane.setBackgroundImage(backImage);
this.setContentPane(contentPane);

如果还有其他方式,请告诉我。将JTabbedPane添加到具有背景的JFrame中?

Can you tell me please if there is another way to add JTabbedPane to a JFrame with a background ?

谢谢。

推荐答案

喜欢这个?

附录:通常你会首先调用 super.paintComponent(g),但是由于图像将覆盖整个背景,因此无需执行此操作。 - camickr

Addendum: "Normally you would invoke super.paintComponent(g) first, but since the image will cover the entire background there is no need to do this."—camickr

附录:另见不透明度属性

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Imager {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new ImagePanel("image.jpg"));
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    private static class ImagePanel extends JPanel {

        BufferedImage img;

        ImagePanel(String name) {
            this.setToolTipText(name);
            this.add(new JLabel(name));
            try {
                img = ImageIO.read(new File(name));
                this.setPreferredSize(new Dimension(
                    img.getWidth(), img.getHeight()));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void paintComponent(Graphics g) {
            // super.paintComponent(g);
            g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
        }
    }
}

这篇关于使用background将其他组件添加到JFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆