Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Component's getSize() returning negative values

I have a funny situation in which intermittently I get negative values from calling a JLabel's method getSize(). I want to resize a JLabel to grab the maximum space possible but very often I get it upside down like in this question. It seems that an instant after acquiring that negative value the right one is available. I am almost sure that this is a thread race problem caused by my bad GUI/logic thread architecture, however, I noticed that if I remove this workaround that I made to the parent JPanel, the problem disappears.

I already tried adding a synchronized block while doing the value assignment, I did jlabel.verify() before but nothing helped. Unfortunately, I really need to keep the workaround I mentioned.

I would appreciate any guidance to solve this problem, thanks in advance.

Here is a screenshot:

https://i.sstatic.net/YAmTy.png

like image 852
DiegoSahagun Avatar asked Apr 24 '26 19:04

DiegoSahagun


1 Answers

The only way something like this can happen is if another process is changing jlabel between the time componentWidth variable was assigned and the time you are reading its value. A likely scenario is that jlabel's initialization is happening in a background thread, and was not complete when you assigned the componentWidth variable.

like image 106
Peter Avatar answered Apr 27 '26 07:04

Peter