Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 JComboBox의 항목을 어떻게 정렬할 수 있습니까?


JComboBox JComponent 의 하위 클래스입니다. 클래스이며 텍스트 필드의 조합입니다. 및 드롭다운 목록 사용자가 값을 선택할 수 있습니다. JComboBox ActionListener, ChangeListener, 를 생성할 수 있습니다. 및 ItemListener 사용자가 콤보 상자에서 작업할 때 인터페이스. 기본적으로 JComboBox는 항목 정렬을 지원하지 않습니다. DefaultComboBoxModel 을 확장하여 코드를 사용자 정의할 수 있습니다. 수업.

예시

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class JComboBoxSorterTest extends JFrame {
   private JComboBox comboBox;
   private JTextField textField;
   public JComboBoxSorterTest() {
      setTitle("JComboBoxSorter Test");
      setLayout(new FlowLayout());
      textField = new JTextField(10);
      textField.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            comboBox.addItem(textField.getText());
            textField.setText("");
            comboBox.showPopup();
         }
      });
      String[] items = {"raja", "archana", "vineet", "krishna", "adithya"};
      SortedComboBoxModel model = new SortedComboBoxModel(items);
      comboBox = new JComboBox(model);
      comboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
      Box box1 = Box.createHorizontalBox();
      box1.add(new JLabel("Enter a name and hit enter "));
      box1.add(textField);
      Box box2 = Box.createHorizontalBox();
      box2.add(comboBox);
      add(box1);
      add(box2);
      setSize(375, 250);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   // Customize the code for sorting of items in the JComboBox
   private class SortedComboBoxModel extends DefaultComboBoxModel {
      public SortedComboBoxModel() {
         super();
      }
      public SortedComboBoxModel(Object[] items) {
         Arrays.sort(items);
         int size = items.length;
         for (int i = 0; i < size; i++) {
            super.addElement(items[i]);
         }
         setSelectedItem(items[0]);
      }
      public SortedComboBoxModel(Vector items) {
         Collections.sort(items);
         int size = items.size();
         for (int i = 0; i < size; i++) {
            super.addElement(items.elementAt(i));
         }
         setSelectedItem(items.elementAt(0));
      }
      public void addElement(Object element) {
         insertElementAt(element, 0);
      }
      public void insertElementAt(Object element, int index) {
         int size = getSize();
         for (index = 0; index < size; index++) {
            Comparable c = (Comparable) getElementAt(index);
            if (c.compareTo(element) > 0) {
               break;
            }
         }
         super.insertElementAt(element, index);
      }
   }
   public static void main(String[] args) {
      new JComboBoxSorterTest();
   }
}

출력

Java에서 JComboBox의 항목을 어떻게 정렬할 수 있습니까?