JTextField fields do not work with border

I have a JTextField and I want to install Margin. But when I set any border, it does not work properly. The margin function does not work. This is my code;

 import java.awt.Color; import java.awt.Insets; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.JOptionPane; import javax.swing.JTextField; public class ImageField { public static void main(String[] args) throws IOException { JTextField textField = new JTextField(); textField.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY)); textField.setMargin(new Insets(0, 20, 0, 0)); JOptionPane.showMessageDialog(null, textField, "", JOptionPane.PLAIN_MESSAGE); } } 

If I start this line, it works

  //textField.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY)); 
+6
source share
2 answers

Margin has some problems with Border to get around a problem that you can try using CompoundBorder , setting EmptyBorder as the inner border, and the desired border (Border line in your case) as the outer border.

Something like this should work:

 Border line = BorderFactory.createLineBorder(Color.DARK_GRAY); Border empty = new EmptyBorder(0, 20, 0, 0); CompoundBorder border = new CompoundBorder(line, empty); textField.setBorder(border); 
+15
source

Read it from JavaDoc .

Sets the space between the text component and its text. The default Border object for the text component will use this value to create the correct field. However, if a border other than the standard one is set in the text component, this means that the Border object is responsible for creating the corresponding space of spaces (otherwise this property will be effectively ignored). This causes the component to redraw. The PropertyChange ("margin") event is dispatched to all listeners.

You are probably looking for a composite frame:

 BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.DARK_GRAY), BorderFactory.createEmptyBorder(0, 20, 0, 0)); 
+5
source

Source: https://habr.com/ru/post/915178/


All Articles