BoxLayout can't be shared error?
本问题已经有最佳答案,请猛点这里访问。
您好,我在Java应用程序上工作,下面是一个自定义类Gui的摘录,该类扩展了JFrame:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | public Gui(){ super("EVC Scan & Price"); setSize(400,500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); // GridLayout layout = new GridLayout(5,1); BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS); setLayout(layout); //add header row headerRow.setAlignmentX(Component.CENTER_ALIGNMENT); BorderLayout layoutHeading = new BorderLayout(); headerRow.setLayout(layoutHeading); if (headerImg != null){ ImageIcon icon = new ImageIcon(headerImg); picLabel.setIcon(icon);} headerRow.add(picLabel, BorderLayout.NORTH); title.setAlignmentX(JLabel.CENTER_ALIGNMENT); headerRow.add(title, BorderLayout.SOUTH); add(headerRow); //add first row firstRow.setAlignmentX(Component.LEFT_ALIGNMENT); BoxLayout layoutRow1 = new BoxLayout(firstRow,BoxLayout.Y_AXIS); firstRow.setLayout(layoutRow1); firstRow.add(catLabel); scroll.setSize(390,100); firstRow.add(scroll); add(firstRow); setVisible(true); } |
我已经阅读了许多教程和api,但确实看不到任何错误,但是请看下面的代码:add(headerRow);似乎是"无法共享BoxLayout"错误的触发因素。
如果我将JFrame的布局更改为flowlayout,则应用于firstRow部分的嵌套boxlayout可以正常工作吗?
有人可以帮忙吗?
更改此内容:
为此:
产生错误的代码实际上使用容器将JFrame作为使用容器的BoxLayout传递到BoxLayout的构造函数中。实际上,您是将布局添加到JFrame的contentPane而不是JFrame。
顺便说一句,您可能想通过使类扩展JFrame来迫使自己处于困境,迫使您创建和显示JFrame,而通常需要更大的灵活性。实际上,我敢冒险发现我创建的大多数Swing GUI代码都不会扩展JFrame,实际上,很少有人愿意这样做。更常见的是,您的GUI类将面向创建JPanels,然后将其放置到JFrames或JDialogs或JTabbedPanes中,或者在需要时通过CardLayouts进行交换。这将大大增加您的GUI编码的灵活性。