简体   繁体   English

如何从JTextField获取用户输入?

[英]How do I get user input from a JTextField?

I am attempting a very simple form designed to take user input into a JTextField and show that same input via a pop up dialog. 我正在尝试一个非常简单的表单,旨在将用户输入带入JTextField并通过弹出对话框显示相同的输入。

I can hardcode the JTextField to have a preset number using setText(). 我可以使用setText()将JTextField硬编码为具有预设编号。 If I do this, my program works flawlessly. 如果我这样做,我的程序完美无瑕。

However, when I leave the field blank and try getText() to show the text in the pop up dialog, I either get an empty pop up frame, or I get an 'empty string' exception (I am attempting to parse String to Double.) 但是,当我将该字段留空并尝试使用getText()在弹出对话框中显示文本时,我要么得到一个空的弹出框架,要么我得到一个'空字符串'异常(我试图将String解析为Double) 。)

package buttontest; import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import javax.swing.*; import java.awt.event.ActionEvent; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; public class ButtonTest { public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class ButtonFrame extends JFrame { @SuppressWarnings("LeakingThisInConstructor") public ButtonFrame() { setTitle("SunStream Loan Calculator v2.0"); setSize(900,900); ButtonPanel panel = new ButtonPanel(); panel.add(new JLabel("Enter your loan amount:")); loanAmt = new JTextField(40); panel.add(loanAmt); add(panel,BorderLayout.CENTER); } public JTextField loanAmt; class ButtonPanel extends JPanel implements ActionListener { private Component frame; public ButtonPanel() { final JButton b2 = new JButton("Calculate"); add(b2, BorderLayout.SOUTH); b2.setActionCommand("calculate"); b2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { ButtonFrame bf = new ButtonFrame(); if("calculate".equals(e.getActionCommand())) { JOptionPane.showMessageDialog(frame, bf.loanAmt.getText()); } } }); } @Override public void actionPerformed(ActionEvent ae) { throw new UnsupportedOperationException("Not supported yet."); } } }

Any help would be greatly appreciated. 任何帮助将不胜感激。 I am researching using a KeyListener or KeyEvent but I don't quite understand it well enough. 我正在使用KeyListener或KeyEvent进行研究,但我不太了解它。

You're creating a "shadow" ButtonFrame variable inside of the b2's ActionListener. 你正在b2的ActionListener中创建一个“阴影”ButtonFrame变量。 Yes the bf variable refers to a ButtonFrame object which is of the same class as the displayed ButtonFrame object, but it refers to a completely distinct and non-visualized object. 是的,bf变量引用的ButtonFrame对象与显示的ButtonFrame对象具有相同的类,但它引用了一个完全不同且不可视化的对象。 The key to a solution is to get the text from the ButtonFrame object that is actually displayed, and this can be obtained from within an inner class via the ButtonFrame.this construct: 解决方案的关键是从实际显示的ButtonFrame对象中获取文本,这可以通过ButtonFrame.this结构从内部类中ButtonFrame.this

     b2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           //!! ButtonFrame bf = new ButtonFrame();
           if ("calculate".equals(e.getActionCommand())) {

              //!! note use of ButtonFrame.this:
              JOptionPane.showMessageDialog(frame, ButtonFrame.this.loanAmt.getText());
           }
        }

     });

Next consider using public getters rather than accessing fields such as the JTextField directly. 接下来考虑使用公共getter,而不是直接访问JTextField等字段。 This reduces the chances of the code causing side effects, such as changing the properties of the JTextField object inadvertently. 这减少了代码导致副作用的可能性,例如无意中更改了JTextField对象的属性。

For instance (changes denoted by //!! comment): 例如(由// !!评论表示的变化):

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

public class ButtonTest {
   public static void main(String[] args) {
      ButtonFrame frame = new ButtonFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

class ButtonFrame extends JFrame {

   private JTextField loanAmt; // !! Make field private

   @SuppressWarnings("LeakingThisInConstructor")
   public ButtonFrame() {

      setTitle("SunStream Loan Calculator v2.0");
      setSize(900, 900);
      ButtonPanel panel = new ButtonPanel();
      panel.add(new JLabel("Enter your loan amount:"));
      loanAmt = new JTextField(40);
      panel.add(loanAmt);

      add(panel, BorderLayout.CENTER);
   }

   // !! create a public method to get JTextField's text
   // !! without exposing the JTextField itself.
   public String getLoanAmtText() {
      return loanAmt.getText();
   }

   class ButtonPanel extends JPanel implements ActionListener {
      private Component frame;

      public ButtonPanel() {

         final JButton b2 = new JButton("Calculate");
         add(b2, BorderLayout.SOUTH);
         b2.setActionCommand("calculate");
         b2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               // !! ButtonFrame bf = new ButtonFrame();
               if ("calculate".equals(e.getActionCommand())) {

                  //!! call public method on ButtonFrame object
                  JOptionPane.showMessageDialog(frame,
                        ButtonFrame.this.getLoanAmtText());
               }
            }

         });

      }

      @Override
      public void actionPerformed(ActionEvent ae) {
         throw new UnsupportedOperationException("Not supported yet.");
      }

   }
}

The only way you can access your loanAmt is through ButtonPanel itself. 您可以访问loanAmt的唯一方法是通过ButtonPanel本身。 Because you add loanAmt to this button right ? 因为你把loanAmt添加到这个按钮吗?

So, if you want access loanAmt . 所以,如果你想访问loanAmt You must get all component on this button panel. 您必须在此按钮面板上获取所有组件。 This is my psudeo code howto accessing your loanAmt from ButtonPanel class. 这是我的psudeo代码如何从ButtonPanel类访问loanAmt

b2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        ButtonFrame bf = new ButtonFrame();
        if("calculate".equals(e.getActionCommand())) {
            // Get all component 
            java.awt.Component[] componentList = this.getComponents();
            JTextField txtField;
            String value;
            for (int i = 0; i < componentList.length; i++) {
                if (componentList[i].getClass().getName().equals("javax.swing.JTextField")) {
                    txtField = (JTextField) componentList[i];
                    value = textField.getText();
                }
            }
            if (value != null) JOptionPane.showMessageDialog(frame, value);
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM