user2477252
user2477252

Reputation: 23

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.

Upvotes: 1

Views: 15648

Answers (5)

Here's what works for me in August 2018 using Java 1.8.0_181 to make the font size larger and thus more readable on my 4K laptop monitor. I call it near the top of main prior to invoking dialogs such as the the following:

String menuChoice = JOptionPane.showInputDialog(null, "some prompt", "Menu", JOptionPane.INFORMATION_MESSAGE);

It's very close to previous answers but differs slightly because it includes settings I did not see in those prior responses:

/**
 * Changes the font size used in JOptionPane.showInputDialogs to make them more ADA
 * section 508 compliant by making the text size larger,
 * which is very nice for older people and anyone else with vision problems.
 */
private static void makeDialogsEasierToSee() {      

    // This next one is very strange; but, without it,
    // any subsequent attempt to set InternalFrame.titleFont will
    // be ignored, so resist the temptation to remove it.
    JDialog.setDefaultLookAndFeelDecorated(true);

    Font normalFont = new Font(Font.MONOSPACED, Font.PLAIN, 24);
    Font boldFont = normalFont.deriveFont(Font.BOLD);

    UIManager.put("OptionPane.font", normalFont);
    UIManager.put("OptionPane.messageFont", normalFont);
    UIManager.put("OptionPane.buttonFont", normalFont);
    UIManager.put("TextField.font", normalFont);
    UIManager.put("InternalFrame.titleFont", boldFont);
}

Upvotes: 0

WesternGun
WesternGun

Reputation: 12807

This is the way we shall use:

UIManager.put("OptionPane.messageFont", new Font("Arial", Font.BOLD, 14));
UIManager.put("OptionPane.buttonFont", new Font("Arial", Font.PLAIN, 12));

Just remember to set it before any JOptionPane dialog appears. I just put it in the first line of the main method.

To see why I do this, the DOC of UIManager is always useful.

Defaults

UIManager manages three sets of UIDefaults. In order, they are:

Developer defaults. With few exceptions Swing does not alter the developer defaults; these are intended to be modified and used by the developer.

Look and feel defaults. The look and feel defaults are supplied by the look and feel at the time it is installed as the current look and feel (setLookAndFeel() is invoked). The look and feel defaults can be obtained using the getLookAndFeelDefaults() method.

System defaults. The system defaults are provided by Swing. Invoking any of the various get methods results in checking each of the defaults, in order, returning the first non-null value. For example, invoking UIManager.getString("Table.foreground") results in first checking developer defaults. If the developer defaults contain a value for "Table.foreground" it is returned, otherwise the look and feel defaults are checked, followed by the system defaults. It's important to note that getDefaults returns a custom instance of UIDefaults with this resolution logic built into it. For example, UIManager.getDefaults().getString("Table.foreground") is equivalent to UIManager.getString("Table.foreground"). Both resolve using the algorithm just described. In many places the documentation uses the word defaults to refer to the custom instance of UIDefaults with the resolution logic as previously described.

So, we should change first the developer defaults. And the method UIManager.put(Object key, Object value) is the method to use.

public static Object put(Object key, Object value)

Stores an object in the developer defaults. This is a cover method for getDefaults().put(key, value). This only affects the developer defaults, not the system or look and feel defaults.

Parameters:

key - an Object specifying the retrieval key

value - the Object to store; refer to UIDefaults for details on how null is handled

Returns: the Object returned by UIDefaults.put(java.lang.Object, java.lang.Object)

Throws:

NullPointerException - if key is null

This is exactly what I am looking for: no extra panels, no more trouble of overriding the default UI of JOptionPane.

A complete list of names of attributes in JOptionPane is here:

http://www.java2s.com/Tutorial/Java/0240__Swing/CustomizingaJOptionPaneLookandFeel.htm

Property String                                 Object Type

OptionPane.actionMap                            ActionMap
OptionPane.background                           Color
OptionPane.border                               Border
OptionPane.buttonAreaBorder                     Border
OptionPane.buttonClickThreshhold                Integer
OptionPane.buttonFont                           Font
OptionPane.buttonOrientation                    Integer
OptionPane.buttonPadding                        Integer
OptionPane.cancelButtonMnemonic                 String
OptionPane.cancelButtonText                     String
OptionPane.cancelIcon                           Icon
OptionPane.errorDialog.border.background        Color
OptionPane.errorDialog.titlePane.background     Color
OptionPane.errorDialog.titlePane.foreground     Color
OptionPane.errorDialog.titlePane.shadow         Color
OptionPane.errorIcon                            Icon
OptionPane.errorSound                           String
OptionPane.font                                 Font
OptionPane.foreground                           Color
OptionPane.informationIcon                      Icon
OptionPane.informationSound                     String
OptionPane.inputDialogTitle                     String
OptionPane.isYesLast                            Boolean
OptionPane.messageAnchor                        Integer
OptionPane.messageAreaBorder                    Border
OptionPane.messageFont                          Font
OptionPane.messageForeground                    Color
OptionPane.messageDialogTitle                   String
OptionPane.minimumSize                          Dimension
OptionPane.noButtonMnemonic                     String
OptionPane.noButtonText                         String
OptionPane.noIcon                               Icon
OptionPane.okButtonMnemonic                     String
OptionPane.okButtonText                         String
OptionPane.okIcon                               Icon
OptionPane.questionDialog.border.background     Color
OptionPane.questionDialog.titlePane.background  Color
OptionPane.questionDialog.titlePane.foreground  Color
OptionPane.questionDialog.titlePane.shadow      Color
OptionPane.questionIcon                         Icon
OptionPane.questionSound                        String
OptionPane.sameSizeButtons                      Boolean
OptionPane.separatorPadding                     Integer
OptionPane.setButtonMargin                      Boolean
OptionPane.titleText                            String
OptionPane.warningDialog.border.background      Color
OptionPane.warningDialog.titlePane.background   Color
OptionPane.warningDialog.titlePane.foreground   Color
OptionPane.warningDialog.titlePane.shadow       Color
OptionPane.warningIcon                          Icon
OptionPane.warningSound                         String
OptionPane.windowBindings                       Object[ ]
OptionPane.yesButtonMnemonic                    String
OptionPane.yesButtonText                        String
OptionPane.yesIcon                              Icon
OptionPaneUI                                    String

Upvotes: 2

Harry
Harry

Reputation: 51

This worked for me to change both the font of the text and buttons in JOptionPane:
Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 20);
UIManager.put("OptionPane.messageFont", font);
UIManager.put("OptionPane.buttonFont", font);

Upvotes: 4

MadProgrammer
MadProgrammer

Reputation: 347334

I believe you want TextField.font. This will return the font used by default for all JTextFields for the currently installed look and feel...

A better solution might be to supply your own JTextField, setup with the font you want to use.

For example...

(Sorry, updated, used wrong dialog :P)

enter image description here

import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestOptionPane09 {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JTextField field = new JTextField("Hello");
                field.setFont(field.getFont().deriveFont(Font.BOLD, 24));
                String[] options = {"Ok", "Cancel"};
                int result = JOptionPane.showOptionDialog(
                        null,
                        field,
                        "Help",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE,
                        null,
                        options,
                        0);
                switch (result) {
                    case 0:
                        System.out.println("Okay");
                        break;
                    case 1:
                        System.out.println("Cancel");
                        break;
                }
            }
        });
    }
}

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168845

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);
    }
}

Upvotes: 4

Related Questions