In my example im using a Vector to manipulate the
JList, u can add/remove/clear elements using methods
in Vector class & dont' forgot to call
JList.updateUI() method after modifying the source
Vector...
(By using vector u can dynamically add or remove
items in runtime. Unlike arrays u can change the
size() of Vector in runtime, this will be helpful
while making dynamic JList or JComboBox)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;
public class JListDemo extends JFrame implements
ActionListener
{
Vector vStatic = new Vector();
Vector vData = new Vector();
JList list1 = new JList(vData);
JTextField jtfItemName = new JTextField(12);
JButton jbtnAdd = new JButton("Add Item");
JButton jbtnRefresh = new JButton("Load Static
Items");
JButton jbtnRemove = new JButton("Remove All Items");
public JListDemo()
{
super("JList Demo");
vStatic.add("One");
vStatic.add("Two");
vStatic.add("Three");
vStatic.add("Four");
JPanel jpnlNorth = new JPanel(new
FlowLayout(FlowLayout.LEFT));
jpnlNorth.add(new JLabel("Add a new Item to list"));
jpnlNorth.add(jtfItemName);
jpnlNorth.add(jbtnAdd);
JPanel jpnlSouth = new JPanel(new
FlowLayout(FlowLayout.CENTER));
jpnlSouth.add(jbtnRefresh);
jpnlSouth.add(jbtnRemove);
Container c = getContentPane();
c.add("North",jpnlNorth);
c.add("Center",new JScrollPane(list1));
c.add("South",jpnlSouth);
validate();
pack();
show();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jbtnAdd.addActionListener(this);
jbtnRefresh.addActionListener(this);
jbtnRemove.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jbtnAdd)
{
vData.add(jtfItemName.getText().trim());
}
else if(ae.getSource() == jbtnRefresh)
{
vData.removeAllElements();
vData.addAll(vStatic);
}
else if(ae.getSource() == jbtnRemove)
{
vData.removeAllElements();
}
// DON'T FORGOT THESE LINES ARE IMPORTANT TO UPDATE
JList
vData.trimToSize();
list1.updateUI();
validate();
pack();
}
public static void main(String args[])
{
new JListDemo();
}
}