This example shows you how to create a border that have a title in it. There is a special border class the TitledBorder
that does this. We can define the justification of the title, left, centered or right justify. To do this we call the setTitleJustification()
method. We can also set other attributes such as font or the title position.
package org.kodejava.swing;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
public class TitledBorderExample extends JFrame {
public TitledBorderExample() {
initializeUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new TitledBorderExample().setVisible(true));
}
private void initializeUI() {
setSize(500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
TitledBorder border = new TitledBorder(" Form Data ");
border.setTitleJustification(TitledBorder.LEFT);
border.setTitlePosition(TitledBorder.TOP);
JPanel panel = new JPanel();
panel.setBorder(border);
panel.setLayout(new GridLayout(1, 2));
JLabel usernameLabel = new JLabel("Username: ");
JTextField usernameField = new JTextField();
panel.add(usernameLabel);
panel.add(usernameField);
setContentPane(panel);
}
}
Latest posts by Wayan (see all)
- How do I use Proxy class to configure HTTP and SOCKS proxies in Java? - March 27, 2025
- How do I retrieve network interface information using NetworkInterface in Java? - March 26, 2025
- How do I work with InetAddress to resolve IP addresses in Java? - March 25, 2025