Search code examples
javajoptionpane

How to format a table in JOptionpane?


So, I have a program which searches through a file to find desired information that the user wants, and I am trying to output it in a nice table in JOptionPane to make it easier to read, but I keep getting something like this:

http://i.imgur.com/tanOzDh.png

I would like the lines to line up accordingly and be formatted properly, here is the code for that particular message:

 String message=String.format("%-10s|%7s|%14s|%13s|%22s", element,symbol,atomicNumber,atomicMass,valence);
JOptionPane.showMessageDialog(null, "Name      |Symbol |Atomic Number |Atomic Mass  |# of Valence Electrons  \n _________________________________________________________________ \n " + message);

Can't seem to figure out what i'm doing wrong here, I used the exact same format code in a different assignment in which it only utilized the terminal and it worked fine, but now that I'm trying to use it in JOptionPane it's not formatting properly.

Any ideas on how to fix this or make it work?


Solution

  • Try JTable instead:

    Object[][] rows = {
        {element,symbol,atomicNumber,atomicMass,valence}
    };
    Object[] cols = {
        "Name","Symbol","Atomic Number","Atomic Mass", "# of Valence Electrons"
    };
    JTable table = new JTable(rows, cols);
    JOptionPane.showMessageDialog(null, new JScrollPane(table));