Reputation: 1689
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...
Upvotes: 0
Views: 11418
Reputation: 449
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);
}
https://i.sstatic.net/JxfbF.png
Upvotes: 0
Reputation: 38885
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 );
}
}
Upvotes: 2
Reputation: 55
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.
Upvotes: 1