简体   繁体   English

如何使用JLabel在JFrame上添加背景图像?

[英]How do I add a background image on a JFrame using a JLabel?

I am trying to display a background image on the JFrame using a JLabel. 我正在尝试使用JLabel在JFrame上显示背景图像。 The code runs and the buttons appear, but the image does not. 代码运行,并且按钮出现,但是图像没有。 I have researched for solutions, yet I have not found one for my code specifically. 我已经研究了解决方案,但是还没有找到专门针对我的代码的解决方案。 Any help would be greatly appreciated. 任何帮助将不胜感激。

/**
 * Adds details to interface and programs buttons
 * 
 * Imani Davis 
 * Final Project
 */

import java.awt.*;
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.border.EmptyBorder;


public class Use_PF_Interface extends JFrame implements Pet_Fish_Interface
{
    // instance variables - replace the example below with your own
    private JFrame window;
    private JPanel panel1, panel2, panel3;
    private JLabel lblBackgroundImage = new JLabel();
    private JButton feedButton = new JButton("Feed Fish");
    private JButton playGamesButton = new JButton("Play Game");

    /**
     * Constructor for objects of class Use_PF_Interface
     */
    public Use_PF_Interface()
    {
        setTitle("Virtual Pet Fish");
        setSize(650, 650);


        //initializes panels and panel layout
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();
        panel1.setLayout(new FlowLayout());
        panel2.setLayout(new FlowLayout());
        panel3.setLayout(new FlowLayout());

        lblBackgroundImage.setLayout(new FlowLayout());

        //sets background image of panel
        lblBackgroundImage.setIcon(new ImageIcon("C:\\Users\\This PC\\Desktop\\OCEAN2.JPEG"));
        panel1.add(lblBackgroundImage);
        validate();

        //adds button to panels
        panel2.add(feedButton);
        panel2.add(playGamesButton);

        //add panels to frame
        add(panel1);
        add(panel2);

    }


}

JFrame uses a BorderLayout by default, a BorderLayout can only manage a single component within any of the five available positions it provides, this means that panel2 is most likely the only component getting shown. JFrame默认使用BorderLayoutBorderLayout只能在其提供的五个可用位置中的任何一个位置管理单个组件,这意味着panel2很可能是唯一显示的组件。

An alternative is to add you components to the JLabel , but remember, JLabel doesn't have a default layout manager. 另一种选择是将组件添加到JLabel ,但是请记住, JLabel没有默认的布局管理器。 Also, remember, JLabel only uses the icon and text properties to calculate its preferred size, so if the contents require more space, they will be clipped. 另外,请记住, JLabel仅使用icontext属性来计算其首选大小,因此,如果内容需要更多空间,则会对其进行裁剪。

Start by having a look at How to Use BorderLayout for more details 首先查看如何使用BorderLayout了解更多详细信息

Also, remember, most Swing components are opaque generally, so you need to set them transparent when you want to do something like this 另外,请记住,大多数Swing组件通常都是不透明的,因此当您要执行此类操作时,需要将它们设置为透明

背景

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Use_PF_Interface extends JFrame {
    // instance variables - replace the example below with your own

    private JPanel panel2;
    private JLabel lblBackgroundImage = new JLabel();
    private JButton feedButton = new JButton("Feed Fish");
    private JButton playGamesButton = new JButton("Play Game");

    /**
     * Constructor for objects of class Use_PF_Interface
     */
    public Use_PF_Interface() {
        setTitle("Virtual Pet Fish");
        setSize(650, 650);

        //initializes panels and panel layout
        panel2 = new JPanel();
        panel2.setOpaque(false);
        panel2.setLayout(new FlowLayout());

        lblBackgroundImage.setLayout(new FlowLayout());

        //sets background image of panel
        lblBackgroundImage.setIcon(new ImageIcon("..."));
        lblBackgroundImage.setLayout(new BorderLayout());

        //adds button to panels
        panel2.add(feedButton);
        panel2.add(playGamesButton);

        lblBackgroundImage.add(panel2);

        add(lblBackgroundImage);

    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new Use_PF_Interface();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Try this, 尝试这个,

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageInFrame {
    public static void main(String[] args) throws IOException {
        String path = "Image1.jpg";
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        JLabel label = new JLabel(new ImageIcon(image));
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(label);
        f.pack();
        f.setLocation(200,200);
        f.setVisible(true);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM