Reputation: 3
I just started learning Java a couple weeks ago so i'm fairly new. I'm currently working on a TicTacToe game and I was just about finished but instead of having my board display itself as a System.out.print I would like it to be displayed on a JOptionPane message instead to improve it aesthetically. However my board is completely made with loops and i'm not sure how I can display that on a JOptionPane :( I've tried researching similar situations online but I everything I find is quite confusing or doesn't seem to apply to the kind of statements i'm printing. If anyone could help me out it would be much appreciated.
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// This is the column
System.out.print(" ");
for (int i = 0; i < numCol; i++)
System.out.print(i + " ");
System.out.print('\n');
System.out.println(); // blank line after the header
// The write the table
for (int i = 0; i < numRow; i++) {
System.out.print(i + " ");
for (int j = 0; j < numCol; j++) {
if (j != 0)
System.out.print("|");
System.out.print(" " + brd[i][j] + " ");
}
System.out.println();
if (i != (numRow - 1)) {
// separator line
System.out.print(" ");
for (int j = 0; j < numCol; j++) {
if (j != 0)
System.out.print("+");
System.out.print("---");
}
System.out.println();
}
}
System.out.println();
}
Upvotes: 0
Views: 1039
Reputation: 2920
Like MadProgrammer mentioned above, JOptionPane isn't the best way to go about displaying something like this. But if you really want to use JOptionPane, do something like this:
Create a String
object holding an empty string at the top...
String str = "";
And replace each of your System.out.print
statements with str +=
, followed by whatever was previously contained within the parentheses. For example:
str += " ";
for (int i = 0; i < numCol; i++)
str += i + " ";
str += "\n";
Replace your System.out.println
statements with str += "\n";
.
Finally, at the end you can use JOptionPane
to display the string.
JOptionPane.showMessageDialog(null,str);
There are going to be some alignment issues that you'll have to solve on your own since JOptionPane does not place the characters in a gridded alignment like consoles do (as far as I know, at least), but this should give you a good idea of how to do it.
Upvotes: 1