Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

java - Add other components to JFrame with background

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);

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

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like this?

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

Addendum: See also the opacity property.

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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...