0

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);
Andrew Thompson
  • 166,747
  • 40
  • 210
  • 420
zak Smiths
  • 35
  • 4

1 Answers1

3

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

DevilsHnd
  • 7,644
  • 2
  • 17
  • 21
  • So I’m still learning Java, how is it that html is allowed to be used this way, if you know? – LuckyBandit74 Aug 01 '21 at 06:14
  • 1
    [Read this tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/html.html). :) – DevilsHnd Aug 01 '21 at 06:26
  • The [HTML width can be set using CSS](https://stackoverflow.com/a/7861833/418556) (ATM the HTML is just wide enough to display the text). Remove `
    ` for the same effect.
    – Andrew Thompson Oct 31 '21 at 10:23