我正在編寫一個程序,調出一個從配置文件中列出多個選項的JDialog框。每次打開選項的數量都會有所不同,所以我需要能夠動態調整窗口的高度,而不是寬度。該窗口最好使用FlowLayout並定義窗口的寬度,以便數據被包裝的JPanel屬性。但我無法動態調整高度。我嘗試使用pack方法,但它將所有面板按照FlowLayout的意思排成一行。我嘗試了GridLayout,但它將所有面板重新調整爲相同的大小,並且是不可接受的外觀。我也嘗試過BoxLayout,但無法讓它工作。我可以使用pack()僅調整框架的高度嗎?
是否有更好的佈局管理器使用或使寬度靜態?
這是我的代碼。每一個面板和箱構造上述定義,我只是沒有複製代碼:
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]);
}
}
}
爲更好地幫助越早發佈的[SSCCE(HTTP: //sscce.org/),簡短,可運行,可編譯 – mKorbel
你可以嘗試使用類似[WrapLayout](http://tips4java.wordpress.com/2008/11/06/wrap-layout/)或SwingLabs的VerticalLayout, SwingX庫,或者只是使用GridBagLayout,這取決於你的需求 – MadProgrammer
你可以記住寬度,然後在'pack'後恢復它。 –