Search code examples
javaswingtitled-border

How to find the x position of the title in TitledBorder


I've tried getTitlePosition, but it only seems to return the border's starting point, 0, not the title itself. I also tried getBorderJustification, but it returned the int value for Center.

Is there a way to get the x position for the actual text in a TitledBorder?

Box container = Box.createVerticalBox();
Box topBox = new Box(BoxLayout.PAGE_AXIS);
Box btmBox = new Box(BoxLayout.PAGE_AXIS);
TitledBorder border = new TitledBorder("Title");
border.setTitleJustification(TitledBorder.CENTER);

topBox.add(new JLabel(new ImageIcon(new BufferedImage(200,40,BufferedImage.TYPE_INT_RGB))));
btmBox.add(new JLabel(new ImageIcon(new BufferedImage(200,40,BufferedImage.TYPE_INT_RGB))));

topBox.setBorder(border);
btmBox.setBorder(border);

container.add(topBox);
container.add(btmBox);

Solution

  • I couldn't figure out how to ensure that the popup stays above the title if the title is centered

    So you will need to check the title location. if it is centered then you use basic math:

    1. you know the width of the panel
    2. you know the width of the popup
    3. subtract the popup width from the panel width and divide by 2.