Java: Add Background image to frame [duplicate]

二次信任 提交于 2019-11-28 14:50:16
MadProgrammer
  1. Set the layout of your main panel to BorderLayout
  2. Create a JLabel and add it to you main panel
  3. Set the image icon of the label using your background image
  4. Set the layout of the label to what ever you want to use
  5. Continue adding your components to the label as you normally would

An example can be found here

You can simply override paintComponent for your mainPanel and draw the background image in that method. You should choose the appropriate strategy for painting your image (stretch it, keep aspect ratio, repeat horizontally/vertically) but that should not be too hard.

Here is an example that stretches the image over the content pane.

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestBackgroundImage {

    private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame(TestBackgroundImage.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
        JPanel mainPanel = new JPanel(new BorderLayout()) {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
            }

        @Override
        public Dimension getPreferredSize() {
            Dimension size = super.getPreferredSize();
            size.width = Math.max(backgroundImage.getIconWidth(), size.width);
            size.height = Math.max(backgroundImage.getIconHeight(), size.height);
            return size;
        }

        };
        mainPanel.add(new JButton("A button"), BorderLayout.WEST);
        frame.add(mainPanel);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }

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

            @Override
            public void run() {
                try {
                    new TestBackgroundImage().initUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!