Java Jcombobox Class Example

JCOMBOBOX

Java Swing Tutorial Explaining the JComboBox Component. JComboBox is like a drop down box — you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.

JCOMBOBOX SOURCE CODE

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

public class JComboBoxDemo extends JPanel {

 JLabel jlbPicture;
 public JComboBoxDemo() {
  String[] comboTypes = { "Numbers", "Alphabets", "Symbols" };
  // Create the combo box, and set 2nd item as Default
  JComboBox comboTypesList = new JComboBox(comboTypes);
  comboTypesList.setSelectedIndex(2);
  comboTypesList.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {
    JComboBox jcmbType = (JComboBox) e.getSource();
    String cmbType = (String) jcmbType.getSelectedItem();
    jlbPicture.setIcon(new ImageIcon(""
      + cmbType.trim().toLowerCase() + ".jpg"));
   }
  });
  // Set up the picture
  jlbPicture = new JLabel(new ImageIcon(""
    + comboTypes[comboTypesList.getSelectedIndex()] + ".jpg"));
  jlbPicture.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
  jlbPicture.setPreferredSize(new Dimension(177, 122 + 10));
  // Layout the demo
  setLayout(new BorderLayout());
  add(comboTypesList, BorderLayout.NORTH);
  add(jlbPicture, BorderLayout.SOUTH);
  setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
 }
 public static void main(String s[]) {
  JFrame frame = new JFrame("JComboBox Usage Demo");
  frame.addWindowListener(new WindowAdapter() {

   public void windowClosing(WindowEvent e) {
    System.exit(0);
   }
  });
  frame.setContentPane(new JComboBoxDemo());
  frame.pack();
  frame.setVisible(true);
 }
}
Output
Download JComboBox Source Code

ANOTHER EXAMPLE: JCOMBOBOX SOURCE CODE

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.*;
import java.text.*;

public class DateComboBoxDemo extends JPanel {

 static JFrame frame;
 JLabel jlbResult;
 String datePattern_Current;
 public DateComboBoxDemo() {
  String[] datePatterns = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy",
    "yyyy.MM.dd G 'at' hh:mm:ss z", "EEE, MMM d, ''yy",
    "h:mm a", "H:mm:ss:SSS", "K:mm a,z",
    "yyyy.MMMMM.dd GGG hh:mm aaa" };
  datePattern_Current = datePatterns[0];
  // Set up the UI for selecting a pattern.
  JLabel jlbHeading = new JLabel(
    "Enter Date pattern /Select from list:");
  JComboBox patternList = new JComboBox(datePatterns);
  patternList.setEditable(true);
  patternList.setAlignmentX(Component.LEFT_ALIGNMENT);
  patternList.addActionListener(new ActionListener() {

   public void actionPerformed(ActionEvent e) {
    JComboBox jcmbDates = (JComboBox) e.getSource();
    String seletedDate = (String) jcmbDates.getSelectedItem();
    datePattern_Current = seletedDate;
    showDateinLabel();
   }
  });
  // Create the UI for displaying result
  JLabel jlbResultHeading = new JLabel("Current Date/Time",
    JLabel.LEFT);
  jlbResult = new JLabel(" ");
  jlbResult.setForeground(Color.black);
  jlbResult.setBorder(BorderFactory.createCompoundBorder(
    BorderFactory.createLineBorder(Color.black), BorderFactory
      .createEmptyBorder(5, 5, 5, 5)));
  // Lay out everything
  JPanel jpnDate = new JPanel();
  jpnDate.setLayout(new BoxLayout(jpnDate, BoxLayout.Y_AXIS));
  jpnDate.add(jlbHeading);
  jpnDate.add(patternList);
  JPanel jpnResults = new JPanel();
  jpnResults.setLayout(new GridLayout(0, 1));
  jpnResults.add(jlbResultHeading);
  jpnResults.add(jlbResult);
  setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
  jpnDate.setAlignmentX(Component.LEFT_ALIGNMENT);
  jpnResults.setAlignmentX(Component.LEFT_ALIGNMENT);
  add(jpnDate);
  add(Box.createRigidArea(new Dimension(0, 10)));
  add(jpnResults);
  setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
  showDateinLabel();
 } // constructor
 /** Formats and displays today's date. */
 public void showDateinLabel() {
  Date today = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat(
    datePattern_Current);
  try {
   String dateString = formatter.format(today);
   jlbResult.setForeground(Color.black);
   jlbResult.setText(dateString);
  } catch (IllegalArgumentException e) {
   jlbResult.setForeground(Color.red);
   jlbResult.setText("Error: " + e.getMessage());
  }
 }
 public static void main(String s[]) {
  frame = new JFrame("JComboBox Usage Demo");
  frame.addWindowListener(new WindowAdapter() {

   public void windowClosing(WindowEvent e) {
    System.exit(0);
   }
  });
  frame.setContentPane(new DateComboBoxDemo());
  frame.pack();
  frame.setVisible(true);
 }
}
Output
Download JComboBox Source Code

