Java Swing How to - Display multiple lines in JOptionPane








Question

We would like to know how to display multiple lines in JOptionPane.

Answer

import java.awt.GridLayout;
/*from w w  w .j  a  va  2 s  . c  o m*/
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main {
  private void displayGUI() {
    JOptionPane.showMessageDialog(null, getPanel(), "Output : ",
        JOptionPane.INFORMATION_MESSAGE);
  }

  private JPanel getPanel() {
    JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
    JLabel nameLabel = getLabel("Your Name : java2s.com" );
    JLabel ageLabel = getLabel("Your Age : 12");
    JLabel yearLabel = getLabel("Your Birth Year : 2004");
    panel.add(nameLabel);
    panel.add(ageLabel);
    panel.add(yearLabel);

    return panel;
  }

  private JLabel getLabel(String title) {
    return new JLabel(title);
  }

  public static void main(String[] args) {
    new Main().displayGUI();
  }
}