简体   繁体   中英

How to set an image as background in Java application in eclipse or windows builder pro

I was wondering how to set an image as the background to an application in Java. I know in android it is very straight forward, and windows builder pro has a lot of amazing tools for building the Java gui so was wondering whether there was a way I could do this? Thanks in advance! MY application looks pretty bad as grey...

You can't set the background to an image exactly. What you have to do is draw the image on the graphics during painting. So you'll need to subclass JPanel and override the paintComponent() method, and draw the image there.

 public class ImagePanel extends JPanel {
     private Image bgImage;

     public Image getBackgroundImage() {
        return this.bgImage;
     }

     public void setBackgroundImage(Image image) {
        this.bgImage = image;
     }

     protected paintComponent(Graphics g) {
         super.paintComponent(g);
         g.drawImage( bgImage, 0, 0, bgImage.getWidth(null), bgImage.getHeight(null), null );
     }
 }

You can set your component's color by calling:

.setBackground(myColor);

Some components such as JLabels require you to call this upon it for the color change to take effect:

.setOpaque(true);

Hope this helped.

Technically you could add a label on the whole screen and then in the icon option chane to specific background:

JLabel lblNewLabel = new JLabel("n");
lblNewLabel.setIcon(new ImageIcon("gene.jpg"));
lblNewLabel.setBounds(0, 0, 434, 261);
frame.getContentPane().add(lblNewLabel);

For example, in the Source

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnNewButton = new JButton("Let's start!");
    btnNewButton.setFont(new Font("David", Font.ITALIC, 12));
    btnNewButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e) 
        {
            JOptionPane.showMessageDialog(null, "Now we will have to add some code here right =]?");
        }
    }
                                                        );
    btnNewButton.setBounds(158, 120, 89, 23);
    frame.getContentPane().add(btnNewButton);


    JLabel lblNewLabel = new JLabel("n");
    lblNewLabel.setIcon(new ImageIcon("gene.jpg"));
    lblNewLabel.setBounds(0, 0, 434, 261);
    frame.getContentPane().add(lblNewLabel);
}

http://imgur.com/rSTXZLP.jpg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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