Search code examples
javaswingmultidimensional-arrayjoptionpane

Java multidimensional Array shown in OptionPane


I can't find a way how to get to get a JOptionPane show the multidimensional array.

This is my first attempt.

public static void main (String [] args)
{
    int[][] numbers = new int[5][5];

    int rows = 5;
    int columns = 5;

    numbers[0][0] = 30;
    numbers[0][1] = 29;
    numbers[0][2] = 28;
    numbers[0][3] = 27;
    numbers[0][4] = 26;

    numbers[1][0] = 26;
    numbers[1][2] = 25;
    numbers[1][2] = 24;
    numbers[1][3] = 23;
    numbers[1][4] = 22;

    int x, y;

    for (x = 0;  x < rows; x++)
    {
        for (y = 0; y < columns; y++)
        {
            System.out.print(numbers[x][y] + " ");
        }
        System.out.println("");

    }
    JOptionPane.showMessageDialog(null, numbers,"Arrays",JOptionPane.INFORMATION_MESSAGE);
    System.exit(0);
}

This is the JOptionPane output

https://www.dropbox.com/s/hfyjsgeaimpr2dh/JOptionPane%20output.PNG

As you can see something is wrong.

The console output is looks like this.

https://www.dropbox.com/s/ac0a65kttdora27/Console%20output.PNG

And what I want is that you see the console output is shown in the JOptionPane.

Thanks in advance!


Solution

  • You could use a StringBuilder in the same way you are printing to the console :

    public static void main (String [] args)
    {
        int[][] numbers = new int[5][5];
    
        int rows = 5;
        int columns = 5;
    
        numbers[0][0] = 30;
        numbers[0][1] = 29;
        numbers[0][2] = 28;
        numbers[0][3] = 27;
        numbers[0][4] = 26;
    
        numbers[1][0] = 26;
        numbers[1][2] = 25;
        numbers[1][2] = 24;
        numbers[1][3] = 23;
        numbers[1][4] = 22;
    
        int x, y;
        StringBuilder builder = new StringBuilder();
        for (x = 0;  x < rows; x++)
        {
            for (y = 0; y < columns; y++)
            {
                builder.append(numbers[x][y] + " ");
            }
            builder.append("\n");
        }
        JOptionPane.showMessageDialog(null, builder,"Arrays",JOptionPane.INFORMATION_MESSAGE);
        System.exit(0);
    }