I'm creating a Tic Tac Toe GUI based game in Java and am struggling with using 2D arrays with JOptionPane
. So far I have been able to create the buttons to choose from:
import java.awt.GridLayout;
import javax.swing.*;
public class YourHEad {
public static void main(String[] args) {
JFrame frame = new JFrame("GridLayout Test");
frame.setLayout(new GridLayout(4, 4));
StringBuilder sb = new StringBuilder();
sb.append("<html>");
String[][] seats = new String [4][4];
String alpha = "ABCD";
for (int i=0; i<4; i++){
String letter = Character.toString(alpha.charAt(i));
for (int j=0; j<4; j++){
String number = Integer.toString(j+1);
seats [i][j]=letter+number+" ";
}
}
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
frame.add(new JButton(seats[i][j]));
}
}
frame.pack();
frame.setVisible(true);
if(new JButton(seats[0][0]).getModel().isPressed()){
System.out.println("the button is pressed");
}
}}
As you can see from the final lines of code, I am trying to work out how to tell when the button is pressed, so that if for example, the user clicks on 'A1', (hence 0,0), then the program can output text (which I will change to be in the JOptionPane format).
Hope I've explained it okay.
Hope, This will help
public class YourHEad
{
public static void main(String[] args)
{
final JFrame frame = new JFrame("GridLayout Test");
frame.setLayout(new GridLayout(4, 4));
StringBuilder sb = new StringBuilder();
sb.append("<html>");
String[][] seats = new String [4][4];
String alpha = "ABCD";
for (int i=0; i<4; i++){
String letter = Character.toString(alpha.charAt(i));
for (int j=0; j<4; j++){
String number = Integer.toString(j+1);
seats [i][j]=letter+number+" ";
}
}
for (int i = 0; i < 4; i++){
for (int j = 0; j < 4; j++){
JButton button= new JButton(seats[i][j]);
button.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(frame, ((JButton)(e.getSource())).getText()+" is Pressed");
}
});
frame.add(button);
}
}
frame.pack();
frame.setVisible(true);
}
}