我无法为我的班级的战舰克隆生成一系列按钮,并且似乎无法弄清楚为什么它不起作用。任何建议都会有所帮助......我让主类创建 jFrame,然后是网格类,更具体地说,生成器方法构建按钮数组。
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);
}
}
网格.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]);
}
}
}