You can add a background directly to JPanel
, instead of using a JLabel
to do so because all the swing components inherit from JComponent
and can therefore be containers of other components, Jbuttons, Jlabels, Jtextfields and some others do not have any implementation of a LayoutManager
, which makes components such as JPanel
more appropriate for this purpose, as they already have layout implementation.
The class below has been adapted of this link(in Portuguese and very well explained), you have to pass the reference of the image, that the JPanel
adapts to her size:
class myCustomPanel extends JPanel {
private Image background;
public myCustomPanel(URL path) {
this.background = new ImageIcon(path).getImage();
setOpaque(false);
setPreferredSize(new Dimension(getWidth(), getHeight()));
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(background, 0, 0, this);
super.paintComponent(g);
}
@Override
public int getWidth() {
return background.getWidth(this);
}
@Override
public int getHeight() {
return background.getHeight(this);
}
}
Functional example of the above class, with a JButton
added:
package example;
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class BackgroundPanel extends JFrame {
public BackgroundPanel() throws MalformedURLException {
//se a imagem estiver no projeto, basta referenciar ela
// pela localização do pacote
//ex: URL path = getClass().getResource("caminho/da/suaImage.jpg");
URL path = new URL("http://www.itinterns.org/wp-content/uploads/2015/09/Java_620X0.jpg");
JPanel p = new myCustomPanel(path);
p.add(new JButton("botao"));
this.add(p);
this.pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class myCustomPanel extends JPanel {
private Image background;
public myCustomPanel(URL path) {
this.background = new ImageIcon(path).getImage();
setOpaque(false);
setPreferredSize(new Dimension(getWidth(), getHeight()));
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(background, 0, 0, this);
super.paintComponent(g);
}
@Override
public int getWidth() {
return background.getWidth(this);
}
@Override
public int getHeight() {
return background.getHeight(this);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
BackgroundPanel b = new BackgroundPanel();
b.setLocationRelativeTo(null);
b.setVisible(true);
} catch (MalformedURLException ex) {
}
}
});
}
}
Resulting:
Never use the
jLabel
to put pictures but indications with where to put email, password, etc. The main function is this. ThejPanel
has properties for it.– Max Tag