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");
setSize(400,400);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);

// 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,
if(ke.getKeyCode()==KeyEvent.VK_DELETE)
{

// Remove the selected item
v.remove(jl.getSelectedValue());

// Now set the updated vector (updated items)
jl.setListData(v);

}
}
});

// 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
v.add(jf.getText());

// Now set the updated vector to JList jl
jl.setListData(v);

// Make the button disabled
jb.setEnabled(false);

}

});

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
jb.setEnabled(true);

// When user presses enter key, then..
if(ke.getKeyCode()==KeyEvent.VK_ENTER)
// Click on JButton, doClick() does it!
jb.doClick();

}
});

// Add JTextField jf to JMenu menu
menu.add(jf);

// Add JButton jb to JMenu menu
menu.add(jb);

// Add JMenu menu to JMenuBar mbar
mbar.add(menu);

// Add MenuBar to frame. Don't set.
add(mbar);

// 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!
add(js);

}

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!



No comments: