1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class File
{
 private JFrame frame1;
 private JPanel panel1;
 private JPanel panel2;
 private JLabel labelWeight;
 private JLabel labelHeight;




    File()
    {
     frame1 = new JFrame();
     panel1 = new JPanel();
     panel2 = new JPanel();
     labelWeight = new JLabel("Weight :");
     labelHeight = new JLabel("Height :");


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

     panel1.setLayout(new FlowLayout());
     panel1.add(labelWeight);

     panel2.setLayout(new FlowLayout());
     panel2.add(labelHeight);

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

     frame1.setLayout(new BoxLayout(frame1,BoxLayout.X_AXIS));
     panel1.setAlignmentY(0);
     panel2.setAlignmentY(0);

     frame1.add(panel1);
     frame1.add(panel2);


     frame1.setSize(400, 200);
     frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
     frame1.setVisible(true);
    }


    public static void main (String args[])
    {
     new File();
    }

}   

It gives BoxLayout Sharing error at runtime

Nate W.
  • 9,141
  • 6
  • 43
  • 65
subanki
  • 1,411
  • 10
  • 25
  • 48
  • Exception in thread "main" java.awt.AWTError:BoxLayout cannot be shared at javax.swing.BoxLayout.CheckContainer (Unknown Source) at....so on – subanki Aug 28 '10 at 19:37
  • In a nut shell What is the difference between contentpane and panel . – subanki Aug 28 '10 at 19:38
  • possible duplicate of [\[Java\] Boxlayout can't be shared error](http://stackoverflow.com/questions/761341/java-boxlayout-cant-be-shared-error) – subanki Aug 28 '10 at 19:53

2 Answers2

2

Generally, LayoutManagers are set on a JPanel. I guess JFrame implements this method to forward it to the content pane of the frame. I would suggest you try:

Container contentPane = frame1.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.X_AXIS)); 

If you still have problems take a look at the Swing tutorial on How to Use Box Layout for working examples.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • @subanki - yes, actually you must. `JFrame.add()` and `JFrame.setLayout()` are just delegates; they call the same named method of the result of `getContentPane()` (if rootPaneCheckingEnabled is true). – user85421 Aug 29 '10 at 00:28
1

Swing components should be created in the Event Dispatch Thread. Try this in your main():

javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        new File();
    }
});

But your problem may be the same as this question.

Community
  • 1
  • 1
Arnold Spence
  • 21,942
  • 7
  • 74
  • 67