Actually my problem is, I need to display multiple line of text in JButton.
I know, I can use the html tag <br> for the new line, but it is not suitable for my application.
I tried one more way by using JTextArea(there we can set the LineWrap and WrapStyleWord) that is, I created a JTextArea and added that textarea to the JButtons, but this is also not suitable for my application, because the look of the JButton is very important in our application and it is lost when I added the JTextArea to the buttons.
But I can add a JLabel to the buttons without losing the look of the button in my application.
So I need to set multiLine on the JLabel.
The text (that is the string value) that is displaying on the JLabel will get at runtime, so I need to insert a linebreak(either with <br> or \n) in the string value at appropriate position.
For that purpose (appropriate position in the string), I set font for the JLabel and the get the FontMetrics on the font and then use the method getCharWidth('c') on the FontMetrics to get the character width and then I use the width of the label and then divide (label width/character width)to get the number of characters that have to be displayed on one line, it is working only for the character 'c', (that is I get the width of the character 'c'), but the string can contain many characters other than 'c'. Is there any other way to get the character width or any way to set the character width for a font(that means I need to set a constant value to any character), so that I can use the above logic to get the number of characters in one line.
Sorry. I can use the <html> tags. But the problem is I can not get the correct position to insert the <br> or \n in the string.
int noOfLines=messagelabel.getWidth() / messagelabel.getFontMetrics(font).charWidth('c');
From the above code I can get the no Of Characters in one line and then insert the line beark in the string.
The problem is, it is working correctly when the string contains only the character 'c', but actually the string can contain other characters also.
So I need to set character width for all the characters that is displaying on the label.
Obviously, if the display text is generated at runtime, there is no way, you can specify before hand, where the breaks should happen. So the easier approach would be the above. Of course, in this example, the breaks would be defined by the width of the button. If you override JButton#setPreferredSize() you can control that too. Else leave it to your layout manager to figure out the dimensions.
Notice I have defined the width of the table. You will probably want to play around with that to get it right in your application.
If your button has a top limit to which it can grow (because of other components), just take out the table width.
Of course, this is not the only way to do it.
Now you tell us, how else it can be done