Reputation: 1
Is it possible to have a panel within a panel in one method in Java?
Like If I created a JPanel
within a method called, CreatePanel
, could I add another one below it? I'm trying to add two or possibly three panels within one method but have not succeeded thus far.
If this is not possible, how would you create a JPanel
, say LeftPanel
, and add another JPanel
within LeftPanel
?
Any help with sources and clear explanation would be terrific because I'm a beginner at Java and sometimes when something you say might be obvious to you and all the CS-jocks but not to me.
Upvotes: 0
Views: 604
Reputation: 347194
The basic premise would follow the same work flow for adding any other component to a panel...
You could do something like...
public JPanel createMasterPane() {
JPanel master = new JPanel(new BorderLayout());
JPanel leftPane = new JPanel();
leftPane.add(new JLabel("Left"));
master.add(leftPane, BorderLayout.WEST);
JPanel rightPanel = new JPanel();
rightPanel.add(new JLabel("Right"));
master.add(rightPanel, BorderLayout.EAST);
return master;
}
A better solution (IMHO) would be to separate the individual areas of responsibility and do something more like this...
public JPanel createLeftPane() {
JPanel leftPane = new JPanel();
leftPane.add(new JLabel("Left"));
return leftPane;
}
public JPanel createRightPane() {
JPanel rightPanel = new JPanel();
rightPanel.add(new JLabel("Right"));
return rightPanel;
}
public JPanel createMasterPane() {
JPanel master = new JPanel(new BorderLayout());
master.add(createLeftPane(), BorderLayout.WEST);
master.add(createRightPane(), BorderLayout.EAST);
return master;
}
You might like to spend some time looking through How to create a UI with Swing for more details...
Upvotes: 3
Reputation: 473
What you ask is possible but i think you will learn more by reading the tutorial on layout managers than being given the answer. Please read up on layout managers and laying out components :)
http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html
Upvotes: 5