以下用于布置组件的代码返回错误
public class MainPanel extends JPanel
{
private JTextField txt1, txt2;
private JButton btnCopy, btnCut, btnDel;
private JPanel wrapper1, wrapper2;
public MainPanel()
{
txt1 = new JTextField();
txt2 = new JTextField();
btnCopy = new JButton("Copy");
btnCut = new JButton("Cut");
btnDel = new JButton("Delete");
wrapper1 = new JPanel();
wrapper1.setLayout(new BoxLayout(wrapper1, BoxLayout.Y_AXIS));
wrapper1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
wrapper1.add(txt1);
wrapper1.add(txt2);
wrapper2 = new JPanel();
wrapper2.setLayout(new BoxLayout(wrapper1, BoxLayout.Y_AXIS));
wrapper2.setBorder(BorderFactory.createLineBorder(Color.BLACK));
wrapper2.add(btnCopy);
wrapper2.add(btnCut);
wrapper2.add(btnDel);
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(wrapper1);
add(wrapper2);
}
}
我知道类似的问题BoxLayout can't be shared error
但这不能解决我的问题,因为我不是使用JFrame而是使用JPanel
错误:
Exception in thread "AWT-EventQueue-0" java.awt.AWTError: BoxLayout can't be shared
at javax.swing.BoxLayout.checkContainer(BoxLayout.java:464)
at javax.swing.BoxLayout.invalidateLayout(BoxLayout.java:248)
at javax.swing.BoxLayout.addLayoutComponent(BoxLayout.java:281)
at java.awt.Container.addImpl(Container.java:1120)
at java.awt.Container.add(Container.java:410)
at copycut.MainPanel.<init>(MainPanel.java:39)
at copycut.CopyCut.<init>(CopyCut.java:23)
at copycut.CopyCut$1.run(CopyCut.java:39)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
最佳答案
我相信代替:
wrapper2.setLayout(new BoxLayout(wrapper1, BoxLayout.Y_AXIS));
您想做:
wrapper2.setLayout(new BoxLayout(wrapper2, BoxLayout.Y_AXIS));
现在,您为父级创建一个带有
BoxLayout
的新wrapper1
,并尝试通过将其设置为wrapper2
的布局来“共享”它。这只是一个模糊不清的内容(或者在快速复制/粘贴后最有可能遗漏的内容):p关于java - Java BoxLayout返回错误BoxLayout不能共享,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21428080/