3

I want to show titled separator in java swing application. Something like

-------Text-------

I found some third party libraries providing this functionality:

But I'm interested in a way without using any third party api. Can we do this by extending JSeparator? How else can we do that?

Radu Murzea
  • 10,724
  • 10
  • 47
  • 69
Harry Joy
  • 58,650
  • 30
  • 162
  • 207

3 Answers3

5

I think you might be able to use a combination of a MatteBorder and a TitledBorder

MatteBorder mb = new MatteBorder(1, 0, 0, 0, Color.BLACK);
TitledBorder tb = new TitledBorder(mb, "Some Long Text", TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION);
rofrol
  • 14,438
  • 7
  • 79
  • 77
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
4

Use a TitledBorder. Like this for example:

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;

public class TestBorder {

    protected void initUI() {
        JFrame frame = new JFrame(TestBorder.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        TitledBorder titledBorder = BorderFactory.createTitledBorder("Some title");
        titledBorder.setTitleJustification(TitledBorder.CENTER);
        panel.setBorder(titledBorder);
        frame.add(panel);
        frame.setSize(400, 300);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestBorder().initUI();
            }
        });
    }

}
Guillaume Polet
  • 47,259
  • 4
  • 83
  • 117
  • It shows text to left, I want the text to be in the center of line separator. – Harry Joy Jul 13 '12 at 08:00
  • @mark updated my code. Simply set the justification of the border. – Guillaume Polet Jul 13 '12 at 08:02
  • titledBorder (aka: GroupBoxes) introduce visual noise, so don't use them - nowadays, even win ux guide cautions against using them ... @mark it's rather straightforward to implement a TitledSeperator for yourself, or extract the code from open source projects like SwingX or any other you already found – kleopatra Jul 13 '12 at 08:36
  • @mark exactly :-) Have a look at Karsten's (JGoodies) articles/talks – kleopatra Jul 13 '12 at 08:56
0

That is simple and lower case.

import javax.swing.border.*;

then

BevelBorder bedge=new BevelBorder(BevelBorder.RAISED);
lbl.setBorder(bedge);

-----------------next border type

import javax.swing.border.*;

then

TitledBorder tedge=new TitledBorder(TitledBorder.CENTER);
lbl.setBorder(tedge);
Drew
  • 24,851
  • 10
  • 43
  • 78