这是我正在制作的计算器的alpha代码,我希望它是按下" 1"计算器在我的数组中输入1,但它甚至不会触发keyPressed。
package ws1;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class ws41 extends Applet implements ActionListener, KeyListener{
Button equals,zero,one,two,three,four,five,six,seven,eight,nine,divide,times,plus,minus,u2s,s2u,period;
Label show;
double total;
double dot;
double left=0;
double right=0;
String tots = "";
String sign = "";
ArrayList<Integer> Calc = new ArrayList<Integer>();
public void init(){
setSize(30,200);
show = new Label("");
period = new Button(" . ");
u2s = new Button(" Usd to Sek");
s2u = new Button("Sek to Usd");
zero = new Button(" 0 ");
one = new Button(" 1 ");
two = new Button(" 2 ");
three = new Button(" 3 ");
four = new Button(" 4 ");
five = new Button(" 5 ");
six = new Button(" 6 ");
seven = new Button(" 7 ");
eight = new Button(" 8 ");
nine = new Button(" 9 ");
plus = new Button(" + ");
minus = new Button(" - ");
times = new Button(" * ");
divide = new Button(" / ");
equals = new Button(" = ");
this.addKeyListener(this);
zero.addActionListener (this);
one.addActionListener (this);
two.addActionListener (this);
three.addActionListener (this);
four.addActionListener (this);
five.addActionListener (this);
six.addActionListener (this);
seven.addActionListener (this);
eight.addActionListener (this);
nine.addActionListener (this);
plus.addActionListener (this);
times.addActionListener (this);
minus.addActionListener (this);
times.addActionListener (this);
divide.addActionListener (this);
equals.addActionListener (this);
u2s.addActionListener (this);
s2u.addActionListener (this);
period.addActionListener(this);
//add(show);
add(one);
add(two);
add(three);
add(four);
add(five);
add(six);
add(seven);
add(eight);
add(nine);
add(zero);
add(period);
add(plus);
add(minus);
add(times);
add(divide);
add(equals);
add(u2s);
add(s2u);
}
public void keyPressed(KeyEvent ke) {
Calc.add(ke.getKeyCode());
}
public void keyReleased(KeyEvent ke){
}
public void keyTyped(KeyEvent ke) {
}
答案 0 :(得分:0)
KeyListener
是焦点内容。也就是说,它只会在注册的组件具有焦点(并且可以聚焦)时响应键事件
AWT已超过15年,并被Swing取代。考虑使用基于Swing的组件
您不应该在按钮上使用KeyListener
,而应该使用ActionListener
。
有关详细信息,请参阅How to use buttons和How to write ActionListeners
事实上,您可以使用Action
API和key bindings大大简化此操作,因为Action
将在按钮和键绑定之间共享