如何从文本框中检索值并在actionPerformed()
中使用? 我需要将该值转换为String
以进行进一步处理。 我已经创建了一个文本框,单击按钮后我需要将输入的值存储到String
中,请提供一段代码片段。
如何从文本框中检索值并在actionPerformed()
中使用? 我需要将该值转换为String
以进行进一步处理。 我已经创建了一个文本框,单击按钮后我需要将输入的值存储到String
中,请提供一段代码片段。
testField.getText()
请参阅Java文档中的JTextField
示例代码如下:
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();
ActionListener
示例:
mytextField.addActionListener(this);
public void actionPerformed(ActionEvent evt) {
String text = textField.getText();
textArea.append(text + newline);
textField.selectAll();
}
"\n"
字符串。 - Nirmal- thInk beYondString newline = System.getProperty("line.separator");
这样的代码就是正确的吗? - trashgodString 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);
}
}
现在它正在运作。
class serverfact
并实例化名为VIEWBTN
的内容。这两个名称都没有使用我熟悉的编程风格。 - trashgodclass ServerFact
或JTextField resText
。我之前对这个答案进行了负评,因为它是误导性的;现在它是正确的,所以我已经撤销了投票。我不确定它是否增加了先前答案的内容,但我会听从@harshini的意见,看它是否有用。我很乐意检查您提出的其他答案。我不能保证点赞,但我可以保证诚实、建设性的评论。 - trashgod只需在actionPerformed
内使用event.getSource()
即可。
将其转换为组件。
例如,如果您需要下拉框:
JComboBox comboBox = (JComboBox) event.getSource();
JTextField txtField = (JTextField) event.getSource();
Object selected = comboBox.getSelectedItem(); etc.
你可以在代码的任何地方使用getText()方法,只要它被你的对象实例化调用,所以你可以在类中的任何地方使用该方法。