Search code examples
javaswingfor-loopjbutton

JButton.setText() in a for loop java


I'm trying to get a two line text in a JButton

The text is suppose to display between and
also between /> and just like this but for some reason, it is not working in my for loop

  JButton title[] = new JButton[6];
  JButton button[] = new JButton[30];
  String[] titleText = {"World Religion", "New Title", "New Title", "New Title", "New Title", "New Title"};


  //
  for (int i=0; i<6; i++) {
     title[i] = new JButton();
     title[i].setText("<html> <br /> </html>"+titleText[i]);
     add(title[i]); 
  }

Solution

  • You need to put the text between the <html> and </html> tags as such:

    title[i].setText("<html><br/>" + titleText[i] + "</html>");

    The content inclosed between the tags <html></html> tells the button to interpret it as HTML content.