I am working on a GUI in Java and I have the following code:
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);
}
}
If I compile this, the output I get is:
As you can see, I have one JPanel at NORHT and another one at SOUTH.
I want to add text in the border of a JPanel so I can get as an output something similar as this:
I have tried multiple things but I don't know how. Is there a JPanel method that does this? Should I create a JLabel and place it there somehow?
Thanks in advance.
What you're looking for is the BorderFactory. It can be applied like so:
upperPanel.setBorder(BorderFactory.createTitledBorder("Favorite subjects"));
For a detailed explanation of JPanels, Borders and what's possible (with examples), see the Oracle article How to Use Borders.