从Textfield中读取值

时间:2012-01-28 10:18:26

标签: java swing jtextfield

我想从Java中的textfied中读取一个值,但我无法读取它 这是我的代码

import javax.swing.*;
import java.awt.*; 
import java.awt.event.ActionListener;
import java.awt.event.*;

public class TextField extends JDialog {
  TextField() {
    JFrame frm = new JFrame("SAMPLE PROGRAM");
    frm.setBounds(150,150,420,400);
    frm.setLayout(null);
    Container content = frm.getContentPane();
    content.setBackground(Color.cyan);
    JTextField text = new JTextField();
    text.setBounds(70,25,100,30);
    JButton button1, button2; 
    button1 = new JButton("PROGRAMMER");
    button2 = new JButton("USER");
    button1.setBounds(270,25,120,50);
    button2.setBounds(270,90,120,50);
    button1.addActionListener(new ButtonHandler());
    button2.addActionListener(new ButtonHandler());
    frm.add(button1);
    frm.add(button2);
    frm.add(text);
    frm.setVisible(true);
    frm.setResizable(false);
  }

  public static void main(String[] args) {
    new TextField();
  }
  class ButtonHandler implements ActionListener { 
    public void actionPerformed(ActionEvent e) {     
      String str = new String();     
      str = e.getActionCommand();    
      System.out.println(" " + str);
    }
  }  
}

我尝试了以下方法

1.在Class Textfield中,我在button2.addactionlistener下使用了这个方法。它给出了一个错误

不能引用在不同方法中定义的内部类中的非最终变量文本

button1.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent ae) {  
    if(text.getText().equals("joe")) 

2.在班级ButtonHandler

它说文字无法解决

我应该使用什么方法来阅读文本字段以及应该在哪个类中阅读

2 个答案:

答案 0 :(得分:2)

1)如果你重命名(可能与名称为TextField的AWT API冲突)并删除JDialog,因为它从未使用过

public class TextField extends JDialog { TextField(){

public class MyTextField { public MyTextField(){

2)并更改主要方法

public static void main(String[] args) {
    new TextField();
}

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            private final JTabbedPane jtp = new JTabbedPane();

            @Override
            public void run() {
                MyTextField textField = new MyTextField();
            }
        });
    }

3)删除所有字符>

4)为JFrame添加DefaultCloseOparation,否则您的程序将保留在内存中,直到您的PC重新启动或关闭

5)删除所有联合国_ Swing methods并使用LayoutManager

答案 1 :(得分:1)

String str = text.getText();

如果你替换

,这应该有效
str = e.getActionCommand();

 String str = text.getText();

如果这不起作用,您可能必须将JTextField创建为静态JTextField或添加最终修饰符。

PS:下次,只需要输入必要的代码,而不是JFrame或JButtons,它只会让代码更容易阅读。