Reputation: 3
I have the following code to create my GUI.
private static void createGUI() {
JFrame frame = new JFrame ("Tiles Game");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar (new JMenuBar());
frame.setContentPane (MainPanel.getInstance());
frame.pack();
frame.setResizable (false);
frame.setLocationRelativeTo (null);
frame.setVisible (true);
}
This is the MainPanel (extends JPanel) constructor:
private MainPanel() {
super (new BorderLayout());
setPreferredSize (new Dimension (IMG_SIZE + 10, IMG_SIZE + 10));
...
panel = new ImagePanel();
add (panel, BorderLayout.CENTER);
}
And this is the ImagePanel (extends JPanel) constructor:
private ImagePanel() {
super();
setPreferredSize (new Dimension (IMG_SIZE, IMG_SIZE));
...
}
However the ImagePanel is aligned to the top left corner of the MainPanel rather than centered, so I get a bunch of extra padding at the bottom and right sides, and none at the top and left sides. How do I place it at the center of the MainPanel?
Upvotes: 0
Views: 1283
Reputation: 209004
Probably what's happening is that you are drawing your image from (0, 0)
which are the top-left corner. Then you set the preferred size to 10 pixels larger which makes the panel larger, but the image is still at (0, 0)
Instead use the same size witoout adding 10, and just use an EmptyBorder
for the panel. Also as a recommendation, override getPreferredSize()
instead of using setPreferredSize()
public class ImagePanel extends JPanel {
public ImagePanel() {
setBorder(new EmptyBorder(10, 10, 10, 10));
}
@Override
public Dimension getPreferredSize() {
return new Dimension(IMG_SIZE, IMG_SIZE);
}
}
Also you may want to consider using a GridBagLayout
for the container panel, for a sure center, if the container is to be larger than the the child panel. Few things you could do. Even consider using a ImageIcon
and JLabel
instead of painting (if the image doesn't need to be resized (as Camickr(+1) pointed out). A JLabel
could easily be made a background by just setting the layout of the label and set it as the content pane of the frame.
ImageIcon icon = new ImageIcon(...)
JLabel frameBackground = new JLabel(icon);
frameBackground.setLayout(new BorderLayout());
frame.setContentPane(frameBackground);
Upvotes: 2
Reputation: 324128
Don't use a JPanel to display an image.
Instead use a JLabel
with an ImageIcon
.
If you want extra space around the image then you use an EmptyBorder
on the label.
Upvotes: 2