【发布时间】:2012-03-13 20:45:12
【问题描述】:
我遇到了 JTextField 问题。我需要从 JTextField 获取文本并稍后在 JDialog 中对其进行修改。我对 JTextField 使用相同的变量。只要您不进入对话框,打印的字符串就是您在文本字段中输入的任何内容。如果您在对话框中输入一个字符串,它只会打印该字符串,直到您在对话框中再次更改它(使主文本字段无用)。我可以通过添加一个单独的变量来解决这个问题,但想尽量避免不必要的声明。我的印象是这无关紧要,因为我正在创建一个新的 JTextField 对象并处理对话框。我错过了什么吗?有什么想法吗?
这是我的问题的模型。
import java.awt.event.*;
import javax.swing.*;
public class textfield extends JPanel {
private JTextField textfield;
private JButton printButton, dialogButton, okayButton;
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame();
frame.setSize(200,200);
frame.getContentPane().add(new textfield());
frame.setVisible(true);
}
private textfield() {
textfield = new JTextField(10);
add(textfield);
((AbstractButton) add(printButton = new JButton("Print"))).addActionListener(new printListener());
((AbstractButton) add(dialogButton = new JButton("Dialog"))).addActionListener(new dialogListener());
}
private class printListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String string = null;
string = textfield.getText();
System.out.println(string);
}
}
private class dialogListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
final JDialog dialog = new JDialog(frame, "Dialog", true);
JPanel p = new JPanel();
textfield = new JTextField(10);
p.add(textfield);
p.add(okayButton = new JButton(new AbstractAction("Okay") {
public void actionPerformed(ActionEvent e) {
String string = null;
string = textfield.getText();
System.out.println(string);
dialog.dispose();
}
}));
dialog.add(p);
dialog.pack();
dialog.setVisible(true);
}
}
}
【问题讨论】:
标签: java swing actionlistener jtextfield jdialog