Java Swing JComboBox

2018-01-09 19:23 更新

Java Swing教程 - Java Swing JComboBox


A JComboBox< E> 是一個Swing組件,允許我們從一個選擇列表中做一個選擇。

JComboBox可以有一個可編輯的字段,我們可以鍵入一個新的選擇值。

類型參數E是它包含的元素的類型。

我們可以通過在其構造函數中傳遞選擇列表來創(chuàng)建一個JComboBox。

以下代碼使用String數組作為選擇列表。

String[] sList = new String[]{"Spring", "Summer",  "Fall",  "Winter"}; 
JComboBox<String> seasons = new JComboBox<>(sList);

下面的代碼使用String的Vector作為選擇列表

Vector<String> myList  = new Vector<>(4); 
myList.add("Spring");
myList.add("Summer"); 
myList.add("Fall"); 
myList.add("Winter");
JComboBox<String> seasons2 = new JComboBox<>(myList);

下表列出了JComboBox類的常用方法。

ID 方法/說明
1 void addItem(E item)將項目添加到列表。 將調用所添加對象的toString()方法,并顯示返回的字符串。
2 E getItemAt(int index)從列表返回指定索引處的項目。
3 int getItemCount()返回選項列表中的項目數。
4 int getSelectedIndex()返回所選項目的索引。 如果所選項目不在列表中,則返回-1。
5 Object getSelectedItem()返回當前選定的項目。 如果沒有選擇,則返回null。
6 void insertItemAt(E item,int index)在列表中指定的索引處插入指定的項目。
7 boolean isEditable()如果JComboBox是可編輯的,則返回true。 否則,它返回false。 默認情況下,JComboBox是不可編輯的。
8 void removeAllItems()從列表中刪除所有項目。
9 void removeItem(Object item)從列表中刪除指定的項目。
10 void removeItemAt(int index)刪除指定索引處的項目。
11 void setEditable(boolean editable)如果指定的可編輯參數為true,則JComboBox是可編輯的。 否則,它是不可編輯的。
12 void setSelectedIndex(int index)選擇列表中指定索引處的項目。 如果指定的索引為-1,它將清除選擇。
13 void setSelectedIndex(int index)選擇列表中指定索引處的項目。 如果指定的索引為-1,它將清除選擇。...


選擇事件

要處理JComboBox中的所選或取消選擇的事件,請向其中添加一個項目偵聽器。每當選擇或取消選擇項目時,都會通知項目偵聽器。

