How do you set the font of the text displayed in a JOptionPane?

John Zukowski

A JOptionPane is made up of lots of other component types. If you'd like to change the font of the text displayed in a JOptionPane, you have to change the font of the appropriately related component. For instance, to change the text of the text message, this goes into a JLabel, so you would change the font with UIManager.put("Label.font", newFont);. You can do the same with buttons UIManager.put("Button.font", newFont); or any of the other components that go within the JOptionPane. The following demonstrates this by changing the font for the label:


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SamplePopup {
  public static void main(String args[]) {

    JFrame frame = new JFrame("Sample Popup");
    JButton button = new JButton ("Ask");
    Font f = new Font("Monospaced", Font.BOLD, 24);
    UIManager.put("Label.font", f);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        Component source = (Component)actionEvent.getSource();
        Object response = JOptionPane.showInputDialog(
          source, 
          "Where would you like to go to lunch?",
          "Select a Destination", 
          JOptionPane.QUESTION_MESSAGE,
          null,
          new String[] {
            "Burger King", 
            "McDonalds", 
            "Pizza Hut", 
            "Taco Bell", 
            "Wendy's"},
          "McDonalds");
        System.out.println ("Response: " + response);
      }
    };
    button.addActionListener(actionListener);
    Container contentPane = frame.getContentPane();
    contentPane.add(button, BorderLayout.SOUTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact