Search code examples
javaswingfontsjtextfieldjoptionpane

How to change the font in JOptionPane.showInputDialog JTextField?


I need to know the ui manager property that needs to be set to make the font changed for the JTextField in JOptionPane.showInputDialog window.


Solution

  • One trick is to make a confirmation dialog look like an input dialog. Note that this example still behaves differently to a standard input dialog in that the input field is not selected by default. For that, I have always found the tips in this article on Dialog Focus to be invaluable.

    The following shows a standard input dialog compared to the confirm dialog using a large font.

    Standard input dialog Big input dialog

    import java.awt.*;
    import javax.swing.*;
    
    class BigInputOptionPane {
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
    
                @Override
                public void run() {
                    String s = JOptionPane.showInputDialog(null);
                    if (s!=null) {
                        System.out.println("User chose: " + s);
                    } else {
                        System.out.println("User did not chose an option!");
                    }
    
                    JTextField tf = new JTextField(8);
                    tf.setFont(tf.getFont().deriveFont(26f));
                    int result = JOptionPane.showConfirmDialog(
                            null, tf, "Input", 
                            JOptionPane.OK_CANCEL_OPTION);
                    if (result==JOptionPane.OK_OPTION) {
                        System.out.println("User chose: " + tf.getText());
                    } else {
                        System.out.println("User did not chose an option!");
                    }
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }