繁体   English   中英

如何从 Java Swing 中的 JTextField 检索值?

[英]How to Retrieve value from JTextField in Java Swing?

我们如何从文本字段和actionPerformed()检索值? 我需要将值转换为String以进行进一步处理。 我在单击按钮时创建了一个文本字段,我需要将输入的值存储到String中,您能提供一个代码片段吗?

testField.getText()

请参阅JTextField的 java 文档

示例代码可以是:

button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent ae){
      String textFieldValue = testField.getText();
      // .... do some operation on value ...
   }
})
* First we declare JTextField like this

 JTextField  testField = new JTextField(10);

* We can get textfield value in String like this on any button click event.

button.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent ae){
      String getValue = testField.getText()

   }
})

我们如何从文本字段中检索值?

mytestField.getText();

ActionListner示例:

mytextField.addActionListener(this);

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();
}

我发现有帮助的是下面的这种情况。

String tempEmail = "";
JTextField tf1 = new JTextField();

tf1.addKeyListener(new KeyAdapter(){
    public void keyTyped(KeyEvent evt){
         tempEmail = ((JTextField)evt.getSource()).getText() + String.valueOf(evt.getKeyChar());
    }
});
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Swingtest extends JFrame implements ActionListener
{
    JTextField txtdata;
    JButton calbtn = new JButton("Calculate");

    public Swingtest()
    {
        JPanel myPanel = new JPanel();
        add(myPanel);
        myPanel.setLayout(new GridLayout(3, 2));
        myPanel.add(calbtn);
        calbtn.addActionListener(this);
        txtdata = new JTextField();
        myPanel.add(txtdata);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == calbtn) {
            String data = txtdata.getText(); //perform your operation
            System.out.println(data);
        }
    }

    public static void main(String args[])
    {
        Swingtest g = new Swingtest();
        g.setLocation(10, 10);
        g.setSize(300, 300);
        g.setVisible(true);
    }
}

现在它的工作

只需在actionPerformed使用event.getSource() frim

将其投射到组件

例如,如果您需要组合框

JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();

使用适当的api来获取值,

对于前。

Object selected = comboBox.getSelectedItem();  etc.

您可以在代码中的任何地方使用 getText() 方法,它被您的对象实例调用,因此您可以在 calass 中的任何地方使用该方法

暂无
暂无

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

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