【问题标题】:Variable amounts of arguments in class类中可变数量的参数
【发布时间】:2016-04-14 23:20:21
【问题描述】:

对于我正在做的一个项目,我必须创建一个名为 BirdButton 的类,它的构造函数中有 4 个或 5 个参数。它看起来像下面这样。注意动物是一个单独的类,它是一些鸟类的图片。根据输入,birdbutton 将突出显示图像中的不同鸟类。

import java.awt.event.ActionEvent;

public class BirdButton extends EventButton
{
    public BirdButton(String n, int x, int y, Animals a){
     super(n);
     setLabel(n);
     setBounds(50,10,x,y);
     a.add(this);
    }

    public void actionPerformed(ActionEvent e) {

    }
}

在另一个类中,我尝试将按钮添加到 JFrame,但是传递给按钮的参数数量是 4 或 5。对于这个项目,另一个类驱动程序无法更改,看起来像这样

public class Driver {
    private JFrame win;
    private Animals animals = new Animals();
    private BirdButton nextBtn, enlargeBtn, shrinkBtn, moveToBtn;
    private JTextField field;

    public Driver() {
        win = new JFrame("Angry Animal Name Game");
        win.setBounds(100, 100, 600, 600);
        win.setLayout(null);
        win.setVisible(true);
        nextBtn = new BirdButton( "NEXT", 10, 10, animals);
        win.add(nextBtn, 0);
        enlargeBtn = new BirdButton( "ENLARGE", 10, 60, animals);
        win.add(enlargeBtn, 0);
        shrinkBtn = new BirdButton( "SHRINK", 10, 110, animals);
        win.add(shrinkBtn, 0);
        field = new JTextField();
        field.setBounds(10, 250, 100, 20);
        win.add(field, 0);
        moveToBtn = new BirdButton( "MOVETO", 10, 275, animals, field);
        win.add(moveToBtn, 0);
        win.add(animals, 0);
        animals.recenter();
        win.repaint();
    }
}

当我尝试编译代码时,我收到一个错误,即参数数量的长度不同,因此它不起作用。如何对 BirdButton 进行编码以接受 4 个或 5 个输入?

谢谢

【问题讨论】:

  • 你为什么不能再创建一个接受 5 个参数的构造函数?

标签: java arguments


【解决方案1】:

使用重载的构造函数:

public class BirdButton extends EventButton
{
    public BirdButton(String n, int x, int y, Animals a, JTextField field) {
        super(n);
        setLabel(n);
        setBounds(50,10,x,y);
        setField(field);
        a.add(this);
    }

    public BirdButton(String n, int x, int y, Animals a) {
        this(n, x, y, a, null);
    }
}

【讨论】:

  • 谢谢你让它工作,但我真的不明白创建第二个构造函数和其中的代码背后的概念。您能否对整个重载的构造函数概念有所了解?
  • @GeeBoughuski,就像方法重载一样。它们都具有相同的名称,但接受不同的参数。第二个版本使用this 关键字调用第一个版本,将null 作为field 值传递。
  • 和聪明人的话:不要使用可变参数,只是自找麻烦和无法维护的代码
猜你喜欢
  • 1970-01-01
  • 2017-08-04
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 2017-09-13
  • 2010-12-12
  • 1970-01-01
相关资源
最近更新 更多