如何将图像设置为背景

时间:2014-05-06 13:37:22

标签: java image swing background jpanel

我正在尝试使用内容窗格JPanel创建一个简单的JFrame。我想知道如何将IMAGE设置为背景。我知道有很多人已经问过这个,但每当我尝试时,我都会得到未解决的编译错误。 最后,我在班上创建了一个全新的课程,但也有错误。 我该怎么做呢?请帮忙。

package menu;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.ImageObserver;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import models.AskTheAdmiralFrame;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
/**
 * 
 * @author Russell
 *
 */

public class HistoraskMenu extends JFrame {

private static final long serialVersionUID = 8106152174535131551L;
private static JPanel panel;
private JButton ATA = new JButton("Ask The Admiral");
public Color oldPaper = new Color(255, 230, 179); 
private JLabel label = new JLabel();
private final JLabel label_1 = new JLabel("");
private final ImageIcon bg = new ImageIcon("/Users/Russell/Desktop/Russell/Java/Coding"
            + "/eclipse workspace/Historask/resources/bg.jpg");
Image img = bg.getImage();

public HistoraskMenu(){
    setBounds(50, 50, 700, 500);    
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setTitle("Historask");

    panel = new JPanel();

    setContentPane(panel);

    label.setHorizontalAlignment(SwingConstants.CENTER);    //Sets position of Historask sign
    label.setVerticalAlignment(SwingConstants.TOP);
    label.setBackground(new Color(238, 232, 170));          //Sets the colour of the foreground and background of Historask sign
    label.setForeground(oldPaper);
    label.setIcon(new ImageIcon("/Users/Russell/Desktop/Russell/Java/Coding"
            + "/eclipse workspace/Historask/resources/title.png"));
    label.setOpaque(true);
    label.setBounds(50, 10, 500, 50);
    getContentPane().add(label);

    panel.add(label_1);

    ATA.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {            //What happens when you press ATA button
            new AskTheAdmiralFrame();
        }
    });

    getContentPane().add(ATA);

    setVisible(true);
}

public class panel extends JPanel{
    setLayout(new GridLayout(0, 1, 0, 0));

    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, this);
        super.paintComponents(g);
      }
}

1 个答案:

答案 0 :(得分:0)

如果您在HistoraskMenu()构造函数中引用面板对象,它将不会绘制图像,因为您直接将其初始化为JPanel。而是尝试panel = new panel();