且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPanels和GridLayouts

更新时间:2023-12-05 22:18:40

根据您的设计,不应在JPanel上添加JLabel.在JFrame顶部添加headerLabel并对齐文本CENTER.

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

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.

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.