Search code examples
javaarraysswing2djoptionpane

How could I print a 2D array in Java to a window in Swing / JOptionPane


I am really stumped. I cant find anywhere how to print this table as a window (like ShowMessageDialog) in JOptionPane just as it would print in the console the desired output

Here is my code:

import javax.swing.JOptionPane;
import java.util.*;
public class StarWars {

    public static void main(String[] args) {
        String [][] gridPlayer = new String [6][6];
        Scanner kb = new Scanner (System.in);

        String [] rows = {"A", "B", "C", "D", "E", "F", "G", "H"};

        for (int i = 0; i < 6; i++){
            for (int j = 0; j < 6; j++){

                gridPlayer[i][j] = " ~ ";
            }
        }
        System.out.print("  ");
        for (int i = 0; i < 6; i++){
            System.out.print(" " + rows[i] + " ");
        }
        System.out.println();
        for (int i = 0; i < 6; i++){
            System.out.print(" " + i);
            for (int j = 0; j < 6; j++){
                System.out.print(gridPlayer[i][j]);
            }

            System.out.println();

        }

        JOptionPane.showMessageDialog(null, for (int i));

    }

}

If anyone would know how to do this, your help would be throughougly appreciated.

P.S. StarWars class is present as it is a homework assignment ;)


Solution

  • There are many possible approaches, here is one: you can try this with a StringBuilder and put everything into a JLabel using html tags:

        StringBuilder sb = new StringBuilder();
        sb.append("<html>");
    
        String [][] gridPlayer = new String [6][6];
        Scanner kb = new Scanner (System.in);
    
        String [] rows = {"A", "B", "C", "D", "E", "F", "G", "H"};
    
        for (int i = 0; i < 6; i++){
            for (int j = 0; j < 6; j++){
    
                gridPlayer[i][j] = " ~ ";
            }
        }
        sb.append("&nbsp&nbsp");
        for (int i = 0; i < 6; i++){
            sb.append(" " + rows[i] + " ");
        }
        sb.append("<br>");
        for (int i = 0; i < 6; i++){
            sb.append(" " + i);
            for (int j = 0; j < 6; j++){
                sb.append(gridPlayer[i][j]);
            }
    
            sb.append("<br>");
    
        }
        sb.append("</html>");
    
        JOptionPane.showMessageDialog(null, new JLabel(sb.toString()));