2013-01-02 30 views
2

請看看下面的代碼如何在JLabels中應用換行符?

JLabel menuItemTitle = new JLabel("How to Find Waist"); 
    JLabel menuItemDescription = new JLabel("Take the Neck measurement with your shoulders down and relaxed.\n Looking straight ahead rap the tape around the smallest point, below the Larynx, and sloping down slightly toward the front.\nTry a few spots to get the lowest number, and where it feels the most natural."); 

     JPanel northPanel = new JPanel(); 
     northPanel.setLayout(new FlowLayout(FlowLayout.CENTER)); 
     northPanel.add(menuItemTitle); 

     JPanel centerPanel = new JPanel(); 
     centerPanel.setLayout(new FlowLayout()); 
     centerPanel.add(menuItemDescription); 


     JDialog dialog = new JDialog(); 
     dialog.setLayout(new BorderLayout()); 
     dialog.add(northPanel,"North"); 
     dialog.add(centerPanel,"Center"); 

       dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       dialog.setLocationRelativeTo(null); 
       dialog.pack(); 
       dialog.setVisible(true); 

我已經添加了必需的轉義字符,但它不是打破行。我如何在JLabels中添加LineBreaks?我也嘗試了上面的HTML使用。但那也失敗了。請幫忙。

更新

HTML版本

menuItemDescription = new JLabel("<html>Take the Neck measurement with your shoulders down and relaxed.</br> Looking straight ahead rap the tape around the smallest point, below the Larynx, and sloping down slightly toward the front.</br>Try a few spots to get the lowest number, and where it feels the most natural.</html>"); 
+0

你能後的HTML版本中使用的HTML代碼,你的JLabel裏面,因爲這應該工作。 – Goibniu

+0

重複的:http://stackoverflow.com/questions/1090098/newline-in-jlabel –

+0

@Goibniu:好的。編輯 –

回答

5

您可以用這種方式

JLabel label = new JLabel("<html>Welcome to<br>Stackoverflow</html>"); 
+0

感謝您的答案Upendra :) –

+1

使用'style ='width:120px;''在自動換行的主體中。有關詳細信息和演示,請參閱[此答案](http://stackoverflow.com/questions/7861724/is-there-some-word-wrap-property-of-jlabel-exist/7861833#7861833)。 –