java 获取文本框内容 getText()取不到,赋默认值却可以取到
publicclassTestButton{publicstaticvoidmain(String[]args){Framef=newFrame("test");f.se...
public class TestButton {
public static void main(String[] args) {
Frame f = new Frame("test");
f.setBounds(200, 100, 300, 200);
Panel panel = new Panel();
Button b = new Button("提交");
TextField tx= new TextField();
b.setBounds(50, 50, 5, 10);
panel.add(tx);
panel.add(b);
System.out.println("------1-------"+tx.getText());
b.addActionListener(new ButtonHandler(tx.getText()));
f.add(panel);
f.setVisible(true);
f.addWindowListener(new TestFrame());
}
}
}
public class ButtonHandler implements ActionListener{
public String text;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("事件发生。。。。");
System.out.println("按钮的标签是:"+e.getActionCommand());
System.out.println("------------"+text);
}
public ButtonHandler(String text) {
// TODO Auto-generated method stub
this.text = text;
}
} 展开
public static void main(String[] args) {
Frame f = new Frame("test");
f.setBounds(200, 100, 300, 200);
Panel panel = new Panel();
Button b = new Button("提交");
TextField tx= new TextField();
b.setBounds(50, 50, 5, 10);
panel.add(tx);
panel.add(b);
System.out.println("------1-------"+tx.getText());
b.addActionListener(new ButtonHandler(tx.getText()));
f.add(panel);
f.setVisible(true);
f.addWindowListener(new TestFrame());
}
}
}
public class ButtonHandler implements ActionListener{
public String text;
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("事件发生。。。。");
System.out.println("按钮的标签是:"+e.getActionCommand());
System.out.println("------------"+text);
}
public ButtonHandler(String text) {
// TODO Auto-generated method stub
this.text = text;
}
} 展开
1个回答
展开全部
不需要构造方法 TextFileld定义成全局变量 在监听里getText
public class ButtonHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("事件发生。。。。");
System.out.println("按钮的标签是:"+e.getActionCommand());
System.out.println("------------"+t.getText());
}
}
public class ButtonHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("事件发生。。。。");
System.out.println("按钮的标签是:"+e.getActionCommand());
System.out.println("------------"+t.getText());
}
}
更多追问追答
追问
可是我在同一个类中system.out.println("----------1-------------"+tx.getText());这里都获取不到,
追答
最开始初始化都没加文本内容 怎么可能有值
TextField tx= new TextField(“Test”);
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询