简体   繁体   English

如何访问存储在JLabels的2D数组中的JLabel超类的方法

[英]How can I access a method of a JLabel super class stored in a 2D array of JLabels

I am trying to make a numbers game which involves creating a grid of JLabels which are stored in a 2D array. 我正在尝试制作一个数字游戏,其中涉及创建一个JLabel网格,这些网格存储在2D数组中。

The JLabels themselves are established by creating an object of the NumberPanel class which creates a JLabel displaying a random number. 通过创建NumberPanel类的对象来建立JLabel本身,该对象创建一个显示随机数的JLabel。

In the main class which creates the objects via the 2D array I need to be able to access a method of the NumberPanel class called "isClicked" to set a boolean value to true or false. 在通过2D数组创建对象的主类中,我需要能够访问NumberPanel类的名为“ isClicked”的方法,以将布尔值设置为true或false。

I have pasted my code below, if anyone can give me a hand I would greatly appreciate it :) 我在下面粘贴了我的代码,如果有人可以帮我,我将不胜感激:)

**NumberPanel Class:**

public class NumberPanel extends JLabel {

    private boolean isClicked;

    NumberPanel() {
        //Constructor code
    }

    public void clicked(boolean b) {    //Need to access this method
        isClicked = b;
    }
}

**Original class containing NumberPanel objects**

public class NumberGameGui extends JPanel {

    private JLabel[][] numberGrid;

private void gridPopulator() {

    for (int i = 0; i < 12; i++) 
        for (int j = 0; j < 9; j++) {
            numberGrid[i][j] = new NumberPanel();
            add (numberGrid[i][j]);
            numberGrid[i][j].addMouseListener (new PanelListener());
        }

    **NumberGrid[1][1].isClicked(true);** //Want to access isClicked method
}

Try this: 尝试这个:

((NumberPanel)numberGrid[1][1]).isClicked(true);

Or use NumberPanel as the static class of the array: 或使用NumberPanel作为数组的静态类:

private NumberPanel[][] numberGrid;

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

相关问题 如何在NetBeans中手动将jlabel添加到jlabel数组? - How to add jlabels to a jlabel array manually in netbeans? 将几个JLabel分配给二维数组索引 - Assigning several JLabels to 2d array index 将JLabels的2D数组打印到GridLayout - Printing a 2D array of JLabels to a GridLayout 如何用不同的类对象制作2D数组? - How Can I make 2D array with different object of class? 如何将JLabel与其下方的JLabel行对齐 - How do I line up my JLabel with the row of JLabels below it 如何使用1D数组初始化2D数组? - How can I initialize an 2D array with 1D array? 将充满数字值的文件分配给JLabels的2D数组 - Assigning file filled with number values to a 2D array of JLabels 如果我有一个方法名称以字符串形式存储在2D数组中,是否可以使用该字符串来调用所述方法? - If I have a method name stored in a 2D array as a String, is it possible for me use that String to call said method? 如何在 Java 中编写一个循环,该循环使用存储在另一个二维数组中的数据访问二维数组,该二维数组包含每个 position 的相邻位置 - How to code a loop in Java that access a 2D array using the the data stored in another 2D array that contains the adyacent positions of each position 如何调用超类的重写方法? - how can i call a overriden method of the super class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM