Reputation: 830
I am creating a JFrame
, and when the window is expanded I want the content to stay centered, instead of staying the same distance away from the side. I am using WindowBuilder on Eclipse.
Is there a quick way to do this?
Upvotes: 0
Views: 73
Reputation: 285415
One way, have the container use a GridBagLayout and add the single content to the container without constraints.
For example:
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CenteredContent extends JPanel {
public static final String IMG_PATH = "https://duke.kenai.com/iconSized/duke.gif";
public CenteredContent() throws IOException {
URL imgUrl = new URL(IMG_PATH);
BufferedImage img = ImageIO.read(imgUrl);
Icon imgIcon = new ImageIcon(img);
JLabel label = new JLabel(imgIcon);
setLayout(new GridBagLayout());
add(label);
}
private static void createAndShowGui() {
CenteredContent mainPanel = null;
try {
mainPanel = new CenteredContent();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
JFrame frame = new JFrame("CenteredContent");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Upvotes: 3