我正在编写一个程序,它会打开一个JDialog框,列出配置文件中的多个选项。每次打开时选项的数量都会有所不同,因此我需要能够动态调整窗口的高度,而不是宽度。该窗口最好使用FlowLayout并定义窗口的宽度,以便数据处于封装状态的JPanel。但我无法动态调整高度。我尝试使用pack方法,但它将所有面板排成一行,就像FlowLayout一样。我尝试了GridLayout,但它将所有面板重新调整为相同尺寸并且是不可接受的外观。我也试过BoxLayout,但无法让那个工作。
是否有更好的布局管理器或使宽度静态的方法?
这是我的代码。每个面板和框都在构造函数上面定义,我只是没有复制该代码:
public ReSizeMe()
{
curConfig = new Config();
config = curConfig.getConfig();
setBox = new JDialog();
setBox.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // Set as 480, 600
setBox.setLayout(new FlowLayout());
this.buildSetFrame();
//setBox.pack();
setBox.setVisible(true);
}
public void buildSetFrame()
{
intPanel = new JPanel();
butPanel = new JPanel();
optPanel = new JPanel();
editPanel = new JPanel[maxOptions];
optWrapper = new JPanel[maxOptions];
intPanel.setLayout(new FlowLayout());
optPanel.setLayout(new GridLayout(10, 1)); // trying different things here too.
optText = new JTextField[maxOptions];
editButton = new JButton[maxOptions];
delButton = new JButton[maxOptions];
intPanel.setBorder(BorderFactory.createTitledBorder("Modify Interface"));
apply = new JButton("Apply");
newOpt = new JButton("New Option");
help = new JButton("Help");
close = new JButton("Close");
intPanel.add(ethIntLabel);
intPanel.add(ethIntName);
butPanel.add(apply);
butPanel.add(newOpt);
butPanel.add(close);
ethIntName.setText(config.getProperty("EthIntName"));
setBox.add(welcomeMsg);
setBox.add(intPanel);
setBox.add(optPanel);
buildOptions();
setBox.add(butPanel);
}
void buildOptions()
{
for (int i = 0; i < maxOptions; i++)
{
editable = Boolean.parseBoolean(config.getProperty("option." + i + ".edit"));
if (config.getProperty("option." + i + ".name") == null)
{
break;
}
else if (editable != false &&
config.getProperty("option." + i + ".name") != null &&
!config.getProperty("option." + i + ".name").isEmpty())
{
editPanel[i] = new JPanel();
optWrapper[i] = new JPanel();
optText[i] = new JTextField(20);
editButton[i] = new JButton("Edit");
delButton[i] = new JButton("Delete");
editButton[i].setActionCommand(Integer.toString(i));
delButton[i].setActionCommand(Integer.toString(i));
optText[i].setText(config.getProperty("option." + i + ".name"));
optText[i].setEditable(false);
editPanel[i].add(editButton[i]);
editPanel[i].add(delButton[i]);
optWrapper[i].add(optText[i]);
optWrapper[i].add(editPanel[i]);
optPanel.add(optWrapper[i]);
}
}
}
答案 0 :(得分:3)
是的,Box
应该很棒:
Box box = Box.createVerticalBox();
box.add(...)
box.add(Box.createVerticalStrut(5)); // spacing
<etc.>
add(box);