How to read an input value from a JTextField and add to a JList in Java?


A JList is a subclass of JComponent class that allows the user to choose either a single selection or multiple selections. A JList class itself does not support scrollbar. In order to add scrollbar, we have to use JScrollPane class together with the JList class. The JScrollPane then manages a scrollbar automatically. A DefaultListModel class provides a simple implementation of a list model, which can be used to manage items displayed by a JList control. We can add items or elements to a JList by using addElement() method of DefaultListModel class. We can also add items or elements to a JList by reading an input value from a text field.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JTextfieldToJListTest extends JFrame {
   private DefaultListModel model;
   private JList list;
   private JTextField jtf;
   public JTextfieldToJListTest() {
      setTitle("JTextfieldToJList Test");
      model = new DefaultListModel();
      jtf = new JTextField("Type something and Hit Enter");
      jtf.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            jtf.setText("");
         }
      });
      list = new JList(model);
      list.setBackground(Color.lightGray);
      jtf.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            model.addElement(jtf.getText());
            JOptionPane.showMessageDialog(null, jtf.getText());
            jtf.setText("Type something and Hit Enter");
         }
      });
      add(jtf,BorderLayout.NORTH);
      add(new JScrollPane(list),BorderLayout.CENTER);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTextfieldToJListTest();
   }
}

Output

raja
Published on 25-Jul-2019 11:47:35
Advertisements