java - 为什么我的 Java 代码不获取 JTextfield 的值?

标签 java swing null jtextfield

我正在尝试从文本字段(由用户输入)中获取一个值以用于处理。但无论我做什么,它都不会获得输入的值,它似乎仍然是空的。有人能告诉我为什么它不能从文本字段中获取值吗?

这是最初创建名为 writeStrings 的文本字段的方法

public void chooseEmpToAdd()
{
     JTextArea EmpDetails = new JTextArea(5,20);
     JTextField writeStrings  = new JTextField(20); 
     JLabel enterIDno = new JLabel("Please enter The Employye ID number that you wish to assign to a department: ");  

     JButton  submit  = new JButton  (" Submit") ;
       ButtonListenerEmp Listener2 = new ButtonListenerEmp(); 
      submit.addActionListener(Listener2);
     JFrame frameAllEmps = new JFrame();
      frameAllEmps.setSize( 150, 140 );
     frameAllEmps.pack();
     frameAllEmps.setVisible(true); 

     //layout
     frameAllEmps.setLayout(new FlowLayout());
      frameAllEmps.add(enterIDno);

    int x = 0;
    System.out.println("ALL Emps from the tree map");
    for(int key:employeeMap.keySet())
    {

        Employee dEmp = employeeMap.get(key);
        System.out.println("Employe no :" +x+": "+dEmp);
        EmpDetails.setText(EmpDetails.getText()+" "+dEmp);
        frameAllEmps.add(EmpDetails);   
         x++;
    }

    frameAllEmps.add(new JScrollPane(EmpDetails));
    frameAllEmps.add(writeStrings);
    frameAllEmps.add(submit);
    frameAllEmps.pack();

}

这是应该从文本框中获取值并将其打印到控制台的操作监听器,但它不起作用。

 private class ButtonListenerEmp implements ActionListener
    {
        public void actionPerformed (ActionEvent e )
        {
            String ID ; 
            int dID;


               ID = writeStrings.getText();
                System.out.println("start of try b4 changes: "+ID);     
               }
           }

最佳答案

监听器实现不应该访问局部变量 writeStrings,我什至不确定那将如何编译——您发布的代码是否准确?

哦,您可能同时拥有一个局部变量 writeStrings 一个实例变量 writeStrings,尽管这很难说,因为您没有不要发布其余代码。尽量不要在 chooseEmpToAdd 方法中声明 writeStrings;改用类变量。

关于java - 为什么我的 Java 代码不获取 JTextfield 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7869453/

相关文章:

java - 这个问题的最佳数据结构?

java - 获取ArrayList中重复项的数量

java - 调用时 GUI 无法正确显示

java - 如何生成 1 次鼠标 + 1 次键盘点击?

android - 在 SwipeRefreshLayout 上设置刷新( bool 值)时偶尔会出现 NullPointerExceptions

java - MULTIPART_FORM_DATA : No injection source found for a parameter of type public javax. ws.rs.core.Response

java - 如何在 Java 中使用 SHA384 生成 48 个字符的哈希

Java:如何检查字符串的整个 JTree 路径

Java:你能像 C 中那样对待 null 像整数 0 吗?

ios - 在 Objective-c 中,我应该使用什么来返回该参数不能为零?