我有JPanel
帶有邊框,問題是當我在JFrame
上添加面板時,需要面板大小,但我使用setPreferredSize
來設置面板的首選大小。該框架的佈局是'BoxLayout',這裏是代碼:在JFrame上顯式設置jpanel的大小
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)將使它適當調整自身的大小,爲其子的首選大小提供恰當的大小。 –