Saturday, 4 July 2015

Adding Or Removing Elements From JList In Java

Before reading this tutorial you should have enough knowledge about JList  see our tutorial on How to create simple Jlist In Java.This tutorial shows how to add or remove list elements on a run a time user can add element on clicking on add button user also have a choice to remove all or any single selected item this program following methods to add or remove item-list.

int getSelectedIndex():

This method returns that index which is selected by user and if no item-list is selected then this method method will return -1.

remove(int):

This method is used to remove desired item from list model in java.

CODING:

import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class myfram extends JFrame implements ActionListener 
{
JList l1;
JTextField t1;
JButton b1,b2,b3;
int ret;
DefaultListModel listModel;

myfram()

{
setTitle("Adding or Removing Items From JList");
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
listModel = new DefaultListModel();
listModel.addElement("Item 1");
listModel.addElement("Item 2");
listModel.addElement("Item 3");
listModel.addElement("Item 4");
//creating J List
l1 = new JList(listModel);
//Creating Text Field
t1 = new JTextField(10);  
//Creating Buttons
b1 = new JButton("ADD");
b1.addActionListener(this);
b2 = new JButton("REMOVE");
b2.addActionListener(this);
b2.setActionCommand("remove");
b3 = new JButton("Clear All");
b3.addActionListener(this);
b3.setActionCommand("clear");
//adding jlist to a scrollpane
JScrollPane js = new JScrollPane(l1);
js.setPreferredSize(new Dimension(300,100));
add(js);
add(t1);
add(b1);
add(b2);
add(b3);
setSize(700,500);
setVisible(true);
}

public void actionPerformed(ActionEvent ae)

{
if ("clear".equals(ae.getActionCommand()))
{
listModel.removeAllElements();

}


else if("remove".equals(ae.getActionCommand()))

{
ret = l1.getSelectedIndex();
listModel.remove(ret);
}
else
{
String select =t1.getText();
Object obj = select;
listModel.add(0,obj);

}

}

}

public class simplelist
{

public static void main(String[] args) 

{

myfram fr = new myfram();

}
}

OUTPUT:





Cosmetic Planet

No comments:

Post a Comment