【发布时间】:2015-12-03 02:33:24
【问题描述】:
感谢Layout,我想创建一个包含两个JPanels 的JFrame。左边是结果(尽管有setExtendedState(JFrame.MAXIMIZED_BOTH);),右边是我调整框架大小时的结果:
这是最小化的代码:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* The Frame which will contain one or two Panels.
*
*/
class Frame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel panAction;
public void JFrame() {
setLayout(new GridBagLayout());
GridBagConstraints info = new GridBagConstraints();
info.gridx = info.gridy = 0;
//info.gridwidth = 1;
//info.gridheight = 2;
info.fill = GridBagConstraints.BOTH;
//info.weightx = 1;
//info.weighty = 1;
JPanel buttonPanel = new ButtonPanel(this);
add(buttonPanel, info);
setExtendedState(JFrame.MAXIMIZED_BOTH);
pack();
}
public void changeSecondPanel(JPanel panel) {
if(this.panAction != null) {
remove(this.panAction);
}
GridBagConstraints info = new GridBagConstraints();
info.gridx = 0;
info.gridy = 1;
//info.gridwidth = 1;
//info.gridheight = 2;
//info.weightx = 1;
//info.weighty = 1;
info.fill = GridBagConstraints.BOTH;
add(panAction, info);
this.panAction = panel;
}
}
/**
* The upper Panel.
*
*/
class ButtonPanel extends JPanel {
private static final long serialVersionUID = 1L;
public ButtonPanel(final Frame frame) {
setBackground(Color.BLUE);
JButton button = new JButton("CREATE");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
frame.changeSecondPanel(
/**
* The bottom Panel.
*/
new JPanel() {
private static final long serialVersionUID = 1L;
{
setBackground(Color.GREEN);
}
});
}
});
}
}
public class PanelProblem {
public static void main(String[] args) {
new Frame().setVisible(true);
}
}
我尝试了GridLayout 和BorderLayout,但并没有解决我的问题。我已经检查了Can components of a gridbaglayout fill parent frame upon resize?、GridBagLayout doesn't fill all the space 和许多其他来源。
【问题讨论】:
标签: java swing jframe jpanel layout-manager