【发布时间】:2013-01-17 09:51:36
【问题描述】:
我有带边框的JPanel,问题是当我在JFrame 上添加面板时,尽管我使用setPreferredSize 设置了面板的首选尺寸,但它采用了面板尺寸。框架的布局是“BoxLayout”,代码如下:
public class ActionForm extends JFrame {
JPanel namePanel;
JPanel descPanel;
JLabel actionName;
JLabel nameLabel;
JTextField nameTextField, descTextField;
FlowLayout toolBarLayout = new FlowLayout();
public ActionForm() {
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
TitledBorder nameBorder= BorderFactory.createTitledBorder(
"Change Description");
nameBorder.setTitleJustification(TitledBorder.LEFT);
namePanel = new JPanel(toolBarLayout);
namePanel.setPreferredSize(new Dimension(150, 150));
nameLabel = new JLabel("ButtonName");
nameTextField = new JTextField("Action's Name", 50);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
namePanel.setBorder(nameBorder);
namePanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
this.add(namePanel);
}
public static void main(String[] args) {
ActionForm form = new ActionForm();
form.setVisible(true);
form.setSize(970, 500);
form.setResizable(false);
}
}
为什么面板的大小没有变化?
【问题讨论】:
-
你在问为什么 setPreferredSize() 似乎没有做任何事情?如果是这样,那是因为它的子项的首选大小是对 JFrame 的建议,但是您已经明确地给了它一个大小,所以它忽略了这个建议。调用 frame.pack() 而不是 frame.setSize(w, h) 将导致它适当地调整自己的大小,为其孩子的首选大小提供正确的大小。
标签: java swing jpanel layout-manager preferredsize