I’m having trouble generating an array of buttons for a clone of battleship for my class, and can’t seem to figure out why it is not working. Any advice would help… I have the main class creating the jFrame, then the grid class, more specifically the generator method builds the array of buttons.
import java.awt.*;
import javax.swing.*;
public class warship {
/**
* @param args
*/
public static void main(String[] args) {
JFrame gui = new JFrame();
gui.setSize(700, 350);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setLayout(new FlowLayout());
grid oceanGrid = new grid();
oceanGrid.Generator();
gui.add(oceanGrid);
gui.setVisible(true);
}
}
grid.java
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
@SuppressWarnings("serial")
public class grid extends JPanel{
private static int rows = 7;
private static int col = 10;
public void Generator(){
ImageIcon wIcon = new ImageIcon ("H:\\workspace\\Warship\\src\\images\\water.jpg");
JPanel jPan1 = new JPanel();
jPan1.setLayout((LayoutManager) new GridLayout(rows,col,1,1));
jPan1.setSize(350,350);
//Set Border
TitledBorder bdr = javax.swing.BorderFactory.createTitledBorder(null, "Targeting Grid",
javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
javax.swing.border.TitledBorder.DEFAULT_POSITION,
new java.awt.Font("Arial", 0, 16));
bdr.setTitleColor(java.awt.Color.RED);
jPan1.setLayout((LayoutManager) new GridLayout(rows,col,1,1));
jPan1.setBorder(bdr);
//Creates the array of buttons
JButton b[]=new JButton[rows*col];
for (int i = 0, j= rows*col; i < j; i++){
b[i] = new JButton(wIcon);
b[i].setSize(20, 20);
b[i].setMaximumSize(new Dimension(20,20));
b[i].setPreferredSize(new Dimension(20,20));
System.out.println("loop test " + i);
jPan1.add(b[i]);
}
}
}
I think this is the mistake you are making:
Your class grid extend
JPanel, but you declare and initialize anotherJPanelin which you add your buttons. So you are not actually adding the buttons to your grid but to another panel you do not use.The solution is to remove this line
and to replace all occurences of
jPan1withthisThis way you will be adding the buttons to your grid.