日期:2014-05-20  浏览次数:20715 次

JAVA中JTextField监听的返回值问题。

package com.lesson;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;
public class JieMian1 {
public static void main(String[] args) {
tt t=new tt();
System.out.println(t.cn);
}

}
class tt extends JFrame implements ActionListener
{
long cn;
int pw;
JPanel jp1,jp2,jp3;
JButton jb1,jb2;
JLabel jl1,jl2;
JTextField jtf;
JPasswordField jpf;
public tt()
{
jp1=new JPanel();
jp2=new JPanel();
jp3=new JPanel();
jb1=new JButton("确认");
jb2=new JButton("取消");
jl1=new JLabel("账     号");
jl2=new JLabel("密     码");

jtf=new JTextField(10);
jtf.addActionListener(this);
jtf.setActionCommand("gettext");
jpf=new JPasswordField(10);
this.setLayout(new GridLayout(3,1));
jp1.add(jl1);
jp1.add(jtf);
jp2.add(jl2);
jp2.add(jpf);
jp3.add(jb1);
jp3.add(jb2);
this.add(jp1);
this.add(jp2);
this.add(jp3);
this.setSize(200,200);
this.setVisible(true);
}

public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("gettext"))
{
cn=Long.parseLong(jtf.getText());
}
else
System.out.println("no");
}
}

为了方便,我贴出所有代码。为什么我在监听的时候已经取得了那个值,就是倒数第六行的cn,这个cn也是tt类的成员,可是我在主函数中将其输出时为什么不能输出?  
java class

------解决方案--------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

你要注意到先后的问题。。
 tt t=new tt();//这里并不是阻塞的,也就是说不管你是否输入数字,点不点确定,下面的都会执行。

        System.out.println(t.cn);//所以这个在没有你输入数字的时候就已经执行了。
想看效果的话,可以在
if(e.getActionCommand().equals("gettext"))
        {
            cn=Long.parseLong(jtf.getText());
        }
这里添加输出。


噢~ 我也知道在那边添加输出是可行的。 可是假设我现在就需要用到这个数据,就需要JTextField中的内容,那我该怎么办?

你需要这个内容,在哪里用到这个是关键。。。
在主函数里面么?


劳烦大侠都说一下吧。
1.main函数里面
2.其他类

小菜鸟

如果我在主函数里面写成阻塞的,不知道你能否理解。
说实在的,这要求有点哭笑不得,真没有这样需求。
先用标记位解决吧

public class JieMian1 {
static boolean flag=true;
public static void main(String[] args) {
tt t = new tt();

while(flag){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(t.cn);
}

}

class tt extends JFrame implements ActionListener {
long cn;
int pw;
JPanel jp1, jp2, jp3;
JButton jb1, jb2;
JLabel jl1, jl2;
JTextField jtf;
JPasswordField jpf;

public tt() {
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jb1 = new JButton("确认");
jb2 = new JButton("取消");
jl1 = new JLabel("账     号");
jl2 = new JLabel("密     码");

jtf = new JTextField(10);
jtf.setBackground(Color.BLACK);
jtf.addActionListener(this);
jtf.setActionCommand("gettext");
jpf = new JPasswordField(10);
this.setLayout(new GridLayout(3, 1));
jp1.add(jl1);
jp1.add(jtf);
jp2.add(jl2);
jp2.add(jpf);
jp3.add(jb1);
jp3.add(jb2);
this.add(jp1);
this.add(jp2);
this.add(jp3);
this.setSize(200, 200);
this.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("dianji");
if (e.getActionCommand().equals("gettext")) {
cn = Long.parseLong(jtf.getText());
JieMian1.flag=false;//添加个这个
} else
System.out.println("no");
}

}

另外,你实现的接口的竟然是ActionListener 
真不知道你这个程序如何去触发