我需要知道如何構建一個動態調整大小的java佈局。佈局設置了4個面板,從頂部到底部堆疊:如何構建一個在java中動態調整大小的佈局?
頂部面板是一個GridLayout(4,2)。每個rown是一個標籤和一個文本字段 第二個面板是單個按鈕 第三個面板是一個網格佈局(n,2)。我會在一分鐘內得到n 底部面板也是單個按鈕
n是一個動態變化的數字。第三個面板包含一個文本字段,然後是一個右邊有2個按鈕的面板。我遇到的問題是我需要能夠添加和刪除這些行,並讓JFrame像我一樣自動調整大小。我嘗試將Frame設置爲GridLayout(4,1),但是當我更改actionPerformed()的大小時,它均勻地擴展了額外的空間。我想只爲第三個面板添加空間。
感謝
編輯:actionPerformed方法
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src == addTarget) {
targetChoosers.add(new JFileChooser(new File("C:\\")));
targets.add(new JTextField());
targetButtons.add(new JButton("Browse..."));
targetDeleters.add(new JButton("Delete"));
int numTargets = targets.size();
targetButtons.get(numTargets - 1).addActionListener(this);
targetDeleters.get(numTargets - 1).addActionListener(this);
bottomPanel.setLayout(new GridLayout(numTargets, 2));
bottomPanel.add(targets.get(numTargets - 1));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.add(targetButtons.get(numTargets - 1));
panel.add(targetDeleters.get(numTargets - 1));
bottomPanel.add(panel);
}
//...
else if (targetDeleters.contains(src)) {
int index = targetDeleters.indexOf(src);
targets.remove(index);
targetChoosers.remove(index);
targetButtons.remove(index);
targetDeleters.remove(index);
this.remove(submit);
this.remove(bottomPanel);
int numTargets = targets.size();
bottomPanel = new JPanel(new GridLayout(numTargets, 2));
for (int i = 0; i < targets.size(); i++) {
bottomPanel.add(targets.get(i));
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
panel.add(targetButtons.get(i));
panel.add(targetDeleters.get(i));
bottomPanel.add(panel);
}
this.add(bottomPanel);
this.add(submit);
}
//...
pack();
invalidate();
validate();
}
請提供[sscce](http://sscce.org/),其中顯示瞭如何在按鈕偵聽器中調用'pack()'。 – trashgod
@trashgod我已經發布了actionperformed方法(無論如何,相關部分)。我不確定pack()會如何幫助,因爲GridLayout會自動將組件的大小設置爲均勻分佈在整個框架中 – ewok
@ewok然後在此處發佈基於SSCCE的可運行代碼,然後您將看到許多具有佈局的奇蹟:-) – mKorbel