java按钮显示多行,如何在不知道该行的情况下将JButton(JAVA)文本拆分为多行UNTIL CREATION...

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值