我正在创建JFrame
,当窗口展开时,我希望内容保持居中,而不是与侧面保持相同的距离。我在Eclipse上使用WindowBuilder。
有快速的方法吗?
答案 0 :(得分:3)
一种方法是让容器使用GridBagLayout并将单个内容添加到容器中而不受约束。
例如:
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();
}
});
}
}