0

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

2

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Tiny nitpick, but I'm not sure calling `pack` counts as 'rendering'. – BeUndead Feb 08 '20 at 21:36
  • 1
    @BeUndead: While `pack()` doesn't display the GUI, it does size it for display, and so you're right, and I'll correct this, but still, calling `pack()` *will* resize the contained components, if appropriate layout managers are used. – Hovercraft Full Of Eels Feb 08 '20 at 21:39
  • Thanks for the edit. And no argument here, I appreciate `pack` would resolve the issue. The answer before just read as if it had to be _rendered_ first, which wasn't quite right as pointed out within the answer itself. +1'd. – BeUndead Feb 09 '20 at 03:14
  • @BeUndead: the reason for my wording was based on my (perhaps faulty) recollection of the description of the rendering process in the book, "Filthy Rich Components" by Guy and Haase, a must-have book for any Swing developers, back when we were actually developing Swing applications. – Hovercraft Full Of Eels Feb 09 '20 at 03:20
  • *"Finding out/calculating the width of a [component]"* (scratches head) .. Why? Only a couple of times in the last decade have I needed to know the size of a component, and that is when dealing with scroll panes or when painting components directly into graphics. See [What is the XY problem?](http://meta.stackexchange.com/q/66377) – Andrew Thompson Mar 10 '20 at 17:30
0

You can add a component listener to the object it worked at me. In this listener you can use some events like componentResized or componentShown for getting the width and height of the component.

  • *"events like onresized or onshown"* A (Java) [`ComponentListener`](https://docs.oracle.com/en/java/javase/13/docs/api/java.desktop/java/awt/event/ComponentListener.html) does not have either of those methods. Are you thinking instead of Javascript? – Andrew Thompson Mar 10 '20 at 17:24