我在按钮名称中有问题

时间:2010-12-23 23:33:38

标签: java

这是我的代码:

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;

public class Keyboard extends BorderLayout
{
    public Panel p1 = new Panel();
    public Button[] arr = new Button[20];
    public String[] name =
    {
        "9", "8", "7", "6", "5", "4", "3", "2", "1", "0",
        "+", "-", "*", "/", ".", "cos", "sin", "=", "pow"
    };

    public Keyboard()
    {
    }

    public String[] getName()
    {
        return name;
    }

    public void setName(String[] name)
    {
        this.name = name;
    }

    public Panel Keyboard()
    {
        for (int i = 0; i < arr.length; i++)
        {
            this.arr[i] = new Button("" + this.name[i]);
        }


        this.p1.setLayout(new GridLayout(6, 6));

        for (int i = 0; i < arr.length; i++)
        {
            this.arr[i].setBackground(Color.LIGHT_GRAY);
            this.arr[i].setForeground(Color.BLUE);
            this.p1.add(this.arr[i]);
        }
        this.p1.setBackground(Color.green);
        return this.p1;
    }
}

调用名称的字符串数组有问题... 如果我在代码中写这行: this.arr[i]=new Button("boaz"); 每个叫做boaz的按钮...... 但我想看看这个数组的按钮:

public String[] name = {"9","8","7","6","5","4","3","2","1","0","+","-","*","/",".","cos","sin","=","pow"};

但是当我写这一行以将字符串放在按钮的名称时:

this.arr[i]=new Button(""+this.name[i]);

按钮消失的面板

我需要写的是按钮将具有数组名称字符串的名称? 代码行this.arr[i]=new Button(""+this.name[i]);不起作用的方式......

1 个答案:

答案 0 :(得分:2)

首先,我不确定你为什么要扩展BorderLayout。没有看到你的其他应用程序,我在这里猜测。但是,如果您要在面板中显示计算器按钮,则更简单的方法是让包含面板的框架包含按钮网格。像这样:

class MyFrame extends JFrame{
  public MyFrame() {
    setLayout(new BorderLayout() );
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(6, 6) );

    for (int i = 0; i < name.length; i++) {
      JButton btn = new JButton(name[i]);
      p1.add(btn);
    }

    add(p1, BorderLayout.CENTER);
  }

  private static final String[] name = {"9","8","7","6","5","4","3","2","1","0",
      "+","-","*","/",".","cos","sin","=","pow"};
}

还有其他一些想法: 您的代码在Keyboard()方法的第一个for循环中有一个ArrayIndex异常,因为它检查arr []变量的长度,但访问名称[] var,其大小较小。

另外,我强烈建议您不要使用与类(和构造函数)同名的方法。 public Keyboard()是您的类的构造函数,也没有其他方法JPanel Keyboard()。把它称之为别的东西。

您的代码使用awt类(Panel,Button)。学习swing类同行(JPanel,JButton,JFrame等)。创建它们是为了使GUI构建任务更容易。

最后,我不能向人们强调这一点......如果你是初学者在java中构建GUI,那么online Swing tutorials是非常好的。您可以从中学到很多示例代码。