Add and Remove Elements in JList Dynamically

Till now we've seen how to work with JLists, store jlist selected items using serialization also on how it looks on NimbusLookAndFeel and now it's time to look at how to dynamically add contents to JList and delete them.

Shall we go? OK. Let's go!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class DynamicJList extends JFrame
JMenuBar mbar;
JMenu menu;
JTextField jf;
JButton jb;
JList<String> jl;
Vector<String> v;
public DynamicJList()
// Set frame properties
setTitle("Dynamic JList");
setLayout(new FlowLayout());

// Create a vector that can store String objects
v=new Vector<String>();

// Create a JList that is capable of storing String type items
jl=new JList<String>(v);

// Make it fat.
jl.setPreferredSize(new Dimension(200,200));

// Add key listener to JList jl
jl.addKeyListener(new KeyAdapter(){

// What to do when a key is pressed?
public void keyPressed(KeyEvent ke)

// If user presses Delete key,

// Remove the selected item

// Now set the updated vector (updated items)


// Create a new MenuBar
mbar=new JMenuBar();

// Create a menu with text Menu
menu=new JMenu("Menu");

// Create a JButton with text Add
jb=new JButton("Add");

// Add actionlistener to JButton jb
jb.addActionListener(new ActionListener(){

// When user does an action?
public void actionPerformed(ActionEvent ae)

// Add what the user types in JTextField jf, to the vector

// Now set the updated vector to JList jl

// Make the button disabled



jf=new JTextField(20);

// Add key listener to JTextField
jf.addKeyListener(new KeyAdapter(){

// What to do when a key is pressed?
public void keyPressed(KeyEvent ke)
// Make the JButton enabled

// When user presses enter key, then..
// Click on JButton, doClick() does it!


// Add JTextField jf to JMenu menu

// Add JButton jb to JMenu menu

// Add JMenu menu to JMenuBar mbar

// Add MenuBar to frame. Don't set.

// Create a scrollpane for JList jl
JScrollPane js=new JScrollPane(jl);

// Add that scrollpane to JFrame. You don't need to add JList again, as you add scrollpane, it means that you are adding JList because JScrollPane is pointing JList only!


public static void main(String args[])
new DynamicJList();


That's it. Everything is explained within the program and all that is in this paragraph for you has a link to other  swing components. Take a look.

Watch it. Before you leave!

Posted by at on

Tags: Swing Components,