Frage

How do I get the Panel into the Frame. I've tried for hours and just don't get it.

I tried JPanel panel = new TopPanel(); but It just will not call the Frame. Our teacher taught this to us a week ago for the beginner class and ever since this, I've been confused.

Thanks for helping in advance and please explain.

Frame:

public class CourseGUI extends JFrame {
    public CourseGUI()
    {

        super("CourseGUI Frame");


        JPanel topPanel = new JPanel();
        topPanel.setBackground(java.awt.Color.WHITE);
        Dimension d = new Dimension(800,600);

        topPanel.setPreferredSize(d);

        this.setLayout(new BorderLayout());

        this.add(topPanel, BorderLayout.NORTH);

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setSize(800,600);
        //JPanel tp = new TopPanel();
        //this.add(tp.BorderLayout.North);

        JPanel panel = new TopPanel();

        this.setVisible(true);
    }
    public static void main(String[] args)
    {
        new CourseGUI();
    }

}

Panel (Suppose to be on the top)

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


public class TopPanel extends JPanel {

    public TopPanel() {
        JPanel panel = new JPanel();
        JLabel Crse = new JLabel("Course Info");
        Crse.setFont(new Font("Serif", Font.PLAIN, 14));
        panel.add(Crse);

    }
}
War es hilfreich?

Lösung

In the TopPanel class you just add the lable into another JPanel object panel, and this panel is not added into TopPanel. I made a little change in your TopPanel class. (You can change the layout if needed )

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


 public class TopPanel extends JPanel {

     public TopPanel() {

         JLabel Crse = new JLabel("Course Info");
         Crse.setFont(new Font("Serif", Font.PLAIN, 14));
        add(Crse);

     }
 }

use this TopPanel in CourseGui

  JPanel topPanel = new TopPanel();

Please try accept if it worked

You can alsoe use

    JPanel topPanel = new JPanel();
    JLabel Crse = new JLabel("Course Info");
    Crse.setFont(new Font("Serif", Font.PLAIN, 14));
    topPanel.add(Crse);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top