【发布时间】:2014-04-06 22:18:28
【问题描述】:
我正在寻找的是针对我的场景使用的最佳布局的建议。我基本上有任意数量的子面板,它们可以在一个容器面板中,可以由用户动态调整大小。所有子面板的宽度均为 300 像素,并且可以具有可变高度。我希望将面板从左到右、从上到下放置到面板中,就像FlowLayout 一样。但是,我使用FlowLayout 尝试的任何操作都会使面板垂直居中且高度较小。我希望面板固定在屏幕顶部。
我使用FlowLayout 创建了以下示例来说明我的意思。
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DynamicPanel extends JPanel {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new DynamicPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
public DynamicPanel() {
setupGUI();
}
private void setupGUI() {
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.add(getPanel(1, 4));
this.add(getPanel(2, 2));
}
private JPanel getPanel(int panelNum, int numButtons) {
JPanel panel = new JPanel(new GridBagLayout()) {
@Override
public Dimension getPreferredSize() {
Dimension ret = super.getPreferredSize();
ret.width = 300;
return ret;
}
};
panel.add(new JLabel("Panel "+panelNum), getGrid(0, 0, 1.0, 0));
for(int i = 0; i < numButtons; i++) {
panel.add(new JButton("Button"), getGrid(0, i+1, 1.0, 0));
}
return panel;
}
/*
* Returns the GridBagConstraints for the given x, y grid location
*/
private GridBagConstraints getGrid(int x, int y, double xweight, double yweight) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.weightx = xweight;
c.weighty = yweight;
return c;
}
}
在本例中,我希望标签 Panel1 和 Panel2 彼此垂直,而不是 Panel2 设置得较低,因为关联的面板居中。
我想我可以使用 GridBagLayout,并向容器面板添加一个组件侦听器,并在调整容器面板大小时为每个子面板相应地编辑 GridBagContraints,但我想知道是否有更好的方法这?如果这很重要,在实际程序中,子面板将是自定义面板,而不仅仅是按钮列表。
提前感谢您的帮助!
【问题讨论】: