Hi!
I have a following code, which should add p1 panel to a tabbed pane and then add this pane to a frame. Everything seems to be correct, but it just doesn't add a panel to a pane and only adds a pane to a frame.
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class ProtoForm extends JFrame
{
private JTabbedPane tpCategories;
private JLabel l1, l2;
private JTextField tf1, tf2;
private JPanel p1;
public ProtoForm()
{
super("ProtoForm");
setSize(new Dimension(500, 375));
tpCategories = new JTabbedPane();
addSoftComponents(p1);
addTab(tpCategories, "Soft", null, p1, null);
add(tpCategories);
}
private void addTab(JTabbedPane tp, String title, Icon icon, JPanel panel, String tip)
{
tp.addTab(title, icon, panel, tip);
}
private void addSoftComponents(JPanel panel)
{
MigLayout layout = new MigLayout();
panel = new JPanel();
panel.setLayout(layout);
JLabel l1 = new JLabel("label 1");
JLabel l2 = new JLabel("label 2");
JTextField tf1 = new JTextField(35);
JTextField tf2 = new JTextField(35);
panel.add(l1);
panel.add(tf1, "wrap");
panel.add(l2);
panel.add(tf2, "wrap");
}
}
But everything works correctly if I add p1 = new JPanel(); to the the main(). Here is the
working code (!!!! marks modified parts of the code):
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class ProtoForm extends JFrame
{
private JTabbedPane tpCategories;
private JLabel l1, l2;
private JTextField tf1, tf2;
private JPanel p1;
public ProtoForm()
{
super("ProtoForm");
setSize(new Dimension(500, 375));
tpCategories = new JTabbedPane();
!!!! p1 = new JPanel();
addSoftComponents(p1);
addTab(tpCategories, "Soft", null, p1, null);
add(tpCategories);
}
private void addTab(JTabbedPane tp, String title, Icon icon, JPanel panel, String tip)
{
tp.addTab(title, icon, panel, tip);
}
private void addSoftComponents(JPanel panel)
{
MigLayout layout = new MigLayout();
!!!! //panel = new JPanel();
panel.setLayout(layout);
JLabel l1 = new JLabel("label 1");
JLabel l2 = new JLabel("label 2");
JTextField tf1 = new JTextField(35);
JTextField tf2 = new JTextField(35);
panel.add(l1);
panel.add(tf1, "wrap");
panel.add(l2);
panel.add(tf2, "wrap");
}
}
Can someone please explain to me why is it so and how should I redesign the code to create and add panels in procedures outside of main()?
In case someone might need MigLayout it is from http://www.miglayout.com/.