如何在此特定代码中添加背景图像? :) JAVA

时间:2016-02-22 11:42:19

标签: java

HI THERE :)我试图弄清楚要使用哪些正确的代码,以便我可以为此添加背景图像:)这是代码,它的作用是它只显示JLABEL和JBUTTON,什么我需要的是放一个背景图片:O 但每当我尝试它时,它要么覆盖整个事物,要么它不显示:(

    import javax.swing.*;
import java.awt.*;
 import java.awt.event.*;

public class MainFrame 
{
JFrame mainFrame = new JFrame("Main Frame");
JPanel mainPanel = new JPanel();
JLabel label1 = new JLabel("A SECOND OF LIFE");
JButton button1 = new JButton("START");
JButton button2 = new JButton("EXIT");
Font font = new Font ("Impact", Font.PLAIN, 40);
JLabel label2 = new JLabel("Do you have what it takes? ");
//JLabel background = new JLabel(new ImageIcon("C:\\Users\\Master Boat\\Desktop\\PH\\horror bg jisha.png"));
//FlowLayout poli = new FlowLayout();


public MainFrame()
{   


    label1.setAlignmentX(Component.CENTER_ALIGNMENT);
    label2.setAlignmentX(Component.CENTER_ALIGNMENT);
    button1.setAlignmentX(Component.CENTER_ALIGNMENT);
    button2.setAlignmentX(Component.CENTER_ALIGNMENT);
    button1.setFont(font);
    button2.setFont(font);
    label1.setFont(font);
    //mainFrame.add(background);
    //background.setLayout(poli);




    button2.addActionListener(new btnFunc());
    button1.addActionListener(new btnFunc2());
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.add(label1);
    mainPanel.add(label2);
    mainPanel.add(button1);
    mainPanel.add(button2);
    mainFrame.setSize(500, 500);
    mainFrame.setLocation(500, 100);
    mainFrame.add(mainPanel);
    mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    mainFrame.setVisible(true);


}

public static void main(String[] args)
{
    SwingUtilities.invokeLater(MainFrame::new);
}
public class btnFunc implements ActionListener {

    public void actionPerformed (ActionEvent e) {

        JOptionPane.showMessageDialog(null,"YOU ARE A COWARD !", " WAAAAA!",JOptionPane.INFORMATION_MESSAGE);
        System.exit(1);
    }   


}
public class btnFunc2 implements ActionListener {

    public void actionPerformed (ActionEvent e) {

        new gamesamplingbeta();
    }
}

}

2 个答案:

答案 0 :(得分:0)

您可以在标签上添加图像:

ImageIcon background;
background = new ImageIcon("/image/image.png");

label= new JLabel() {
  public void paintComponent(Graphics g) {
    g.drawImage(icon.getImage(), 0, 0, null);
    super.paintComponent(g);
  }
};

答案 1 :(得分:0)

检查此链接...使用setsize()函数调整图像大小 http://www.java2s.com/Code/Java/Swing-JFC/Panelwithbackgroundimage.html