简体   繁体   English

初始化JButton引用类型的2D数组

[英]Initialize a 2D Array of JButton reference type

How to initialize/declare a 2D array of reference type in Java? 如何在Java中初始化/声明引用类型的2D数组? In particular I want to initialize a 2d array of JButton type (3x3) and then add them to a frame inside the constructor. 特别是,我想初始化JButton类型(3x3)的2d数组,然后将它们添加到构造函数内的框架中。 How do i go about it? 我该怎么办?

MadProgrammer is correct, but in order to use them, you will need to initialize every JButton individually thereafter. MadProgrammer是正确的,但是为了使用它们,此后您需要分别初始化每个JButton。

JButton[][] buttons = new JButton[3][3];
for(int i = 0; i <= 2; i++){
    for(int x = 0; x <= 2; x++){
        buttons[i][x] = new JButton();
    }
}
JButton[][] myButtons = JButton[3][3];

creates the array you need. 创建您需要的数组。 It declares and initializes the array. 它声明并初始化数组。 If you want to declare and initialize it separately, then you can do it this way: 如果要分别声明和初始化,则可以通过以下方式进行:

JButton[][] myButtons;
//...
myButtons = JButton[3][3];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM