在Java Applet中打印整个数组而不是单个值

时间:2014-05-12 06:38:17

标签: java arrays applet

这是一个电话键盘小程序.....

我的applet出现问题似乎是将整个阵列打印到所选的数字我希望它只打印所选的数字,就像拨打号码时在手机上发生的那样。谁能看到我哪里出错了?先谢谢!

 import java.awt.*;
  import java.awt.event.*;

 public class Telephone extends Frame implements ActionListener
 {
Button keys[];
Panel keypad;
TextField lcd;
Label value;
boolean  foundKey;

public Telephone()
{
    lcd =new TextField(20);
        lcd.setEditable(false);
    keypad= new Panel ();
    keys= new Button[13];



    //construct and assign captions to the buttons
    for (int i=0; i<=9; i++)
        keys[i] = new Button(String.valueOf(i));

    keys[10] =new Button ("*");
    keys[11] =new Button ("0");
    keys[12] =new Button ("#");


    setBackground(Color.magenta);
    setLayout(new BorderLayout());
    keypad.setLayout(new GridLayout(4,3,10,10));

    //add keys
    for(int i=1; i<=3; i++)//1,2,3
                keypad.add(keys[i]);

    for (int i=4; i<=6; i++)//4,5,6
                keypad.add(keys[i]);

    for (int i=7; i<=9; i++)//7,8,9
        keypad.add(keys[i]);

    keypad.add(keys[10]);
    keypad.add(keys[11]);
    keypad.add(keys[12]);

    for (int i=0; i<keys.length; i++)
        keys[i].addActionListener(this);

    //add componets to display
    add(lcd, BorderLayout.NORTH);
    add(keypad,BorderLayout.CENTER);
    //add()

    addWindowListener(

        new WindowAdapter()
                {
                    public void windowClosing(WindowEvent e)
                    {
                        System.exit(0);
                    }
                }
    );

}//constructor ends

public void actionPerformed(ActionEvent e)
{
    foundKey = false;
    for (int i=0; i<keys.length &&!foundKey;i++)
            {
                if(e.getSource() == keys[i])

            foundKey=true;
                //switch(i)
                //{
                //  case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:


                    lcd.setText(lcd.getText()+ keys[i].getLabel());
            //      break;
            //  }//end switch
            }//end for
}//end actionPerformed

    public static void main(String args[])
    {
        Telephone f = new Telephone();
        f.setTitle("Telephone Application");
        f.setBounds(50,130,250,300);
        f.setVisible(true);
    }
 }//class ends

1 个答案:

答案 0 :(得分:2)

作为你的陈述

 if(e.getSource() == keys[i])

没有括号,只有条件执行下一个语句:

 foundKey=true;

。但声明

 lcd.setText(lcd.getText()+ keys[i].getLabel());
无论if条件如何,都会打印

解决方案:学会始终将括号括起来if,switch,while,for等。