我無法爲我的課程生成用於戰艦克隆的按鈕數組,並且似乎無法弄清楚爲什麼它不起作用。任何建議將有助於...我有主類創建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