Pin It

How to use Combo Box (Drop-Down list) in Java using Swing ?.

A Simple program demonstrating the use of Combo Box (Drop-Down list) in Java using Swing.


Click here to download complete source code 


package com.hubberspot.swing.example;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ComboBoxDemo extends JFrame {
  private String[] languages = {
    "Java", "C++", "C", "Python",
    "JavaScript", "Perl", "Ruby", "C#"
  };
  
  private JTextField textfield1 = new JTextField
   ("Top Programming Languages : ");

  private JTextField textfield2 = new JTextField(15);
  private JComboBox comboBox = new JComboBox();
  
  private int count = 0;

  public ComboBoxDemo() {
 for(int i = 0; i < languages.length; i++)
   comboBox.addItem(languages[count++]);
 textfield1.setEditable(false);

 comboBox.addActionListener(new ActionListener() { 
   public void actionPerformed(ActionEvent e) {
  textfield2.setText("You Selected : " +      
       ((JComboBox)e.getSource()).getSelectedItem());
   }
 });
 
 setLayout(new FlowLayout());
 add(textfield1);
 add(textfield2);
 add(comboBox);    
 }
 
  public static void main(String[] args) {
 setFrame(new ComboBoxDemo(), 250, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
 SwingUtilities.invokeLater(new Runnable() {
   public void run() {
     frame.setTitle(frame.getClass().getSimpleName());
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(width, height);
     frame.setVisible(true);
   }
 });
 }

}
Output of the program : 



 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot