How to resize a label automatically?
Hi;
I have a form and a label in it. That label should resize itself to fit the text in it. And after this resizing my code resize the form so that label fits in the form. The problem is, I dont know how to resize the label. (I dont mean label.setSize())
I can try it with taking length of the text inside and calculate the length. But some characters are bigger than others. (for example: I and M) So there can be mistakes. Is label supporting such a thing?
There is a way to caluculate the pixel length of a string, I don't remember how off the top of my head, I'm pretty sure it's all in awt. You could also use a monospaced font, that might help out some.
How else did you want to resize it if you don't want to use setSize or setBounds? Are you using a layout manager (use setPreferredSize here)?
srry I mean I can use them but I thought there can be a method or a property like vb.net. Same thing is in VB.Net. There you can make the autosize property true and label will resize itself if you put some text in it. For example if label has a text of "Hi!" it will be shorter itself but if you write label.setText("How are you?") it's width will increase automatically.
Sorry about my english. It is hard to explain such things in a foreign language... (some times it is hard to explain in motherlanguage too :D)
I don't know what you are talking about. As far as I can tell, the default behaviour for a JLabel is to resize itself to fit the text inside it. That's certainly how mine behave. So if yours don't do that then remove some code until they do.
The exception is if they don't have enough room to expand because they're taking up the whole width of the panel they are in. You asked how to resize the form so that there will be room? I don't think that's a good idea. Windows that change their size are an annoying UI feature, which is why you rarely see them. And what happens when your form resizes itself to be three times as wide as your screen?
However you might consider in future posting Swing questions in the Swing forum so you don't have to take advice from mediocre Swing programmers like me.