Adding and Deleting items from AWT list in Java

Adding items in AWT list

  1. import java.applet.Applet; //creates an applet  
  2. import java.awt.List; //creates a list  
  3. import java.awt.Color; //fill the applet background color  
  4.   
  5. public class Demo extends Applet  
  6. {  
  7.   
  8.     public void init()  
  9.   {  
  10.   
  11.         List l = new List(8, true); // create a list  
  12.   
  13.         // add item to a list  
  14.         l.add("Desktop"); //adds item "Desktop" in the list at [0] position  
  15.         l.add("Laptop"); //adds item "Laptop" in the list at [1] position  
  16.         l.add("Tablet"); //adds item "Tablet" in the list at [2] position  
  17.         l.add("Phone"); // and so on.. l.add("Surface");  
  18.         l.add("Kindle");  
  19.         l.add("Screen");  
  20.         l.add("System");  
  21.   
  22.         add(l); // add the list  
  23.   
  24.         setBackground(Color.blue); //set the setBackground color 'blue'  
  25.     }  
  26. }  
applet
 
We can see in the above applet image all the items added in the AWT list with blue background color.

Deleting items for AWT list

By adding a line of code to remove or delete the items in the above code example.
  1. add(l); // add the list  
  2.   
  3. l.remove(3); //remove item at [3] position from the list i.e ‘Phone’  
  4.   
  5. setBackground(Color.blue); //set the setBackground color 'blue'  
applet

We can see that the 3rd positioned item (according to list) “Phone” has been removed or deleted from the list. We can also delete multiple items in a single time by defining item’s position.

Note: Items can also be deleted by defining item’s name as given below.
  1. l.remove("Desktop”);  
  2. l.remove("Laptop");  
  3. l.remove("Tablet");  
applet

We can see that the 3 items have been removed at once. All the items can be removed at once by using the following syntax.
  1. l.removeAll();  
applet

Thank you keep learning and sharing.

 

Ebook Download
View all
Learn
View all