【问题标题】:Cannot find symbol error when calling methods in an extended JButton class在扩展的 JButton 类中调用方法时找不到符号错误
【发布时间】:2014-12-29 17:55:53
【问题描述】:

我需要一些帮助来解决这个问题。我似乎无法弄清楚为什么它不起作用。 我想向我的 ButtonDefault 类添加更多方法,该类是 JButton 的子类,但我不断收到“未找到符号”错误。

下面的代码,ButtonDefault 的实例化,默认颜色和动作 按钮返回并且工作正常。然而,所有这些代码都在 ButtonDefault 的构造函数中。 我想向 ButtonDefault 类添加其他方法,以便稍后我可以更改 按钮等。

我不断收到的错误:
MineSweeper.java:50:找不到符号 符号:方法 setUpButton() 位置:类 javax.swing.JButton 按钮[i][j].setUpButton();

我有 2 节课。

//MineSweeper.java
public class MineSweeper extends JFrame implements ActionListener,MouseListener,ItemListener {
    static JButton[][] button = new ButtonDefault[17][31];

    public void tileSetup()
    {
       button[i][j] = new ButtonDefault(i,j, this); //This work just fine
       //These work too - I just don't want it here. 
       //button[i][j].setIcon(null);
       //button[i][j].setBorder(UIManager.getBorder("Button.border"));
       //button[i][j].setBackground(null);
       //button[i][j].setBackground(Color.BLUE);
       //button[i][j].setBorder(new LineBorder(Color.GRAY, 1));
       //button[i][j].setEnabled(true);
       button[i][j].setUpButton(); //This don't work. 
    }
}

//ButtonDefault.java
public class ButtonDefault extends JButton implements ActionListener,MouseListener,ItemListener
{
    public ButtonDefault(){};
    public ButtonDefault(int x, int y, final MineSweeper mineObject)
    {
        this.setPreferredSize(new Dimension(18,18));
        this.setBackground(Color.BLUE);

        addMouseListener(new MouseListener() {  
           //All the code in here work just fine. 
    }

    public void setUpButton()
    {
        this.setIcon(null);
        this.setBorder(UIManager.getBorder("Button.border"));
        this.setBackground(null);
        this.setBackground(Color.BLUE);
        this.setBorder(new LineBorder(Color.GRAY, 1));
        this.setEnabled(true);
    }

}

【问题讨论】:

    标签: java methods jframe jbutton subclassing


    【解决方案1】:

    setUpButtonButtonDefault 而不是JButton 的自定义方法。因此数组声明应该是

    private ButtonDefault[][] buttons = new ButtonDefault[ROWS][COLUMNS];
    

    注意事项:

    • 通常使用 static 声明表示设计不佳,因此请改用实例字段
    • 幻数也被认为是糟糕的设计,至少考虑使用常量

    【讨论】:

    • 你也可以写ButtonDefault def = new ButtonDefault(i,j, this); button[i][j] = def; def.setUpButton();
    • 哇...这太明显了,我不敢相信我错过了。谢谢!!!现在工作得很好......
    【解决方案2】:

    在调用 setUpButton 之前尝试投射

    ((ButtonDefault)button[i][j]).setUpButton();
    

    【讨论】:

      猜你喜欢
      • 2014-09-24
      • 2015-01-09
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多