【发布时间】:2019-09-14 11:09:32
【问题描述】:
我正在开发一个 GUI 网格,我需要选择特定的单元格。我用JFrame。我的目标是用数字填充第一列和最后一行,例如 x-y 轴。
我已尝试声明一个 JButtons 数组,其中包含我需要的确切单元格位置,并设置文本。 (代码中的大写锁定注释)
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridLayoutTest {
private static JButton[] arrayBtn;
public static void main(String[] args ) {
// the frame that contains the components
JFrame frame = new JFrame("GridLayoutTest from JCG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set the size of the frame
frame.setSize(1000, 1000);
// set the rows and cols of the grid, as well the distances
between them
GridLayout grid = new GridLayout(10,14, 0, 0);
// what layout we want to use for our frame
frame.getContentPane().setBackground(Color.WHITE);;
frame.setLayout(grid);
arrayBtn = new JButton[140];
// add JButtons dynamically
for(int i=0; i < arrayBtn.length; i++) {
arrayBtn[i] = new JButton();
arrayBtn[i].setBackground(Color.WHITE);
arrayBtn[i].setSize(1,1);
//IF I RUN ONLY THIS WORKS WITH THE FIRST CELL(IF I INSERT OUT
// THE FOR CYCLE DOESN'T WORK)
arrayBtn[0].setText("9");
// IF I RUN ALSO THIS CODE ROW I HAVE THE SAME ERROR
arrayBtn[1].setText("9");
frame.add(arrayBtn[i]);
}
frame.setVisible(true);
}
}
例外:
Exception in thread "main" java.lang.NullPointerException
relative to the row of the specific cell selected.
【问题讨论】:
标签: java swing jframe jbutton grid-layout