Search code examples
javaswingjoptionpane

How to you justify/ center text in a showOptionDialog


Simple question related to centering text in a JOptionPane.showOptionDialog;

I tried using the method for a regular JOptionPane using JLabels but that method did not work as the JOptionPane.showOptionDialog method overrides the input text.

JLabel warning = new JLabel()
int x = JOptionPane.showOptionDialog(warning,"I want this text \n to be centered","Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,null,finishedOptions, finishedOptions[0]);
warning.setHorizontalAlignment(SwingConstants.CENTER);

Solution

  • You can use HTML for the message body, for example:

    String msg = "<html><center><b>I want this text</b></center><center>to be "
               + "<font color=blue>centered</font></center></html>";
    JOptionPane.showMessageDialog(null, msg, "Confirm", JOptionPane.QUESTION_MESSAGE);
    

    This message box above would look something like:

    enter image description here