How to display a control in JPanel during runtime
I had a problem in a Java project about not able to display a JTree into a JPanel. The JPanel is created during design time. The problem is JTree is created during runtime and adding the JTree into the JPanel
will not display the control when executing the application.
The code below won't work:
JTree treeObject = new JTree();
panelObject.add(treeObject);
There is one more thing to do to make it work by adding a group layout.
//---------- START
JTree treeObject = new JTree();
panelObject.add(treeObject);
javax.swing.GroupLayout myLayout = new javax.swing.GroupLayout(panelObject);
panelObject.setLayout(myLayout);
myLayout.setHorizontalLayout(
myLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(treeObject, panelObject.getWidth(), panelObject.getWidth(), panelObject.getWidth())
);
myLayout.setVerticalGroup(
myLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(treeObject, panelObject.getHeight(), panelObject.getHeight(), panelObject.getHeight() );
//--------- END
That's it!
will not display the control when executing the application.
The code below won't work:
JTree treeObject = new JTree();
panelObject.add(treeObject);
There is one more thing to do to make it work by adding a group layout.
//---------- START
JTree treeObject = new JTree();
panelObject.add(treeObject);
javax.swing.GroupLayout myLayout = new javax.swing.GroupLayout(panelObject);
panelObject.setLayout(myLayout);
myLayout.setHorizontalLayout(
myLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(treeObject, panelObject.getWidth(), panelObject.getWidth(), panelObject.getWidth())
);
myLayout.setVerticalGroup(
myLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(treeObject, panelObject.getHeight(), panelObject.getHeight(), panelObject.getHeight() );
//--------- END
That's it!
Comments
Post a Comment