簡體   English   中英

如何將來自 2 個不同 JTextField 的 2 個元素添加到一個 JList

[英]How to add 2 elements from 2 different JTextField to one JList

如何將來自不同 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);
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM