Create ComboBox in Java

Create ComboBox in Java:

We can use the Eclipse IDE for this example. If you do not know about it then follow this link- How to Install Eclipse For Java and create a program in it.

A JComboBox is a component that combines two features: a display area showing a default option and a list box that contains additional, alternate options. (A list box is also known as a ComboBox or a drop-down list). The display area contains either a button that a user can click or an editable field into which the user can type. When a JComboBox appears on the screen, the default option is displayed. When the user clicks the JComboBox, a list of alternative items drop-down; if the user selects one, it replaces the box’s displayed item.

Java ComboBox Methods:

MethodDescription
int getItemCount( )Returns the number of items in the list.
int getMaximumRowCount( )Returns the maximum number of items the ComboBox can display without a scroll bar.
int getSelectedIndex( )Returns the index of the selected item.
Object getSelectedItem( )Returns the selected item as an Object.
void removeItem(Object obj )Removes the object from the list.
void removeItemAt(int index)Removes the object at the specified index.
void setBackground(Color)Sets the background color.
void setEditable(boolean)Sets the field to be editable or not editable.
void setSelectedIndex( int)Sets the index at the position indicated by the argument.
void setSelectedItem (Object)Sets the selected item in the ComboBox display area to be the Object argument.
void setOpaque(boolean)Sets background as transparent (boolean is false) or solid (boolean is true).

Sample Code to Create ComboBox in Java:

ComboBox in Java Codeunit
java combox code 1

Output:

java combobox output
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Combobox  extends JFrame implements ActionListener{

	JComboBox combo_box;
	
	Combobox(){
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	this.setLayout(new FlowLayout());
	
	String [] flowers = {"Rose", "Lotus", "Sun Flower", "Marigold"};
	combo_box = new JComboBox(flowers);
	combo_box.addActionListener(this);
	
	this.add(combo_box);
	this.pack();
	this.setVisible(true);
	
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
        if(e.getSource()==combo_box) {
			
			System.out.println(combo_box.getSelectedItem());
		
	}
        
}     
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	new Combobox();
	
	
	}

}

Computer Memory
Basic Components of Computer System
Computer Software and Hardware
Computer Input Devices
Computer Output Devices
Java (programming language)– Wikipedia

Comments (No)

Leave a Reply