以下代碼顯示了如何向JComboBox添加項目監(jiān)聽器。

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ItemEvent;
// w  ww  .  j ava  2s  .com
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame {
  public Main() {
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    String[] sList = new String[] { "Spring", "Summer", "Fall", "Winter" };
    JComboBox<String> seasons = new JComboBox<>(sList);

    seasons.addItemListener((ItemEvent e) -> {
      Object item = e.getItem();
      if (e.getStateChange() == ItemEvent.SELECTED) {
        // Item has been selected
        System.out.println(item + "  has  been  selected");
      } else if (e.getStateChange() == ItemEvent.DESELECTED) {
        // Item has been deselected
        System.out.println(item + "  has  been  deselected");
      }
    });

    Container contentPane = this.getContentPane();
    contentPane.add(seasons, BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    Main bf = new Main();
    bf.pack();
    bf.setVisible(true);
  }
}


ActionListener

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/*  w w w  .j  a  v  a2s .c  o m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main extends JFrame {
  JComboBox combo = new JComboBox();

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    combo.addItem("A");
    combo.addItem("H");
    combo.addItem("P");
    combo.setEditable(true);
    System.out.println("#items=" + combo.getItemCount());

    combo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Selected index=" + combo.getSelectedIndex()
            + " Selected item=" + combo.getSelectedItem());
      }
    });

    getContentPane().add(combo);
    pack();
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}

在兩個JComboBox之間共享數據模型

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//  w w  w . java  2  s  .  com
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class SharedDataBetweenComboBoxSample {
  public static void main(String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);

    JFrame frame = new JFrame("Shared Data");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    JComboBox comboBox1 = new JComboBox(model);
    comboBox1.setEditable(true);

    JComboBox comboBox2 = new JComboBox(model);
    comboBox2.setEditable(true);
    panel.add(comboBox1);
    panel.add(comboBox2);
    frame.add(panel, BorderLayout.NORTH);

    JButton button = new JButton("Add");
    frame.add(button, BorderLayout.SOUTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.addElement("New Added");
      }
    };
    button.addActionListener(actionListener);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

使用KeySelectionManager監(jiān)聽鍵盤事件

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//  www .jav  a  2s.  c  om
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class SelectingComboSample {

  public static void main(String args[]) {
    String labels[] = { "A", "B", "C", "D", "E", "F" };
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox comboBox = new JComboBox(labels);
    frame.add(comboBox, BorderLayout.SOUTH);

    JComboBox.KeySelectionManager manager =
      new JComboBox.KeySelectionManager() {
        public int selectionForKey(char aKey, ComboBoxModel aModel) {
          System.out.println(aKey);
          return -1;
        }
      };
    comboBox.setKeySelectionManager(manager);

    frame.setSize(400, 200);
    frame.setVisible(true);
  }
}

顏色組合框編輯器

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//from w  ww.j  a  v a  2 s. c o  m
import javax.swing.ComboBoxEditor;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.EventListenerList;

class ColorComboBoxEditor implements ComboBoxEditor {
  final protected JButton editor;

  protected EventListenerList listenerList = new EventListenerList();

  public ColorComboBoxEditor(Color initialColor) {
    editor = new JButton("");
    editor.setBackground(initialColor);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        Color currentBackground = editor.getBackground();
        Color color = JColorChooser.showDialog(editor, "Color Chooser", currentBackground);
        if ((color != null) && (currentBackground != color)) {
          editor.setBackground(color);
          fireActionEvent(color);
        }
      }
    };
    editor.addActionListener(actionListener);
  }

  public void addActionListener(ActionListener l) {
    listenerList.add(ActionListener.class, l);
  }

  public Component getEditorComponent() {
    return editor;
  }

  public Object getItem() {
    return editor.getBackground();
  }

  public void removeActionListener(ActionListener l) {
    listenerList.remove(ActionListener.class, l);
  }

  public void selectAll() {
    // Ignore
  }

  public void setItem(Object newValue) {
    if (newValue instanceof Color) {
      Color color = (Color) newValue;
      editor.setBackground(color);
    } else {
      try {
        Color color = Color.decode(newValue.toString());
        editor.setBackground(color);
      } catch (NumberFormatException e) {
      }
    }
  }

  protected void fireActionEvent(Color color) {
    Object listeners[] = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == ActionListener.class) {
        ActionEvent actionEvent = new ActionEvent(editor, ActionEvent.ACTION_PERFORMED, color
            .toString());
        ((ActionListener) listeners[i + 1]).actionPerformed(actionEvent);
      }
    }
  }
}

public class Main {
  public static void main(String args[]) {
    Color colors[] = { Color.RED, Color.BLUE, Color.BLACK, Color.WHITE };
    JFrame frame = new JFrame("Editable JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JComboBox comboBox = new JComboBox(colors);
    comboBox.setEditable(true);
    comboBox.setEditor(new ColorComboBoxEditor(Color.RED));
    frame.add(comboBox, BorderLayout.NORTH);

    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

Combobox單元格渲染器

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.Graphics;
//from  w  w  w  .j  av a 2s.c o m
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

class ComplexCellRenderer implements ListCellRenderer {
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    Font theFont = null;
    Color theForeground = null;
    Icon theIcon = null;
    String theText = null;

    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
        isSelected, cellHasFocus);

    if (value instanceof Object[]) {
      Object values[] = (Object[]) value;
      theFont = (Font) values[0];
      theForeground = (Color) values[1];
      theIcon = (Icon) values[2];
      theText = (String) values[3];
    } else {
      theFont = list.getFont();
      theForeground = list.getForeground();
      theText = "";
    }
    if (!isSelected) {
      renderer.setForeground(theForeground);
    }
    if (theIcon != null) {
      renderer.setIcon(theIcon);
    }
    renderer.setText(theText);
    renderer.setFont(theFont);
    return renderer;
  }
}

public class Main {
  public static void main(String args[]) {
    Object elements[][] = {
        { new Font("Helvetica", Font.PLAIN, 20), Color.RED, new MyIcon(), "A" },
        { new Font("TimesRoman", Font.BOLD, 14), Color.BLUE, new MyIcon(), "A" },
        { new Font("Courier", Font.ITALIC, 18), Color.GREEN, new MyIcon(), "A" },
        { new Font("Helvetica", Font.BOLD | Font.ITALIC, 12), Color.GRAY, new MyIcon(), "A" },
        { new Font("TimesRoman", Font.PLAIN, 32), Color.PINK, new MyIcon(), "A" },
        { new Font("Courier", Font.BOLD, 16), Color.YELLOW, new MyIcon(), "A" },
        { new Font("Helvetica", Font.ITALIC, 8), Color.DARK_GRAY, new MyIcon(), "A" } };

    JFrame frame = new JFrame("Complex Renderer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ListCellRenderer renderer = new ComplexCellRenderer();
    JComboBox comboBox = new JComboBox(elements);
    comboBox.setRenderer(renderer);
    frame.add(comboBox, BorderLayout.NORTH);
    
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}

class MyIcon implements Icon {

  public MyIcon() {
  }

  public int getIconHeight() {
    return 20;
  }

  public int getIconWidth() {
    return 20;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(Color.RED);
    g.drawRect(0, 0, 25, 25);
  }
}
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號