大家好!我正在尝试解决一个 - 显然 - 简单的问题,但我无法解决它。我正在开发一个带有 Java/Swing 库的示例应用程序;我有一个 JFrame 和一个 JPanel。我只想实现以下目标:
JPanel必须在 JFrame 内居中。
JPanel必须始终具有使用
setPreferredSize() 方法指定的大小。不得在此大小下调整其大小。
我尝试使用 GridBagLayout:这是我能做到的唯一方法。
请参阅下面的示例:
/* file StackSample01.java */
import java.awt.*;
import javax.swing.*;
public class StackSample01 {
public static void main(String [] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.RED);
frame.setLayout(new GridBagLayout());
frame.add(panel, new GridBagConstraints());
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
这是一个屏幕截图:
我不会使用 GridBagLayout 来做太简单的事情。我尝试了一个最简单的解决方案,使用 Box,但这不起作用:
示例代码:
/* file StackSample02.java */
import java.awt.*;
import javax.swing.*;
public class StackSample02 {
public static void main(String [] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.RED); // for debug
panel.setAlignmentX(JComponent.CENTER_ALIGNMENT); // have no effect
Box box = new Box(BoxLayout.Y_AXIS);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue()); // causes a deformation
frame.add(box);
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
这里是截图,
有任何想法吗?谢谢大家 :-)