I am trying to write a Battleship program using Java Swing and currently I have a class that makes two grids. I am trying to find out the location of which button was clicked so I can use this later to place shots etc... Unfortunately I am having a fair bit of trouble with this.
I have got the object to print out every thing that is in it by using the actionPerformed method but I only want the grid[x][y]. How do I go about this?
Thanks in advance for any help.
package testapp;
/**
*
* @author Craig
*/
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.Border;
public class menu extends JPanel implements ActionListener{
JButton[][] grid;
TextField text = new TextField(20);
public menu(int width, int length) {
Border playerBorder = BorderFactory.createTitledBorder("Player");
Border comBorder = BorderFactory.createTitledBorder("Com");
JPanel player = new JPanel();
player.setBorder(playerBorder);// set border round player grid
player.setLayout(new GridLayout(4,4));
grid=new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton(); //creates new button
player.add(grid[x][y]); //adds button to grid
grid[x][y].setBackground(Color.BLUE);//sets grid background colour
grid[x][y].setPreferredSize(new Dimension(40, 40));//sets each grid buttons dimensions
add(text);
grid[x][y].addActionListener(this);
}
}
JPanel com = new JPanel();
com.setBorder(comBorder);// set border round com grid
com.setLayout(new GridLayout(4,4));
grid=new JButton[width][length]; //allocate the size of grid
for(int y=0; y<length; y++){
for(int x=0; x<width; x++){
grid[x][y]=new JButton(); //creates new button
com.add(grid[x][y]); //adds button to grid
grid[x][y].setBackground(Color.BLUE);//sets grid background colour
grid[x][y].setPreferredSize(new Dimension(40, 40));//sets each grid buttons dimensions
}
}
//this.setLayout(new FlowLayout());
this.add(player);
this.add(com);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton) {
JButton btn = (JButton)source;
text.setText("IN THE BOX ");
}
}
}