这是电话键盘小程序.....
我的小程序出现问题,似乎正在将整个阵列打印到选定的号码,我只希望打印选定的号码,就像拨打电话时手机上的情况一样。谁能看到我错了?先谢谢了!
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
最佳答案
作为你的陈述
if(e.getSource() == keys[i])
没有括号,只有下一条语句将被有条件地执行:
foundKey=true;
。但是声明
lcd.setText(lcd.getText()+ keys[i].getLabel());
不管是否满足条件,都将被打印。
解决方案:学会始终将括号放在if,switch,while,for等上。