How do you split a long line into multiple lines so it will fit in a button?
Most other answers have used HTML but they hard code the string into the line making it impossible to split the line on the fly as the button is being created.
Edited: I added a method to do this after researching, asking and not getting a good answer on how to do this dynamically.
Please share your methods
解决方案
This is a sample method that splits a line dynamically using HTML tags
/**
* This method divides the button text into lines by applying
* html tags. Only way to get multiple lines on a JButton.
* @param string
* @return
*/
private String wrapText(String string){
//Return string initialized with opening html tag
String returnString="";
//Get max width of text line
int maxLineWidth = new ImageIcon("Images/buttonBackground.png").getIconWidth()-10;
//Create font metrics
FontMetrics metrics = this.getFontMetrics(new Font("Helvetica Neue", Font.PLAIN, 15));
//Current line width
int lineWidth=0;
//Iterate over string
StringTokenizer tokenizer = new StringTokenizer(string," ");
while (tokenizer.hasMoreElements()) {
String word = (String) tokenizer.nextElement();
int stringWidth = metrics.stringWidth(word);
//If word will cause a spill over max line width
if (stringWidth+lineWidth>=maxLineWidth) {
//Add a new line, add a break tag and add the new word
returnString=(returnString+"
"+word);
//Reset line width
lineWidth=0;
}else{
//No spill, so just add to current string
returnString=(returnString+" "+word);
}
//Increase the width of the line
lineWidth+=stringWidth;
}
//Close html tag
returnString=(returnString+"");
//Return the string
return returnString;
}