Avoid using JLabel
to add background on screen as it is a common component and will not allow you to overlay other components on yourself.
The most recommended way to do this is to create a component of the type Container
as JPanel
, or that it is a container top level, and overwrite the method paintComponent
. In addition to filling the background, it will allow you to add numerous other components and position them as you wish:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TesteBG extends JFrame {
public TesteBG() {
JLabel titulo1 = new JLabel("Testes de local1");
JLabel titulo2 = new JLabel("Testes de local2");
//
BackgroundPanel bgPanel = new BackgroundPanel();
//
bgPanel.setLayout(new BorderLayout());
bgPanel.add(titulo1, BorderLayout.NORTH);
bgPanel.add(titulo2, BorderLayout.SOUTH);
setContentPane(bgPanel);
setSize(400, 400);
setTitle("Teste");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class BackgroundPanel extends JPanel {
Image imagem;
public BackgroundPanel() {
try {
imagem = ImageIO.read(getClass().getResource("/fotos/1.png"));
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Não foi possivel ler a imagem !");
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imagem, 0, 0, this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new TesteBG();
});
}
}
Note that it is also recommended to configure this panel as rootPane of the screen through the method setContentPane()
. From there, everything you add on the screen should be added to the panel and not directly on the screen, so as not to be parts without background.
There is a more complex but more effective way to apply background image to a screen, without getting stuck to the size of the screen or image, if you want to know how, it is well explained in this answer.
What do you mean? You can edit and explain the problem better?
– user28595
Sorry, it’s not Jbutton, it’s the two Jlabels I want to manipulate
– Guilherme Passos
Look at this answer, it answers you: https://answall.com/a/205296/28595 if you don’t understand something, let me know and I’ll explain it to you.
– user28595
I realized that I find my solution there, but I can’t understand the code. Java is still very new to me, I appreciate if I can help!
– Guilherme Passos
the background is to be applied to jframe ne? Without worrying about resizing or anything? This is simpler: https://answall.com/a/158841/28595
– user28595
Exactly that
– Guilherme Passos
Still, I can do the command, you can take my code and format it to work?
– Guilherme Passos