Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTextField margin doesnt work with border

I have a JTextField and i want to setMargin. But when i set any border, it doesn' t properly work. It' s margin function doesn't 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 commant this line, it works

 //textField.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
like image 691
querman Avatar asked May 08 '12 10:05

querman


People also ask

What is the difference between JTextField and JTextArea?

The main difference between JTextField and JTextArea in Java is that a JTextField allows entering a single line of text in a GUI application while the JTextArea allows entering multiple lines of text in a GUI application.

How do I limit the length of a JTextField?

We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.

How do I change the shape of a JTextField?

The important methods of a JTextField class are setText(), getText(), setEnabled() and etc. By default, a JTextfield has a rectangle shape, we can also implement a round-shaped JTextField by using the RoundRectangle2D class and need to override the paintComponent() method.


1 Answers

Margin have some problem with Border, to work around the problem you can try using a CompoundBorder setting an EmptyBorder as inner border and the desired border (lineBorder in your case) as 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);
like image 80
aleroot Avatar answered Oct 08 '22 23:10

aleroot