JPanels and GridLayouts

2019-07-17 05:13发布

问题:

I have been attempting to recreate this in Java: http://imgur.com/pjt7SMZ

This is the code I have so far:

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Display extends JFrame implements ActionListener {
    private static final int FRAME_WIDTH = 400;
    private static final int FRAME_HEIGHT = 350;

    private static final int FRAME_X_ORIGIN = 100;
    private static final int FRAME_Y_ORIGIN = 75;

    private JButton readFileButton;
    private JButton exitButton;
    private JButton statsButton;
    private JButton clearButton;
    private JButton helpButton;
    private JLabel headerLabel;

    public Display() {

        setSize(FRAME_WIDTH, FRAME_HEIGHT);
        setResizable(false);
        setTitle("CSCE155A Course Offering Viewer");
        setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel header = new JPanel(new GridLayout(1, 1, 5, 5));
        headerLabel = new JLabel("CSCE155A Course Offering Viewer");
        header.add(headerLabel);

    }

    public static void main(String[] args) {
        Display frame = new Display();
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {

    }

}

My problem is with JPanel. As we were instructed, we are suppose to use the BorderLayout with GridLayout inside, but nothing happens whenever I run the code. Is JPanel even the best way to do this? Right now I'm just trying to get the header to work.

回答1:

According to your design, you should not add JLabel on JPanel. Add headerLabel on top of JFrame and align the text CENTER.

 headerLabel = new JLabel("CSCE155A Course Offering Viewer",JLabel.CENTER);       
 add(headerLabel,BorderLayout.NORTH);// Add it with JFrame.