public class TopPanel extends JPanel {
public TopPanel() {
TopPanel tp = new TopPanel();
tp.add(new JLabel("Course Info"));
tp.setSize(300,300);
tp.setVisible(true);
}
}
By creating a TopPanel object inside its own constructor you are causing near infinite recursion:
- your TopPanel constructor will create a new TopPanel object
- whose constructor will create a new TopPanel object
- whose constructor will create a new TopPanel object
- whose constructor will create a new TopPanel object whose constructor ,....
- ... etc -- recursion until your memory runs out. Don't do this.
- whose constructor will create a new TopPanel object whose constructor ,....
- whose constructor will create a new TopPanel object
- whose constructor will create a new TopPanel object
Instead, don't do this:
public class TopPanel extends JPanel {
public TopPanel() {
// get rid of the recursion
// TopPanel tp = new TopPanel();
// add the label to the current TopPanel object, the "this"
add(new JLabel("Course Info"));
// setSize(300,300); // generally not a good idea
// tp.setVisible(true); // not needed
}
// this is an overly simplified method. You may wish to calculate what the
// preferred size should be, or simply don't set it and let the components
// size themselves.
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
Edit
Also, while not in error, this:
JPanel topPane = new TopPanel();
JPanel topPanel = new JPanel();
is very confusing since the two JPanel variables are close enough in name to confuse us, and more importantly to confuse your future self. You will want to use more logical and distinct variable names.