如何将Java中的2D数组打印到Swing / JOptionPane中的窗口

我真的很沮丧.我在任何地方都找不到如何在JOptionPane中将该表打印为窗口(如ShowMessageDialog)的方法,就像在控制台the desired output中打印一样

这是我的代码:

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));

    }

}

如果有人知道如何做,将非常感谢您的帮助.

附言存在StarWars类,因为它是一项家庭作业;)

解决方法:

有很多可能的方法,这是一种:您可以使用StringBuilder尝试此方法,然后使用html标签将所有内容放入JLabel中:

    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()));
上一篇:SVM之SMO最小序列


下一篇:java-如何在单个消息框中显示循环的所有迭代?