Search code examples
javaswingjtextfield

Finding out/calculating the width of a symbol


Finding out/calculating the width of a symbol

panel.add(textfield,BorderLayout.SOUTH);

system.out.println(textfield.getWidth());
System.out.println(textfield.getHeight());

both return 0, which should be more

graphically returns, i mean returning correct


Solution

  • Your problem:

    You're likely calling getWidth() and getHeight() on the Swing component before the component has been sized and rendered by Swing, and so at that time the component has not been sized for the GUI and the values being returned to you are correct, are in fact, 0.

    A solution:

    Instead, call the method after calling pack() or setVisible(true) on the top-level window that contains the JTextField component and after you've added the JTextField. Often this is a JFrame.