java - 如何从 Java Swing 中多次使用的同一文本字段中获取文本
问题描述
我正在尝试从通过我的代码迭代的 JTextField 获取文本(显然,我无法从按钮添加不同的文本字段)。以下是“添加项目”按钮的作用:
addButton.addActionListener(new ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);
p.revalidate();
p.repaint();
p.add(tf);
p.add(tfv);
}
});
它使用 FlowLayout 在面板中添加了两个新的文本字段。现在,我想通过单击“确定”按钮从文本字段中获取用户给出的文本,每个文本字段都分配给不同的变量,或者可能进入 ArrayList,但 getText() 方法似乎不起作用。
okButton.addActionListener( e -> {
String txt = tfv.getText(); //only captures the text from the last field in the panel
});
现在好像什么都想不起来。
解决方案
在此代码中,当您重新初始化tf
并且丢失对先前定义的文本字段的引用时tfv
addButton
tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);
所以要解决这个问题,您需要定义一个 ArrayList 来保存对所有已定义文本字段的引用,然后您可以访问所有这些:
ArrayList<JTextField> arrayNames = new ArrayList<JTextField>();
ArrayList<JTextField> arrayValues = new ArrayList<JTextField>();
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);
p.revalidate();
p.repaint();
p.add(tf);
p.add(tfv);
arrayNames.add(tf);
arrayValues.add(tfv);
}
});
访问
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (JTextField txtValue : arrayValues) {
System.out.println(txtValue.getText());
}
}
});
推荐阅读
- swift - 以编程方式关闭大写锁定
- kendo-ui - 窗口中的简单 Kendo DropDownList 绑定
- google-apps-script - 每次运行脚本时如何增加脚本中引用的单元格?
- python - NameError:写入文件时未定义名称“write”
- java - 不支持的事件循环组类型:使用 pgjdbc-ng 的 NioEventLoopGroup
- templates - 在 Marketo 中更改模板后如何有效更新所有登陆页面?
- ruby-on-rails - 有没有办法防止每次实例化模型时都触发漂亮的打印宝石?
- node.js - npm 版本不匹配命令行与控制面板
- unity3d - 使用 Lean Touch 和 1 根手指旋转
- reactjs - 在一个形状上使用 onClick 事件来创建一个新形状