我想用Eclipse实现按下+在TextField中显示+;按下-在TextField中显示-,可是按下后TextField没有反应
importjava.awt.*;importjava.awt.event.*;publicclassTestLove{publicstaticvoidmain(Stri...
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("-");
}
}
}
} 展开
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("-");
}
}
}
} 展开
1个回答
展开全部
你的代码没什么大问题
修改下两个地方就可以运行了
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得到的是标签,就是按钮上的文字
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询