0

I want to use a TitledBorder around a JTextField without it taking up too much vertical space.

In the top it applies way more spacing for title font than is needed. Also in the bottom there's a whopping 4 pixels I can't use.

This occurs only on Windows; on Mac OSX the example below looks fine while on W10 the JTextField content is horribly cropped.

Can I reduce this in any way?

import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class MoreSpace {
    static public void main(String args[]) {
        EmptyBorder eb = new EmptyBorder(0, 0, 0, 0);
        TitledBorder tb = new TitledBorder(eb, "Title");
        Font font = new Font("dialog", Font.BOLD, 10); 
        tb.setTitleFont(font);
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(300,26));
        textField.setBorder(tb);
        textField.setText("I cant breathe in here");
        JOptionPane.showMessageDialog(null, textField, "",JOptionPane.PLAIN_MESSAGE);        
    }    
}
Tarik
  • 1
  • 2
    1) Swing/AWT GUIs should be started on the EDT. 2) See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) The width of a text field is suggested by the number of columns set & the size of the font. Height is determined from the font size. – Andrew Thompson Jul 16 '17 at 23:50
  • Thanks for the tip! Though in this example case the setPreferredSize method is actually helpful and does set the height of the textfield, which is necessary to demonstrate the cropping effect. – Tarik Jul 17 '17 at 00:03
  • *"which is necessary to demonstrate the cropping effect."* It's likely it **causes** the effect but.. good luck with it. – Andrew Thompson Jul 17 '17 at 08:22
  • Thanks again for helping me search for causes. But in my original code I have the exact same effect using a gridlayout. The method by which its size is restrained seems irrelevant, the cropping effect remains the same. EDIT - to be clear, my goal here is that I WANT to restrain the size, but without swing going overboard on unnecessary cropping – Tarik Jul 17 '17 at 11:50

1 Answers1

3

Create a custom TitledBorder class(from package javax.swing.border) and reduce the maximum EDGE_SPACING as desired.

// Space between the border and the component's edge static protected final int EDGE_SPACING = 2;

this means 2 pixels above and below as padding by default for the TitledBorder. This should explain the 4 pixels you are seeing.

Setting EDGE_SPACING to 0 will do what you are looking for. :)

Alex Moran
  • 31
  • 2