Reputation: 5429
I know there's something really simple here that I'm doing wrong but I just can't see it. I've tried searching online and checking other answers but I can't find someone having the same issue.
I'm trying to create a JFrame with a panel of buttons in NORTH and a panel of buttons in SOUTH and let the user load an image to go in CENTER. When the user resizes the JFrame I'd like the image in the center to stay centered horizontally and vertically but the image is only staying centered horizontally. I'm using a JLabel to hold the image. Can you please help point me in the right direction?
theJFrame.setResizable(true);
imageLabel.setIcon(new ImageIcon(theImage));
imagePanel.add(imageLabel);
theJFrame.add(imagePanel, BorderLayout.CENTER);
theJFrame.pack();
EDIT: The user Hovercraft Full of Eels posted a solution that worked which has since been deleted so I can't choose it, but they suggested setting imageLabel to have a GridBagLayout. I made that change and now it stays centered vertically and horizontally.
EDIT: I'm having a hard time paring down my code enough for a SSCCE because I have another class that creates and calls the GUI class to run it, but I can give you a more detailed code example:
theJFrame = new JFrame();
theFilterButtonPanel = new JPanel();
theUtilityButtonPanel = new JPanel();
imageLabel = new JLabel();
theJFrame.setResizable(true);
theJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and add filter buttons
for (final Filter f : MY_FILTERS) {
createFilterButton(f.getDescription());
}
theJFrame.add(theFilterButtonPanel, BorderLayout.NORTH);
myUtilityButtonPanel.add(createCloseButton());
theJFrame.add(theUtilityButtonPanel, BorderLayout.SOUTH);
theJFrame.add(imageLabel, BorderLayout.CENTER);
When I do it like this, just adding the imageLabel straight into the JFrame, it puts it on the far left of the window and, if I resize it, it stays vertically centered. If instead I use
JPanel theImagePanel = new JPanel();
theImagePanel.add(imageLabel);
theJFrame.add(theImagePanel, BorderLayout.CENTER);
then it centers it horizontally but it stays at the top of the screen when the window is resized (does not center it vertically).
Upvotes: 0
Views: 1452
Reputation: 324197
Add the JLabel directly to the frame. There is no need to add the image to a panel first.
The default alignment for an image only JLabel is to be centered vertically and horizontally in the space available.
Upvotes: 1