1

Hi there I am working on a Java app and below is an excerpt from a custom class called Gui which extends JFrame:

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);
}

I have read many tutorials and the api and really can not see anything wrong with this, however the line reading: add(headerRow); seems to be the trigger for a "BoxLayout can't be shared" error. If I change the layout for the JFrame to a flowlayout the nested boxlayout applied to the firstRow section works fine?

Can anyone help please?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
danparker
  • 49
  • 4

1 Answers1

3

Change this:

BoxLayout layout = new BoxLayout(this, BoxLayout.Y_AXIS);

to this:

BoxLayout layout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);

The error-producing code passes the JFrame into the BoxLayout's constructor as the BoxLayout using container when in fact it's not. In truth, you're adding the layout to the JFrame's contentPane and not the JFrame.

As an aside, you may be painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373