JAVA JCOMBOBOX HIERARCHY

javax.swing
Class JComboBox 
java.lang.Object
java.awt.Component
java.awt.Container
javax.swing.JComponent
javax.swing.JComboBox
All Implemented Interfaces: 
Accessible, ActionListener, EventListener, ImageObserver, ItemSelectable, ListDataListener, MenuContainer, Serializable

JCOMBOBOX CONSTRUCTOR

JComboBox()
Creates a JComboBox with a default data model.
JComboBox(ComboBoxModel aModel)
Creates a JComboBox that takes it’s items from an existing ComboBoxModel.
JComboBox(Object[] items)
Creates a JComboBox that contains the elements in the specified array.
JComboBox(Vector items)
Creates a JComboBox that contains the elements in the specified Vectornext

EDITABLE JCOMBOBOX

Java Swing Tutorial Explaining the Editable JComboBox Component. JComboBox is like a drop down box —
you can click a drop-down arrow and select an option from a list. It generates ItemEvent. For example, when
the component has focus, pressing a key that corresponds to the first character in some entry’s name selects that entry. A vertical scrollbar is used for longer lists.

EDITABLE JCOMBOBOX SOURCE CODE

JComboBox’s getSelectedItem() is used to get what is entered into the control. However when a user types something into the JCombBox rather than selecting an item from the list and does not hit “enter” after entering the text, the getSelectedItem() does not return what is currently entered in the field (it instead gets the last selected item). The users often do not know to hit enter when they change the value in the JComboBox so they just click an “OK” button on the panel (signifying a save) and the value in the JComboBox is not properly saved. But the below program overcomes this probelm by simulating an enter key in the JComboBox or get the value that has been manually entered when the user does not hot “enter” in the JComboBox.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JComboBoxEditable extends JFrame
{
 JComboBox jcmbNames;

 public JComboBoxEditable()
 {
  String[] names = { "hemanth", "Shawn", "Hunter", "Undertaker", "Big Show" };

  jcmbNames = new JComboBox( names );
  jcmbNames.setEditable( true );
  getContentPane().add(jcmbNames, BorderLayout.NORTH);

  JButton jbnOk = new JButton("Ok");
  getContentPane().add(jbnOk, BorderLayout.SOUTH);

//  Print Name of the Selected Combo Box Item to Console when OK button is pressed
  jbnOk.addActionListener( new ActionListener()
  {
   public void actionPerformed(ActionEvent e)
   {
    System.out.println( jcmbNames.getSelectedItem() );
   }
  });

//  Print Name of the Selected Combo Box Item to Console when Enter is pressed

  jcmbNames.addActionListener( new ActionListener()
    { public void actionPerformed(ActionEvent e)
      { System.out.println( jcmbNames.getSelectedItem() );
      }
    });
 }

 public static void main(String[] args)
 {
  JComboBoxEditable frame = new JComboBoxEditable();
  frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
  frame.pack();
  frame.setLocationRelativeTo( null );
  frame.setVisible( true );
  }
}
Output
Download Editable JComboBox Source Code

No comments:

Post a Comment