我想用Eclipse实现按下+在TextField中显示+;按下-在TextField中显示-,可是按下后TextField没有反应

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

public class TestLove {

public static void main(String[] args) {

new LVFrame().LaunchLVFrame(100,100,800,800,Color.pink);
}

}

class LVFrame extends Frame{
TextField tf;
public void LaunchLVFrame(int x,int y,int w,int h,Color color){

setBounds(x,y,w,h);
setBackground(color);
setVisible(true);

tf = new TextField(10);

Button btnStay = new Button("+");
Button btnLeave = new Button("-");

btnStay.addActionListener(new Moniter ());
btnLeave.addActionListener(new Moniter());

add(btnStay);
add(btnLeave);
add(tf);

setLayout(new FlowLayout(FlowLayout.RIGHT,10,10));
pack();
}

class Moniter implements ActionListener{

public void actionPerformed(ActionEvent e){

if(e.getSource()== "+"){
tf.setText("+");
}
else if(e.getSource() == "-"){
tf.setText("-");
}

}

}

}

你的代码没什么大问题

修改下两个地方就可以运行了

 class Moniter implements ActionListener {
  public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("+")) {
    tf.setText("+");
   } else if (e.getActionCommand().equals("-")) {
    tf.setText("-");
   }
  }
 }

用e.getActionCommand()取得的字符串来判断是+还是-

就可以了

 

 

getSource得到的组件的名称和信息等

getActionCommand得到的是标签,就是按钮上的文字

温馨提示:答案为网友推荐,仅供参考
相似回答