1

如何将一条长线分成多条线,使其适合按钮?

大多数其他答案都使用了 HTML,但他们将字符串硬编码到行中,使得在创建按钮时无法动态拆分行。

编辑:在研究、询问并没有得到关于如何动态执行此操作的好答案后,我添加了一种方法来执行此操作。

请分享您的方法

4

1 回答 1

2

这是一个使用 HTML 标签动态分割行的示例方法

/**
         * 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;
        }
于 2013-04-02T17:49:20.357 回答