Search code examples
javastringswingstring-formattingjoptionpane

JOptionPange: Can't print String.format table even with monospaced font


I'm trying to display a table inside JOptionPane. However the column indents are off. I tried to change the font to monospaced, but it didn't work.

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

public class Test {
    public static void main(String[] args) {
        String[] names = {"tom","john", "vincent", "dan"};
        String[] colors = {"red", "orange", "green", "blue"};
        String[] pets = {"dog", "crocodile", "monkey", "parrot"};
        int[] ages = {23, 5454, 1, 6565, 87};

        String s = "";
        for (int i = 0; i < 4; i++) {
            s += String.format("%-20s%-20s%-20s%-20d%n",
                names[i], colors[i], pets[i], ages[i]);
        }

        System.out.println(s);

        JOptionPane.showMessageDialog(null, s);

        JLabel label = new JLabel(s);
        label.setFont(new Font("Monospaced", Font.BOLD, 18));
        JOptionPane.showMessageDialog(null,label,"ERROR",JOptionPane.WARNING_MESSAGE);
   }
}

the console output looks like this:

enter image description here

The first window looks like this (as can be seen the columns are off):

enter image description here

The second window looks like this:

enter image description here

How do I get the table be printed just the way it's printed in console?


Solution

  • You can use a JTextArea:

    import javax.swing.*;
    import java.awt.*;
    
    public class Test5
    {
        public static void main(String[] args)
        {
            String[] names = {"tom","john", "vincent", "dan"};
            String[] colors = {"red", "orange", "green", "blue"};
            String[] pets = {"dog", "crocodile", "monkey", "parrot"};
            int[] ages = {23, 5454, 1, 6565, 87};
    
            StringBuilder s = new StringBuilder();
    
            for (int i = 0; i < 4; i++)
            {
                if (i > 0)
                    s.append("\n");
    
                s.append(String.format("%-20s%-20s%-20s%-20d", names[i], colors[i], pets[i], ages[i]));
            }
    
            JTextArea label = new JTextArea(s.toString());
            label.setOpaque( false );
            label.setEditable( false );
            label.setFont(new Font("Monospaced", Font.BOLD, 12));
    
           JOptionPane.showMessageDialog(null,label,"ERROR",JOptionPane.WARNING_MESSAGE);
       }
    }