I have a JFrame with a panel on it with Overlay Layout because I want to set a JLabel with an image as the background and put stuff over top of it. I set the size of the frame equal to the size of the image and when I put only that on it fits perfectly, but if I add anything over top of it it shifts the image to the right by the width of the component that I add and cuts it off to the right. It does this even though the component isn't in the region that is shifted over. The component is to the right and its properly displayed over the label but the image is still shifted over.
import java.awt.*;
import java.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.imageio.*;
import java.awt.image.*;
public class MainScreen extends JFrame{
JButton button;
JPanel backgroundPanel, p, panel;
public MainScreen(ArrayList<Character> c){
JLabel label = new JLabel(new ImageIcon("house.jpg"));
button = new JButton("Button");
backgroundPanel = new JPanel();
p = new JPanel();
panel = new JPanel();
p.add(button);
panel.add(p);
panel.setOpaque(false);
p.setOpaque(false);
LayoutManager overlay = new OverlayLayout(backgroundPanel);
backgroundPanel.setLayout(overlay);
backgroundPanel.add(panel);
backgroundPanel.add(label);
add(backgroundPanel);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setSize(1200, 700);
setVisible(true);
}
public static void main(String[] args){
MainScreen ms = new MainScreen(new ArrayList<Character>());
}
}
You need to play with the alignmentX/Y properties of the two components to get your desired layout.
Start by setting them all to 0.5f.
Here is a little demo program that allows you to change the properties to see the effect:
Another option is to just set the layout of the JLabel to whatever you want (BorderLayout, GridBagLayout, FlowLayout). Then you can add components directly to the label, like you would for any panel. Any component you add must be fully contained within the label. This will give you more flexibility than using the OverlayLayout.