java - 如何将 2 个不同 JTextField 中的 2 个元素添加到一个 JList
问题描述
如何将来自不同 JTextField 的元素添加到一个列表。我试图将元素放在字符串中并将它们添加到列表中,但那不起作用。
解决方案
您必须将字符串添加到备份JList
. 这是一个简短的示例代码,JTextField
每当您在文本字段中按 ENTER 时,都会将 current 的值附加到列表中:
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.BorderLayout;
public final class Example extends JFrame {
public Example() {
setLayout(new BorderLayout());
// Create a list model and populate it with two initial items.
final DefaultListModel<String> model = new DefaultListModel<String>();
model.addElement("Initial 1");
model.addElement("Initial 2");
// Create a JList (wrapped into a JScrollPane) from the model
add(new JScrollPane(new JList<String>(model)), BorderLayout.CENTER);
// Create a JTextField at the top of the frame.
// Whenever you click ENTER in that field, the current string gets
// appended to the list model and will thus show up in the JList.
final JTextField field1 = new JTextField("Field 1");
add(field1, BorderLayout.NORTH);
field1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Append " + field1.getText());
model.addElement(field1.getText());
}
});
// Create a JTextField at the bottom of the frame.
// Whenever you click ENTER in that field, the current string gets
// appended to the list model and will thus show up in the JList.
final JTextField field2 = new JTextField("Field 2");
add(field2, BorderLayout.SOUTH);
field2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Append " + field2.getText());
model.addElement(field2.getText());
}
});
}
public static void main(String[] args) {
final JFrame frame = new Example();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { System.exit(1); }
});
frame.pack();
frame.setVisible(true);
}
}
推荐阅读
- javascript - 在反应js中下载后pdf文件损坏
- loopback - Loopback 4 - POST 请求数据源模板
- android - 跳过recyclerview上面的视图
- python - mqtt客户端在线程和rest-api的情况下没有收到消息
- python - 带有阿拉伯字符的 CSV 文件在 Excel 中显示为符号
- python - 通过 Python 脚本实现 VBA 宏
- java - 为什么创建URI时主机名声明无效
- html - CSS Circle DIV,背景不是 1:1
- kubernetes - 如何在 zsh 上禁用 kubectl 自动完成功能
- django - 在 Ubuntu VPS 上运行的 Django 应用程序:无法访问此站点