由于JFrame
,我想制作一个包含两个JPanel
的{{1}}。左边是结果(尽管是Layout
),右边是我调整框架的大小:
这是最小化的代码:
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
,但它并没有解决我的问题。我已经检查了Can components of a gridbaglayout fill parent frame upon resize?,GridBagLayout doesn't fill all the space和其他许多来源。
答案 0 :(得分:1)
名为void
的{{1}}方法看起来很可疑。
JFrame
我认为你打算写一个像
这样的构造函数public void JFrame() { ... }
您正在编写的布局代码未被调用。这个修复可以解决这个问题。
希望这有帮助。