如何在不知道行的情况下将JButton(JAVA)文本拆分为多行UNTIL CREATION [英] How to split a JButton (JAVA) text into multiple lines without knowing the line UNTIL CREATION
本文介绍了如何在不知道行的情况下将JButton(JAVA)文本拆分为多行UNTIL CREATION的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将一长行分成多行,使其适合一个按钮?
How do you split a long line into multiple lines so it will fit in a button?
大多数其他答案都使用HTML,但是它们将字符串硬编码到行中,因此无法在创建按钮时即时拆分行.
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.
请分享您的方法
推荐答案
这是一个使用HTML标签动态分割行的示例方法
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="<html>";
//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+"<br>"+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+"<html>");
//Return the string
return returnString;
}
这篇关于如何在不知道行的情况下将JButton(JAVA)文本拆分为多行UNTIL CREATION的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文