Search code examples
javaarraysswingfunctionjoptionpane

Printing 2d array in JOptionPane


I'm try to print random 1d and 2d arrays in JOptionPane. but it comes out like this:

enter image description here

is there a way to format it to line up like this:

enter image description here

the row and col are also random.

another thing, is there a way to use only one function to print for 1d and 2d arrays? and if not can the 2d function use the 1st one? This is for school homework. we are not allowed to mess with JOptionPane. It's supposed to stay like this: JOptionPane.showMessageDialog(null, String);

 public static String printMatrix(int[] m) {
    String result = "";
    for (int i = 0; i < m.length; i++) {
      result += m[i] + "                ";
    }
    return result;
  }


  public static String printMatrix2D(int[][] m) {
    String result = "";
    for (int i = 0; i < m.length; i++) {
      for (int j = 0; j < m[i].length; j++) {
        result += m[i][j] + "                ";
      }
      result += "\n";
    }
    return result;
  }

Solution

  • If you want your numbers to be placed as if they were in a table, you need to create a JPanel with a GridLayout with some hgap and vgap. This works for 4 digit and 5 digit numbers or any amount of digit numbers.

    For example:

    import java.awt.Color;
    import java.awt.GridLayout;
    
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class JOptionPanePrintingInColumns {
    
        private JPanel pane;
        private String[] oneDArray = new String[] {"1000", "10000", "99999", "23000", "100000"};
        private String[][] twoDArray = new String[][] {
            {"1000", "10000", "99999", "23000", "100000"},
            {"1000", "10000", "99999", "23000", "100000"}, 
            {"1000", "10000", "99999", "23000", "100000"},
            {"1000", "10000", "99999", "23000", "100000"}, 
            {"1000", "10000", "99999", "23000", "100000"}
        };
        
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new JOptionPanePrintingInColumns()::createAndShowGui);
        }
        
        private void createAndShowGui() {
            //For the 1D Array
            pane = new JPanel();
            pane.setLayout(new GridLayout(0, 5, 50, 10));
            for (int i = 0; i < oneDArray.length; i++) {
                JLabel label = new JLabel(oneDArray[i]);
                label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                pane.add(label);
            }
            JOptionPane.showMessageDialog(new JFrame(), pane);
            
            //For the 2D array
            pane = new JPanel();
            pane.setLayout(new GridLayout(0, 5, 50, 10));
            for (int i = 0; i < twoDArray.length; i++) {
                for (int j = 0; j < twoDArray[i].length; j++) {
                    JLabel label = new JLabel(twoDArray[i][j]);
                    label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                    pane.add(label);
                }
            }
            JOptionPane.showMessageDialog(new JFrame(), pane);
        }
    }
    

    Which will produce something like this:

    enter image description here enter image description here

    And because we can see the borders, we can notice that each label is the same size as the largest one (i.e. the last in each row) this is why it works for larger or shorter numbers.

    You might have noticed that I used this line:

    pane.setLayout(new GridLayout(0, 5, 50, 10));
    

    But what does the 0 means? It means "create as many rows as needed of 5 columns each", so this works either for 1D or 2D arrays, just changing the way you get the data from each array.


    Edit:

    but i forgot to mention this is for school homework. we are not allowed to mess with JOptionPane. it's supposed to stay like this: JOptionPane.showMessageDialog(null, String);

    You could use HTML tags inside the String to convert it to a table, then place each number inside the cells of it, using some cellspacing to provide more or less space (play with it):

    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    public class JOptionPanePrintingInColumns {
    
        private JPanel pane;
        private String[] oneDArray = new String[] {"1000", "10000", "99999", "23000", "100000"};
        private String[][] twoDArray = new String[][] {
            {"1000", "10000", "99999", "23000", "100000"},
            {"100", "180000", "9999", "3000", "1090000"}, 
            {"111000", "1220000", "9955999", "230100", "1000200"},
            {"10010", "1005400", "9999954", "9", "123"}, 
            {"100430", "1000054", "999", "23123000", "123456789"}
        };
        
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new JOptionPanePrintingInColumns()::createAndShowGui);
        }
        
        private void createAndShowGui() {
            String output;
            StringBuilder sb = new StringBuilder();
            sb.append("<html><table><tr>");
            for (int i = 0; i < oneDArray.length; i++) {
                sb.append("<td>").append(oneDArray[i]).append("</td>");
            }
            sb.append("</tr></table></html>");
            output = sb.toString();
            JOptionPane.showMessageDialog(new JFrame(), output);
            
            sb = new StringBuilder();
            sb.append("<html><table cellspacing=10>");
            for (int i = 0; i < twoDArray.length; i++) {
                sb.append("<tr>");
                for (int j = 0; j < twoDArray.length; j++) {
                    sb.append("<td>").append(twoDArray[i][j]).append("</td>");
                }
            }
            sb.append("</tr></table></html>");
            output = sb.toString();
            JOptionPane.showMessageDialog(new JFrame(), output);
        }
    }
    

    enter image description here