有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing如何在Java中的JPanel边框中编写文本?

我正在用Java开发GUI,我有以下代码:

public class MainWindow extends JFrame {

    public MainWindow () {
        setUpWindow();

        JPanel upperPanel = new JPanel();
        JPanel lowerPanel = new JPanel();

        upperPanel.setBorder(new LineBorder(Color.GRAY, 1));
        lowerPanel.setBorder(new LineBorder(Color.GRAY, 1));




        getContentPane().add(upperPanel, BorderLayout.NORTH);
        getContentPane().add(lowerPanel, BorderLayout.SOUTH);
    }

    private void setUpWindow () {
        setSize(600, 450);
        setTitle("Subjects");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setLayout(new BorderLayout());
        getRootPane().setBorder(BorderFactory.createMatteBorder(4,4,4,4,Color.LIGHT_GRAY));
        setVisible(true);
    }
}

如果我编译这个,我得到的输出是: enter image description here

正如你所见,我在诺特有一个JPanel,在南部有一个

我想在JPanel的边框中添加文本,这样我就可以得到如下类似的输出:

enter image description here

我试过很多方法,但我不知道怎么做。有没有一个JPanel方法可以做到这一点?我应该创建一个JLabel并以某种方式将其放置在那里吗

提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    你要找的是BorderFactory。它可以这样应用:

    upperPanel.setBorder(BorderFactory.createTitledBorder("Favorite subjects"));
    

    有关JPanel、Borders和what's可能的详细解释(带示例),请参阅Oracle文章How to Use Borders