List in Java AWT


The List represents a list of text items. The list can be configured that user can choose either one item or multiple items.

Constructor Used for
List() new scrolling list.
List(int row_num) new scrolling list initialized with the given number of rows visible.
List(int row_num, Boolean multipleMode) new scrolling list initialized which displays the given number of rows.

This Java AWT program demonstrates the use of the List component, which is used to create a scrolling list of items, along with a Button and a Label. The program creates a new Frame named MyApp and sets its size and layout to null (i.e., absolute positioning). It then creates a List component named lst with 4 visible rows and adds several planet names to it.

It also creates a Button named btn with a label "Show Details" and sets its bounds. When the button is clicked, it gets the selected items from the List component and sets the Label named lbl with the selected items. The Label initially displays "Empty Label" and is positioned below the List and Button.

Finally, the program adds the List, Button, and Label to the Frame, and adds a WindowListener to the Frame to exit the program when the window is closed. The main method creates an instance of MyApp to display the GUI.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
 
//List in Java AWT
class MyApp extends Frame{
 
	List lst;
	Button btn;
	Label lbl;
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000, 600);// w,h
		setLayout(null);
		setVisible(true);
		lst = new List(4, false);
		lst.setBounds(10, 50, 100, 100);
		lst.add("Mercury");
		lst.add("Venus");
		lst.add("Earth");
		lst.add("Mars");
		lst.add("Jupiter");
		lst.add("Saturn");
		lst.add("Uranus");
		lst.add("Neptune");
		lst.add("Pluto");
 
		btn = new Button("Show Details");
		btn.setBounds(10, 170, 100, 30);
 
		btn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
 
				String list[] = lst.getSelectedItems();
 
				String data = "Selected Planet : ";
				for (String x : list)
					data += x + " , ";
				lbl.setText(data);
			}
		});
 
		lbl = new Label("Empty Label");
		lbl.setBounds(200, 170, 300, 30);
 
 
		add(lst);
		add(btn);
		add(lbl);
		// Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
 
}
 
public class app {
	public static void main(String[] args) {
		MyApp frm = new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs