tags:

views:

5075

answers:

2

I have this Java JFrame class, in which I want to use a boxlayout, but I get an error saying "java.awt.AWTError: BoxLayout can't be shared". I've seen others with this problem, but they solved it by creating the boxlayout on the contentpane, but that is what I'm doing here. Here's my code:

class edit_dialog extends javax.swing.JFrame{
    javax.swing.JTextField title = new javax.swing.JTextField();
    public edit_dialog(){
        setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
        setTitle("New entity");
        getContentPane().setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));
        add(title);
        pack();
        setVisible(true);
    }
}
+12  A: 

Your problem is that you're creating a BoxLayout for a JFrame (this), but setting it as the layout for a JPanel (getContentPane()). Try:

getContentPane().setLayout(
    new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS)
);
Michael Myers
Thanks, worked perfectly :D
Might want to reformat the code sample slightly: the line is a little too wide to render without a slider.
Bob Cross
@Bob Cross: Done.
Michael Myers
Of course you don't need the first getContentPane... :-)
Tom Hawtin - tackline
Yes, but removing it would confuse the issue, now wouldn't it?
Michael Myers
A: 

I've also found this error making this:

JPanel panel = new JPanel(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

The JPanel isn't initialized yet when passing it to the BoxLayout. So split this line like this:

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));

This will work.

Joaquín M