按钮未显示在 JPanel 中

Buttons not showing up in JPanel

我很难弄清楚为什么这里的按钮不显示?今天早些时候,当我测试 运行 程序时,它们出现了,但现在我已经停滞了 2 个小时,试图让按钮再次出现。这也很奇怪,因为面板肯定会出现,因为出现了“欢迎使用 BookListApp”这句话。

    public BookListUI() {
        textPrompt.setText("Welcome to the BookListApp, fellow bookworm. Start storing your books immediately!");
        textPrompt.setBounds(WIDTH / 2 - 300, 50,500,100);
        frame = new JFrame();
        panel = new JPanel();

        panel.setLayout(null);
        panel.setSize(WIDTH, HEIGHT);
        panel.add(textPrompt);
        addButtons();
        frame.setSize(WIDTH, HEIGHT);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("BookList Application");
        frame.setVisible(true);

    }

    public void addButtons() {
        panel.add(new JButton("Finished books"));
        panel.add(new JButton("Favorite books"));
        panel.add(new JButton("Search by genre"));
        panel.add(new JButton("Save all your books!"));
        panel.add(new JButton("Load your BookList Application"));
        panel.add(new JButton("Exit application"));
    }


    public static void main(String[] args) {
        new BookListUI();
    }

如果您使用绝对布局 (panel.setLayout(null);),那么您必须指定要显示的按钮的边界:

button.setBounds(200, 200, 300, 30);

使用一个或多个合适的布局管理器。请参阅 在容器中布置组件 了解更多详情

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class BookListUI {

    JLabel textPrompt = new JLabel("Welcome to the BookListApp, fellow bookworm. Start storing your books immediately!", JLabel.CENTER);

    public BookListUI() {
        JFrame frame = new JFrame();

        JPanel contentPane = new JPanel(new BorderLayout());
        contentPane.setBorder(new EmptyBorder(32, 32, 32, 32));
        frame.setContentPane(contentPane);

        frame.add(textPrompt, BorderLayout.NORTH);
        JPanel menuPane = new JPanel(new GridLayout(-1, 1));
        menuPane.setBorder(new EmptyBorder(32, 32, 0, 32));
        addButtons(menuPane);
        frame.add(menuPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setTitle("BookList Application");
        frame.setVisible(true);

    }

    public void addButtons(Container container) {
        container.add(new JButton("Finished books"));
        container.add(new JButton("Favorite books"));
        container.add(new JButton("Search by genre"));
        container.add(new JButton("Save all your books!"));
        container.add(new JButton("Load your BookList Application"));
        container.add(new JButton("Exit application"));
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new BookListUI();
            }
        });
    }
}