简体   繁体   English

如何从2D按钮阵列访问一个按钮? Java JSwing

[英]How do I access one button from a 2D array of buttons? Java JSwing

I am trying to create a grid of buttons. 我正在尝试创建一个按钮网格。 This is my code to create the grid (which works), but if I want to access a single button later on how would I go about doing that? 这是我创建网格的代码(有效),但是如果我以后想访问单个按钮,我将如何做呢?

    for(int i = 1; i<= row; i++){
        for( int p=1; p<= col; p++){
           boardPanel.add(new JButton());   
        }
    }

Many Thanks 非常感谢

A Clements; 克莱门特;

From your question title I'm assuming that you want to be able to access these buttons from a 2d array, but in your code the button is not in an array. 根据您的问题标题,我假设您希望能够从2d数组访问这些按钮,但是在您的代码中,该按钮不在数组中。 If you did something like the following: 如果您执行以下操作:

JButton[][] buttons = new JButton[row][col];
for(int i = 1; i<= row; i++){
    for( int p=1; p<= col; p++){
       buttons[i][p] = new JButton();
       boardPanel.add(buttons[i][p]);   
    }
}

Then you are maintaining a 2d array that contains references to the buttons in your JPanel. 然后,您将维护一个2D数组,其中包含对JPanel中的按钮的引用。 So now you can access the buttons from the array like this: 因此,现在您可以像这样从数组访问按钮:

buttons[i][j];

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

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