gpt4 book ai didi

java - 如何将 2 个不同 JTextField 中的 2 个元素添加到一个 JList

转载 作者:行者123 更新时间:2023-12-01 18:36:55 26 4
gpt4 key购买 nike

如何将不同 JTextField 中的元素添加到一个列表中。我尝试将元素放入字符串并将它们添加到列表中,但这不起作用。

最佳答案

您必须将字符串添加到支持 JList 的列表模型中。以下是简短的示例代码,每当您在文本字段中按 ENTER 键时,该代码都会将当前 JTextField 的值附加到列表中:

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);
}
}

关于java - 如何将 2 个不同 JTextField 中的 2 个元素添加到一个 JList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com