jle*_*lee 2 java swing layout-manager gridbaglayout
好吧,就像标题所说的那样,这应该是一个简单的问题,但我很擅长做gui而且我有一点问题.
我正试图将我的窗口分成3个有边框的部分(水平).到目前为止,我有两个,但是,中间的那个延伸到窗口的底部,阻挡了底部.我猜这与我使用NORTH,CENTER和SOUTH有关?我附上了窗口的图片和我的一些代码,如果您需要更多,请告诉我!
顶部
public NamePanel(){
Dimension size = getPreferredSize();
size.height = 125;
setPreferredSize(size);
//setBorder(BorderFactory.createTitledBorder("Who owes who money?"));
setBorder(BorderFactory.createTitledBorder("Who?"));
JRadioButton button;
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
button = new JRadioButton("Bob");
gc.anchor = GridBagConstraints.CENTER;
gc.weightx = 0.5;
gc.weighty = 0.0;
gc.gridx = 1;
gc.gridy = 0;
add(button, gc);
button = new JRadioButton("Sue");
gc.weighty = 0.5;
gc.gridx = 3;
gc.gridy = 0;
add(button, gc);
Run Code Online (Sandbox Code Playgroud)
中段
public ActionsPanel(){
Dimension size = getPreferredSize();
size.height = 75;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("What would you like to do?"));
JRadioButton button;
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
button = new JRadioButton("Add");
gc.anchor = GridBagConstraints.NORTH;
gc.weightx = 0.5;
gc.weighty = 0.0;
gc.gridx = 1;
gc.gridy = 0;
add(button, gc);
Run Code Online (Sandbox Code Playgroud)
底部(隐藏在图片中)
public EntryPanel(){
Dimension size = getPreferredSize();
size.height = 75;
setPreferredSize(size);
setBorder(BorderFactory.createTitledBorder("Enter the transaction"));
JLabel why = new JLabel("Why?: ");
JTextField transName = new JTextField(10);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.anchor = GridBagConstraints.SOUTH;
add(transName, gc);
Run Code Online (Sandbox Code Playgroud)
这几乎是BorderLayout有效的.BorderLayout有五个位置可以显示组件,但只有一个组件可以占据每个位置.有关更多详细信息,请查看如何使用BorderLayout
根据你的需要,你可以使用GridBagLayout,像...
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
add(namePanel, gbc);
add(actionsPanel, gbc);
add(entryPanel, gbc);
Run Code Online (Sandbox Code Playgroud)
这将在容器内垂直布置三个组件,但只尊重那里的首选高度,因此不会扩展以垂直填充整个容器
查看在容器中布置组件以及如何使用GridBagLayout获取更多详细信息
不要忘记,您可以使用多个布局(通过使用多个容器)来生成所需的结果
你应该避免使用setPreferredSize,只需让容器和布局管理器来处理它.请参阅Java Swing中是否应避免使用set(Preferred | Maximum | Minimum)Size方法?更多细节.
您还应该尝试使用packon JFrame来允许窗口在内容周围打包
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |