不确定为什么会出现此错误。我正在使用GroupLayout,因为我希望它为我做间距,并将在未来向框架添加更多面板。下面是堆栈跟踪。
Exception in thread "main" java.lang.IllegalArgumentException: GroupLayout can only be used with one Container at a time
at javax.swing.GroupLayout.checkParent(Unknown Source)
at javax.swing.GroupLayout.invalidateLayout(Unknown Source)
at java.awt.Container.invalidate(Unknown Source)
at java.awt.Component.addNotify(Unknown Source)
at java.awt.Container.addNotify(Unknown Source)
at javax.swing.JComponent.addNotify(Unknown Source)
at java.awt.Container.addNotify(Unknown Source)
at javax.swing.JComponent.addNotify(Unknown Source)
at java.awt.Container.addNotify(Unknown Source)
at javax.swing.JComponent.addNotify(Unknown Source)
at javax.swing.JRootPane.addNotify(Unknown Source)
at java.awt.Container.addNotify(Unknown Source)
at java.awt.Window.addNotify(Unknown Source)
at java.awt.Frame.addNotify(Unknown Source)
at java.awt.Window.pack(Unknown Source)
at client.AlternateGUI.drawGui(AlternateGUI.java:54)
at client.AlternateGUI.main(AlternateGUI.java:24)
以下是代码:
package client;
import java.awt.Component;*
public class AlternateGUI {
private JList people;
private DefaultListModel dlm;
private JLabel l1, l2, l3;
private JFrame alternateGUIFrame;
private final static ImageIcon unavailableIcon = new ImageIcon("offline.png");
public static void main(String[] args)
{
AlternateGUI ls = new AlternateGUI();
ls.drawGui();
}
public AlternateGUI(){
dlm = new DefaultListModel();
people = new JList(dlm);
alternateGUIFrame = new JFrame();
JScrollPane peopleScroller = new JScrollPane(people, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
people.setCellRenderer(new CellRenderer());
GroupLayout alternateGUILayout = new GroupLayout(alternateGUIFrame);
alternateGUIFrame.setLayout(alternateGUILayout);
alternateGUILayout.setAutoCreateGaps(true);
alternateGUILayout.setAutoCreateContainerGaps(true);
alternateGUILayout.setHorizontalGroup(alternateGUILayout.createSequentialGroup()
.addComponent(peopleScroller));
alternateGUILayout.setVerticalGroup(alternateGUILayout.createSequentialGroup()
.addComponent(peopleScroller));
}
public void drawGui() {
l1 = new JLabel("Hi", unavailableIcon , JLabel.LEFT);
l2 = new JLabel("Hello", unavailableIcon , JLabel.LEFT);
l3 = new JLabel("Bye", unavailableIcon , JLabel.LEFT);
dlm.addElement(l1);
dlm.addElement(l2);
dlm.addElement(l3);
alternateGUIFrame.pack();
alternateGUIFrame.setVisible(true);
}
class CellRenderer implements ListCellRenderer
{
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
Component com = (Component)value;
return com;
}
}
}
答案 0 :(得分:22)
您的问题是您在不知不觉中将布局添加到JFrame及其contentPane。解决方案是确保仅将其添加到JFrame的contentPane:
GroupLayout alternateGUILayout = new GroupLayout(alternateGUIFrame.getContentPane());
alternateGUIFrame.getContentPane().setLayout(alternateGUILayout);
这是最重要的第一行。
另一种选择是使用JPanels,然后将JPanels添加到JFrame的contentPane中,其默认的BorderLayout.CENTER位置。