Skip to main content

Adding components (JPanel)s with different layout managers

3 replies [Last post]
sturodgers
Offline
Joined: 2007-06-10

Is there any problem with adding different components to a GUI and using different layout managers?
For example, if I use NetBean's GUI builder to initially build an application, javax.swing.GroupLayout is used to layout all of the panels and buttons, etc. in the generated code.

Then, I would like to add an org.jfree.JFreeChart object using a org.jfree.chart.ChartPanel into one of my JPanels. (FYI, ChartPanel extends javax.swing.JPanel) The default layout manager for a ChartPanel is FlowLayout.

The code to add the ChartPanel is:

<br />
        ChartPanel trngChart = demoChart();<br />
        JPanel chartJPanel = getChartsJPanel();<br />
        chartJPanel.add(trngChart);<br />

I haven't gotten this to show the chart yet. If I pop it up in its own window (I use a new JFrame for this) rather than using a JPanel in the existing GUI, then it works just fine.
So, I have started tinkering with the layout managers...no luck yet.

Thanks
Stu

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
sturodgers
Offline
Joined: 2007-06-10

I will need to look into this a bit more.
I have found that adding in a generic JButton (instead of the ChartPanel) also does not seem to work.
Possibly there is some trick to adding visual components that I have overlooked.
The code for adding the JButton is:

[code] JPanel cjp = getChartsJPanel();
cjp.add(new JButton("press me"));
[/code]

sturodgers
Offline
Joined: 2007-06-10

This had something to do with the layout manager that I have not yet completely grokked.
When I add:

[code]cjp.setLayout(new FlowLayout());[/code]

before I add the component, it works just fine.
The previous layout manager was a GroupLayout.
When I figure out the right code for adding a component with the GroupLayout manager, I will post it.
Regards.

sturodgers
Offline
Joined: 2007-06-10

The previous problem was improper use of a GroupLayout.
Here is the minimum code that I have found that works using the GroupLayout to add a single JButton to a JPanel:

[code]
JPanel bjp = getButtonJPanel();
JButton btn = new JButton("press me too");
GroupLayout lm = (GroupLayout)bjp.getLayout();
lm.setAutoCreateContainerGaps(true);
lm.setAutoCreateGaps(true);
GroupLayout.SequentialGroup hGroup = lm.createSequentialGroup();
hGroup.addComponent(btn);
lm.setHorizontalGroup(hGroup);
GroupLayout.SequentialGroup vGroup = lm.createSequentialGroup();
vGroup.addComponent(btn);
lm.setVerticalGroup(vGroup);
bjp.revalidate();
[/code]

Obviously, using a FlowLayout is a bit simpler for a single component. I think I will only use GroupLayout when I can't get the job done an easier way.....
:)