使用GroupLayout和下面的代碼,我注意到leftPanel沒有更新它的首選大小。我認爲這應該是自動的,似乎可以在其他佈局管理器中工作。我如何通過GroupLayout獲得該行爲?爲什麼我的JPanel的首選大小在其包含的JScrollPane在GroupLayout中有更改時會更改?
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SizeTesting {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
JSplitPane splitPane = new JSplitPane();
final JPanel leftPanel = new JPanel();
final DefaultListModel listModel = new DefaultListModel();
final JList list = new JList(listModel);
final JScrollPane jsp = new JScrollPane(list);
leftPanel.add(jsp);
splitPane.setLeftComponent(leftPanel);
GroupLayout panel1Layout = new GroupLayout(leftPanel);
leftPanel.setLayout(panel1Layout);
panel1Layout.setHorizontalGroup(
panel1Layout.createParallelGroup()
.addComponent(jsp, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
);
panel1Layout.setVerticalGroup(
panel1Layout.createParallelGroup()
.addGroup(GroupLayout.Alignment.TRAILING, panel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jsp, GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE))
);
JPanel rightPanel = new JPanel();
JButton button = new JButton("Add Long Item");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Preferred Size of List BEFORE: " + list.getPreferredSize());
System.out.println("Preferred Size of ScorllPane BEFORE: " + jsp.getPreferredSize());
System.out.println("Preferred size of LeftPanel BEFORE: " + leftPanel.getPreferredSize());
System.out.println();
listModel.addElement("Really long, new Item in List");
System.out.println("Preferred Size of List AFTER: " + list.getPreferredSize());
System.out.println("Preferred Size of ScorllPane AFTER: " + jsp.getPreferredSize());
System.out.println("Preferred size of LeftPanel AFTER: " + leftPanel.getPreferredSize());
}
});
rightPanel.add(button);
splitPane.setRightComponent(rightPanel);
listModel.addElement("Test");
listModel.addElement("Test2");
listModel.addElement("Test3");
frame.add(splitPane);
frame.setVisible(true);
}
} // end class SizeTesting
是的,我似乎不公平地指責GroupLayout。在我的代碼中,GUI構建器在addComponent()方法中設置JScrollPane的首選大小。一旦像這樣手動設置組件的preferredSize,它就不會再次「自動調整」它的preferredSize,這就是問題的原因。 有沒有什麼辦法來恢復組件的preferredSize的「自動調整大小」行爲,我想知道? – acarlow 2010-09-10 07:34:11
你可以通過setPreferredSize(null)來做到這一點。 – Dave 2011-05-05 13:24:38