布置组件的以下代码返回错误
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不能共享错误但这并不能解决我的问题,因为我不是在使用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));
目前,您可以使用 wrapper1
创建一个新的 BoxLayout
,并尝试通过使其成为wrapper2
的布局来"共享"它。这只是一个错误的(或快速复制/粘贴后的省略):p