Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Ella Campbell   on Mar 04 In Java Category.

  
Question Answered By: Umaiza Hashmi   on Mar 04

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();
}
}

Share: 

 

This Question has 3 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Swing problem displaying JList elements in IntelliJ Or get search suggestion and latest updates.


Tagged: