我无法为我的课程生成用于战舰克隆的按钮数组,并且似乎无法弄清楚为什么它不起作用。任何建议将有助于...我有主类创建jFrame,然后网格类,更具体地说,生成器方法构建的按钮数组。使用按钮阵列调试JFrames
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]);
}
}
}
什么具体不工作? – 2012-07-10 18:38:41
它没有显示由oceanGrid调用的jPanel的任何部分。不是按钮或边框。但它正在运行这个类,因为我在按钮的for循环中打印了一个命令行 – 2012-07-10 18:40:55
不要忘记使用正确的Java命名约定:类应以大写字母开头,方法和变量以小写字母开头。当你要求陌生人帮助你处理你的代码时,这变得很重要:不遵守约定的代码很难让我们理解,使它更难以帮助你。 – 2012-07-10 18:59:46