Adding a JPanel from a class to a JFrame in main class

I am trying to add this panel:

import javax.swing.*;
import java.awt.*;

class TopPanel extends JPanel{
    public TopPanel() {
        JPanel panel = new JPanel();
        JLabel label = new JLabel("Course Lookup GUI");
        panel.add(label);
        panel.setVisible(true);
    }
}

To a frame like this:

import javax.swing.*;
import java.awt.*;

class CourseGUI extends JFrame{
    public CourseGUI() {
        this.setLayout(new FlowLayout());
        this.setLocation(200,200);

        TopPanel    tPan = new TopPanel();
        MiddlePanel mPan = new MiddlePanel();

        this.add(tPan);
        this.add(mPan);

        this.setVisible(true);
    }

    public static void main(String[] args){
        CourseGUI cGUI = new CourseGUI();
    }
}

But nothing is adding to the frame, and I'm getting an empty window. What am I doing wrong?

Answers


Since your class already extends JPanel, there is no need to create another panel. Just add the label to the class itself

class TopPanel extends JPanel{
    public TopPanel() {
        //JPanel panel = new JPanel();
        JLabel label = new JLabel("Course Lookup GUI");
        add( label );
        //panel.add(label);
        //panel.setVisible(true);
    }
}

I also agree with Reimeus's comment. There is no need to extend JPanel to do this functionality. Just do:

JPanel tPan = new JPanel;
JLabel label = new JLabel("Course Lookup GUI");
tPan.add(label);
this.add( tPan );

Or even easier, since you are just adding one component to the panel, there is no need to even create the panel. Just do:

JLabel label = new JLabel("Course Lookup GUI");
this.add( label );

Need Your Help

data omisson while using ms ace driver to read csv file

csv oledb

There must be some explanation for this. My csv file is something like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.