【问题标题】:How to make a 'get' method for returning a JButton如何制作返回 JButton 的“get”方法
【发布时间】:2015-05-07 04:28:52
【问题描述】:

大家好,我要返回一个特定的 JButton,然后再在上面设置 setText。 这是代码的sn-p:

JButton[][] tiles = new JButton[4][4];
for (int i=0; i<4; i++) {
    for (int j=0; j<4; j++){
        tiles[i][j] = new JButton();
    }   
}

我基本上想使用访问器方法返回这个 JButton。

public JButton getJButton(int i, int j) {   
    return JButton[i][j];   
}

这是我目前的想法,但是目前返回 null,关于解决方案的任何想法?

非常感谢。

【问题讨论】:

  • 改成:return tiles[i][j];
  • 谢谢,我目前的问题是我不能在类外使用这个方法,因为它返回:无法从 TileBoard 类型对非静态方法 getJButton(int, int) 进行静态引用,但是,将其声明为静态会导致它返回 null。有什么想法吗?

标签: java swing jbutton accessor


【解决方案1】:

private JButton[][] tiles; 应该是字段变量

在你的构造函数中做tiles = new JButton[4][4]; for...

然后将获取方法更改为:

public JButton getJButton(int i, int j) {   
    return tiles[i][j];   
}

【讨论】:

    【解决方案2】:

    声明

    JButton[][] tiles = null;
    
    public void init() {
        tiles = new JButton[4][4];
        for (int i=0; i<4; i++) {
            for (int j=0; j<4; j++) {
                tiles[i][j] = new JButton();
            }   
        }
    }
    
    public JButton getJButton(int i, int j) {   
        return tiles[i][j];
    }
    

    【讨论】:

    • 谢谢,但是出现了一个新问题:如果我尝试从另一个类调用此方法,则会出现错误:无法从输入瓷砖板。提供的唯一解决方案是使 get 方法成为静态方法,这使得该解决方案不起作用,有什么想法吗?
    • 将 JButton[][] tiles = null 声明为静态 JButton[][] tiles = null;它解决了你的问题。
    • 现在只返回 null,而不是正确的 JButton。
    • 确保在调用 getter 之前已经初始化了 JButton 数组。还要检查 JButton[][] tile 是否在 init() 方法中声明为局部变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多