Adding and Deleting items from AWT list in Java

Adding items in AWT list

  1. import java.applet.Applet;  
  2. import java.awt.List;  
  3. import java.awt.Color;  
  4. public class Demo extends Applet {  
  5.  public void init() {  
  6.   List l = new List(8true);  
  7.   l.add("Desktop");  
  8.   l.add("Laptop");  
  9.   l.add("Tablet");  
  10.   l.add("Phone");  
  11.   l.add("Kindle");  
  12.   l.add("Screen");  
  13.   l.add("System");  
  14.   add(l);  
  15.   setBackground(Color.blue);  
  16.  }  
  17. }  
 
applet
 
We can see in the above applet image all the items added in the AWT list with the 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);  
  2. l.remove(3);  
  3. 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 the item’s position.
 
Note: Items can also be deleted by defining the item’s name as given below.
  1. l.remove("Desktop”);    
  2.   l.remove("Laptop"); 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.