Search code examples
javaswingfontsjoptionpane

Setting font in JOptionPane without using HTML


I tried this: Code Zip

Sorry for the inconvenience but I could not attach the whole code (though it's not too big) and could not provide .java extension link so you have to get the zip and it open in html where code is with syntax highlighting.

I read these:

But I don't want to use HTML.

Code

public static void main(String argv[]) {
    JFrame jf;
    jf = new JFrame();
    JPanel jp = new JPanel();
    jf.setBounds(100, 100, 530, 350);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.getContentPane().setLayout(null);
    jp.setFont(new Font("Algerian", Font.ITALIC, 11));
    jf.add(jp);
    String message = "Hello World!”;
    JOptionPane jop;
    jop = new JOptionPane();
    Object[] obj = { UIManager.put("Panel.font",new Font("Algerian", Font.ITALIC, 11)) , message };
    JOptionPane.showMessageDialog(jp,obj,"Dialog",JOptionPane.NO_OPTION);
  }

Solution

  • This MCVE shows one label in 3 option panes with 3 different variants of the same (default) font. It is simply a matter of passing the option pane a component that has the font set, as opposed to a string or a generic object.

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;
    
    public class FontInOptionPane {
    
        FontInOptionPane() {
            JLabel l = new JLabel();
            Font f = l.getFont();
            l.setText(f.toString());
    
            JOptionPane.showMessageDialog(null, l);
    
            f = f.deriveFont(Font.ITALIC);
            l.setText(f.toString());
            l.setFont(f);
            JOptionPane.showMessageDialog(null, l);
    
            f = f.deriveFont(50f);
            l.setText(f.toString());
            l.setFont(f);
            JOptionPane.showMessageDialog(null, l);
        }
    
        public static void main(String[] args) {
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    new FontInOptionPane();
                }
            };
            SwingUtilities.invokeLater(r);
        }
    }