简体   繁体   中英

Java Swing JTextField setMargin unexpected behavior

When I resize the window, my custom JTextField changes size. It only does this once, the first time I resize the window. It's related to this line inside paintComponent :

setMargin(new Insets(2, 25, 2, 2));

Running that command does not resize the text field until I resize the window. After resizing the window, running that command causes JTextField to become larger. Actual size of the window does not matter. The first time window size is changed, JTextField becomes larger and then it stays large until the end of time. I would prefer if the field was large as soon as I start the program, and obviously, I don't want it to randomly change size.

How can I fix the size of this JTextField so that it does not randomly change?

Here is the entire class:

/**
 * From https://gmigdos.wordpress.com/2010/03/30/java-a-custom-jtextfield-for-searching/
 * @author Georgios Migdos <cyberpython@gmail.com> */
public class JIconTextField extends JTextField {

private Icon icon;
private Insets dummyInsets;

public JIconTextField(int columns) throws IOException {
    super(columns);

    Border border = UIManager.getBorder("TextField.border");
    JTextField dummy = new JTextField();
    this.dummyInsets = border.getBorderInsets(dummy);

    String path = "find-16x16.png";
    InputStream is = Main.class.getClassLoader().getResourceAsStream(path);
    setIcon(new ImageIcon(ImageIO.read(is)));
    repaint();
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    int textX = 2;

    if(this.icon!=null){
        int iconWidth = icon.getIconWidth();
        int iconHeight = icon.getIconHeight();
        int x = dummyInsets.left + 5;//this is our icon's x
        textX = x+iconWidth+2; //this is the x where text should start
        int y = (this.getHeight() - iconHeight)/2;
        icon.paintIcon(this, g, x, y);
    }

    setMargin(new Insets(2, textX, 2, 2));
}

}

Further to the comments, if you cut the code out from the paintComponent method and paste it into the constructor, you will get your desired result.

The paintComponent method for actual painting, ie blanking the background of the field and drawing the text. Generally, unless you specifically want to change the way the component is drawn, you should not need to override this method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM