How can I add padding to a jtextfield

后端 未结 6 1694
予麋鹿
予麋鹿 2021-01-01 12:08

How can I add some padding to a jtextfield? I\'ve tried tf.setMargin(new Insets(5,5,5,5)); which doesn\'t have any effect.

相关标签:
6条回答
  • 2021-01-01 12:26
    yourTextFeildVariable.setBorder(BorderFactory.createCompoundBorder(yourTextFeildVariable.getBorder(), BorderFactory.createEmptyBorder(0, 5, 0, 0)));
    

    This is working 100%

    0 讨论(0)
  • 2021-01-01 12:26

    You can apply this to a textbox already created with a border

    jTextField1.setBorder(BorderFactory.createCompoundBorder(jTextField1.getBorder(), BorderFactory.createEmptyBorder(6, 6, 6, 6)));
    
    0 讨论(0)
  • 2021-01-01 12:33

    you have look at CompoundBorder, there you can set LineBorder(Color.gray, 1) and with

    EmptyBorder(5, 5, 5, 5)
    
    0 讨论(0)
  • 2021-01-01 12:35

    The problem you are having is that the UI is setting its own border on the text field, overriding the margin you set. You can see a warning to this effect in the javadoc of setMargin().

    The solution is to let the UI set a border, then squeeze in another border of your own:

    field.setBorder(BorderFactory.createCompoundBorder(
            field.getBorder(), 
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    
    0 讨论(0)
  • 2021-01-01 12:36

    The simplest way is using BorderFactory

    field.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    
    0 讨论(0)
  • 2021-01-01 12:42

    I know this is years too late, but actually, if you want a consistent look and feel in Java, you should be editing the UI so every text field you create doesn't need its own special code. So, taking from Russel Zahniser's example above:

    Border tfBorder = UIManager.getBorder("TextField.border");
    Border newBorder = BorderFactory.createCompoundBorder(tfBorder, 
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
    
    UIManager.setBorder("TextField.border", newBorder);
    
    0 讨论(0)
提交回复
热议问题