精华内容
下载资源
问答
  • jcombobox
    2021-03-08 14:26:25

    写在最前

    最近一段时间都十分忙,一直没有时间更新这边的文章,好在清明小假期终于能有一段调整的时间了,今日继续。

    摘要

    对于日常Swing开发,JComboBox添加事件响应是十分常见的工作内容之一。一般来说,常用的手段有addItemListener及addActionListener。那么两者异同在在什么地方?何时该用ItemListener,而又何时该用ActionListener呢?

    适用场景

    1. 当JComboBox选择内容发生变化时ItemListener会响应2次,而ActionListener会响应1次;

    2. 当JComboBox选择内容未发生变化时ItemListener会响应0次,而ActionListener会响应1次;

    示例代码:

    JComboBox combox = new JComboBox();

    combox.addItem("AAA");

    combox.addItem("BBB");

    combox.addItem("CCC");

    combox.addItemListener(e -> System.out.println("itemStateChanged"));

    combox.addActionListener(e -> System.out.println("actionPerformed"));

    现象:

    当第一次选择“BBB”时,输出为:

    itemStateChanged

    itemStateChanged

    actionPerformed

    当再一次选择“BBB”时,输出为:

    actionPerformed

    进一步分析

    替换实例代码如下:

    combox.addItemListener(e -> System.out.println(e));

    combox.addActionListener(e -> System.out.println(e));

    重复上述操作,当第一次选择“BBB”时,输出为:

    java.awt.event.ItemEvent[ITEM_STATE_CHANGED,item=AAA,stateChange=DESELECTED] on javax.swing.JComboBox[,0,0,196x74,layout=com.apple.laf.AquaComboBoxUI$AquaComboBoxLayoutManager,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=AAA]

    java.awt.event.ItemEvent[ITEM_STATE_CHANGED,item=BBB,stateChange=SELECTED] on javax.swing.JComboBox[,0,0,196x74,layout=com.apple.laf.AquaComboBoxUI$AquaComboBoxLayoutManager,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=BBB]

    java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=comboBoxChanged,when=1490977820123,modifiers=Button1] on javax.swing.JComboBox[,0,0,196x74,layout=com.apple.laf.AquaComboBoxUI$AquaComboBoxLayoutManager,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=BBB]

    当再一次选择“BBB”时,输出为:

    java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=comboBoxChanged,when=1490977820123,modifiers=Button1] on javax.swing.JComboBox[,0,0,196x74,layout=com.apple.laf.AquaComboBoxUI$AquaComboBoxLayoutManager,alignmentX=0.0,alignmentY=0.0,border=,flags=16777536,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=BBB]

    看到这里,响应次数区别的原因就一目了然了,之所以当选择项发生变化时ItemListener会响应2次的原因为:

    1. 当ItemEvent为DESELECTED及SELECTED时,ItemListener各响应了一次;

    2. 当ActionEvent的comboBoxChanged时ActionListener一定会响应一次的。

    总结

    ItemListener及ActionListener两者的异同如下:

    相同处:ItemListener ActionListener都是JCombobox的事件响应Listener;

    不同处

    选中项改变时ItemListener响应2次,选中项不变时ItemListener响应0次;

    选中项改变时ActionListener响应1次,选中项不变时ActionListener响应1次;

    ItemListener适用于因stateChange不同而进行不同事件响应的情况;

    ActionListener适用于不论选中项是否发生变化都需要事件响应的情况;

    更多相关内容
  • 主要介绍了Java Swing中的按钮(JButton)、组合框(JComboBox)、下拉列表(JList)和颜色选择器(JColorChooser)组件使用案例,需要的朋友可以参考下
  • 主要介绍了Java Swing组件下拉菜单控件JComboBox用法,结合具体实例形式分析了Swing组件下拉菜单控件JComboBox的具体定义、使用方法及相关使用注意事项,需要的朋友可以参考下
  • 主要介绍了Java Swing JComboBox下拉列表框的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • Swing开发之JComboBox

    2021-03-08 14:27:00
    JList和ComboBox很相似,因为这两个组件都显示一个项列表。因此,它们都有扩展ListModel接口的模型。而且,这两个组件都有绘制器,...JComboBox组件把编辑工作交给实现ComboBoxEdit接口的一个对象来处理。列表支持...

    JList和ComboBox很相似,因为这两个组件都显示一个项列表。因此,它们都有扩展ListModel接口的模型。而且,这两个组件都有绘制器,这些绘制器通过实现ListCellBenderer接口来绘制列表单元。

    但是,列表和组合框在施工方面还是有差别的。列表单是不可编辑的,但是组合框可以配备一个编辑器。JComboBox组件把编辑工作交给实现ComboBoxEdit接口的一个对象来处理。

    列表支持三个选取模式,并把选取工作实现ListSelectionModel接口的一个对象来处理。组合框在一个时刻只有一个可选取的项,而且选取工作由组合框模型来处理。另一方面,组合框支持键选取,即在某项上按下一下键就可以选取这个项,但列表不能这样做。

    构造函数

    JComboBox()

    创建具有默认数据模型的 JComboBox。

    JComboBox(ComboBoxModel aModel)

    创建一个 JComboBox,其项取自现有的 ComboBoxModel 中。

    JComboBox(Object[] items)

    创建包含指定数组中的元素的 JComboBox。

    JComboBox(Vector> items)

    创建包含指定 Vector 中的元素的 JComboBox。

    常用方法

    addActionListener(ActionListener l)

    添加 ActionListener。

    addItem(Object anObject)

    为项列表添加项。

    addItemListener(ItemListener aListener)

    添加 ItemListener。

    configureEditor(ComboBoxEditor anEditor, Object anItem)

    利用指定项初始化编辑器。

    getEditor()

    返回用于绘制和编辑 JComboBox 字段中所选项的编辑器。

    getItemAt(int index)

    返回指定索引处的列表项。

    getItemCount()

    返回列表中的项数。

    getModel()

    返回 JComboBox 当前使用的数据模型。

    getRenderer()

    返回用于显示 JComboBox 字段中所选项的渲染器。

    getSelectedIndex()

    返回列表中与给定项匹配的第一个选项。

    getSelectedItem()

    返回当前所选项。

    insertItemAt(Object anObject, int index)

    在项列表中的给定索引处插入项。

    isEditable()

    如果 JComboBox 可编辑,则返回 true。

    removeAllItems()

    从项列表中移除所有项。

    removeItem(Object anObject)

    从项列表中移除项。

    removeItemAt(int anIndex)

    移除 anIndex 处的项。

    setModel(ComboBoxModel aModel)

    设置 JComboBox 用于获取项列表的数据模型。

    setRenderer(ListCellRenderer aRenderer)

    设置渲染器,该渲染器用于绘制列表项和从 JComboBox 字段的列表中选择的项。

    setSelectedIndex(int anIndex)

    选择索引 anIndex 处的项。

    setSelectedItem(Object anObject)

    将组合框显示区域中所选项设置为参数中的对象。

    例 1:给JComboBox增加ItemListener和ActionListener

    import java.awt.BorderLayout;

    import java.awt.ItemSelectable;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import java.awt.event.ItemEvent;

    import java.awt.event.ItemListener;

    import javax.swing.JComboBox;

    import javax.swing.JFrame;

    public class ItemListenerSelectingComboSample {

    static private String selectedString(ItemSelectable is) {

    Object selected[] = is.getSelectedObjects();

    return ((selected.length == 0) ? "null" : (String) selected[0]);

    }

    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);

    comboBox.setEditable(true);

    comboBox.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {

    System.out.println("Selected index=" + ((JComboBox)e.getSource()).getItemCount());

    }

    });

    frame.add(comboBox, BorderLayout.SOUTH);

    ItemListener itemListener = new ItemListener() {

    public void itemStateChanged(ItemEvent itemEvent) {

    int state = itemEvent.getStateChange();

    System.out.println((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");

    System.out.println("Item: " + itemEvent.getItem());

    ItemSelectable is = itemEvent.getItemSelectable();

    System.out.println(", Selected: " + selectedString(is));

    }

    };

    comboBox.addItemListener(itemListener);

    frame.setSize(400, 200);

    frame.setVisible(true);

    }

    }

    例 2:采用模板创建JComboBox,同一个模板创建的两个不同JComboBox,对模板操作时两个JComboBox会同时改变

    import java.awt.BorderLayout;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    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);

    }

    }

    //JComboBox与JList共用一个模板

    import java.awt.BorderLayout;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import javax.swing.DefaultComboBoxModel;

    import javax.swing.JButton;

    import javax.swing.JComboBox;

    import javax.swing.JFrame;

    import javax.swing.JList;

    import javax.swing.JPanel;

    import javax.swing.JScrollPane;

    public class SharedDataBetweenComboBoxAndListSample {

    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);

    panel.add(comboBox1);

    frame.add(panel, BorderLayout.NORTH);

    JList jlist = new JList(model);

    JScrollPane scrollPane = new JScrollPane(jlist);

    frame.add(scrollPane, BorderLayout.CENTER);

    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);

    }

    }

    例 3:采用ArrayList组装JComboBox

    import java.awt.BorderLayout;

    import java.util.ArrayList;

    import java.util.Collection;

    import javax.swing.AbstractListModel;

    import javax.swing.ComboBoxModel;

    import javax.swing.JComboBox;

    import javax.swing.JFrame;

    class ArrayListComboBoxModel extends AbstractListModel implements ComboBoxModel {

    private Object selectedItem;

    private ArrayList anArrayList;

    public ArrayListComboBoxModel(ArrayList arrayList) {

    anArrayList = arrayList;

    }

    public Object getSelectedItem() {

    return selectedItem;

    }

    public void setSelectedItem(Object newValue) {

    selectedItem = newValue;

    }

    public int getSize() {

    return anArrayList.size();

    }

    public Object getElementAt(int i) {

    return anArrayList.get(i);

    }

    }

    public class ArrayListComboBoxModelDemo {

    public static void main(String args[]) {

    JFrame frame = new JFrame("ArrayListComboBoxModel");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ArrayList arrayList = new ArrayList();

    arrayList.add("A");

    arrayList.add("B");

    arrayList.add("C");

    ArrayListComboBoxModel model = new ArrayListComboBoxModel(arrayList);

    arrayList.add("A");

    arrayList.add("B");

    arrayList.add("C");

    JComboBox comboBox = new JComboBox(model);

    frame.add(comboBox, BorderLayout.NORTH);

    frame.setSize(300, 225);

    frame.setVisible(true);

    }

    }

    例 4:给JComboBox每项增加图片

    import java.awt.BorderLayout;

    import java.awt.Color;

    import java.awt.Component;

    import java.awt.Font;

    import java.awt.Graphics;

    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 ComplexRenderingSample {

    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,Swing开发之JComboBox篇, 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);

    }

    }

    例 5:改变JComboBox编辑框颜色

    import java.awt.BorderLayout;

    import java.awt.Color;

    import java.awt.Component;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    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 ColorComboBoxEditorDemo {

    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);

    }

    }

    例 6:编辑 JComboBox框,实现颜色切换

    import java.awt.BorderLayout;

    import java.awt.Color;

    import java.awt.Component;

    import java.awt.Dimension;

    import java.awt.event.ActionEvent;

    import java.awt.event.ActionListener;

    import javax.swing.ComboBoxEditor;

    import javax.swing.DefaultListCellRenderer;

    import javax.swing.JButton;

    import javax.swing.JColorChooser;

    import javax.swing.JComboBox;

    import javax.swing.JFrame;

    import javax.swing.JLabel;

    import javax.swing.JList;

    import javax.swing.ListCellRenderer;

    import javax.swing.border.LineBorder;

    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() {

    }

    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);

    }

    }

    }

    }

    class ColorCellRenderer implements ListCellRenderer {

    protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();

    // Width doesn't matter as the combo box will size

    private final static Dimension preferredSize = new Dimension(0, 20);

    public Component getListCellRendererComponent(JList list, Object value, int index,

    boolean isSelected, boolean cellHasFocus) {

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

    isSelected, cellHasFocus);

    if (value instanceof Color) {

    renderer.setBackground((Color) value);

    }

    if(cellHasFocus || isSelected){

    renderer.setBorder(new LineBorder(Color.DARK_GRAY));

    }else{

    renderer.setBorder(null);

    }

    renderer.setPreferredSize(preferredSize);

    return renderer;

    }

    }

    public class ColorComboBoxEditorRendererDemo {

    public static void main(String args[]) {

    Color colors[] = { Color.BLACK, Color.BLUE, Color.GREEN, Color.RED, Color.WHITE, Color.YELLOW };

    JFrame frame = new JFrame("Color JComboBox");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JComboBox comboBox = new JComboBox(colors);

    comboBox.setEditable(true);

    comboBox.setRenderer(new ColorCellRenderer());

    Color color = (Color) comboBox.getSelectedItem();

    ComboBoxEditor editor = new ColorComboBoxEditor(color);

    comboBox.setEditor(editor);

    frame.add(comboBox, BorderLayout.NORTH);

    final JLabel label = new JLabel();

    label.setOpaque(true);

    label.setBackground((Color) comboBox.getSelectedItem());

    frame.add(label, BorderLayout.CENTER);

    ActionListener actionListener = new ActionListener() {

    public void actionPerformed(ActionEvent actionEvent) {

    Color selectedColor = (Color) comboBox.getSelectedItem();

    label.setBackground(selectedColor);

    }

    };

    comboBox.addActionListener(actionListener);

    frame.setSize(300, 200);

    frame.setVisible(true);

    }

    }

    例 7:改变JComboBox旁边按钮样式

    import java.awt.BorderLayout;

    import javax.swing.JButton;

    import javax.swing.JComboBox;

    import javax.swing.JComponent;

    import javax.swing.JFrame;

    import javax.swing.plaf.ComboBoxUI;

    import javax.swing.plaf.ComponentUI;

    import javax.swing.plaf.basic.BasicArrowButton;

    import javax.swing.plaf.basic.BasicComboBoxUI;

    public class PopupComboSample {

    public static void main(String args[]) {

    String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

    JFrame frame = new JFrame("Popup JComboBox");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JComboBox comboBox = new JComboBox(labels);

    comboBox.setUI((ComboBoxUI) MyComboBoxUI.createUI(comboBox));

    frame.add(comboBox, BorderLayout.NORTH);

    frame.setSize(300, 200);

    frame.setVisible(true);

    }

    static class MyComboBoxUI extends BasicComboBoxUI {

    public static ComponentUI createUI(JComponent c) {

    return new MyComboBoxUI();

    }

    protected JButton createArrowButton() {

    JButton button = new BasicArrowButton(BasicArrowButton.WEST);

    return button;

    }

    }

    }

    展开全文
  • NULL 博文链接:https://jisonami.iteye.com/blog/2181450
  • JCombobox是Swing中比较常用的控件,它显示一个项列表,扩展的是ListModel接口的模型,它的显示绘制器通过实现ListCellBenderer接口来绘制列表单元,下面介绍 ①普通应用例子;②显示图片选项框例子;③修改下拉按钮的...

    JCombobox是Swing中比较常用的控件,它显示一个项列表,扩展的是ListModel接口的模型,它的显示绘制器通过实现ListCellBenderer接口来绘制列表单元,下面介绍 ①普通应用例子;②显示图片选项框例子;③修改下拉按钮的例子;④下拉框可选与否的例子.

    对于普通情况下使用JCombobox,没有什么注意事项,只需要把JCombobox new出来,设置它的Model的值就可以了.

    先看Sun给的官方的例子:

    341.jpg

    342.jpg

    具体的实现很简单:

    String[] petStrings = {"Bird","Cat","Dog","Rabbit","Pig"};

    //Create the combo box, select the item at index 4.

    JComboBox petList =newJComboBox(petStrings);

    petList.setSelectedIndex(4);

    petList.addActionListener(this);

    也可以通过petList.setEditable(true);设置是否可以编辑.对于Action的处理和普通的一样.

    JCombobox默认下拉显示和显示项是文本,为了显示其它内容比如图片或者更复杂的东西,则需要设置新的Renderer,JCombobox的Renderer需要实现ListCellRenderer接口.

    这个也比较简单,Sun官方也给了例子:

    343.jpg

    344.jpg

    具体的实现其实和普通的一样,先把JCombobox

    new出来,在使用setRenderer方法设置自己定义的Renderer就可以了.

    // Create the combo box.

    JComboBox petList =newJComboBox(intArray);

    ComboBoxRenderer renderer =newComboBoxRenderer();

    renderer.setPreferredSize(newDimension(200, 130));

    petList.setRenderer(renderer);

    当然这个Renderer是实现了ListCellRenderer接口的.

    privateclassComboBoxRendererextendsJLabelimplementsListCellRenderer {

    这样要是实现接口的方法:

    /*

    * This method finds the image and text corresponding to the

    selected

    * value and returns the label, set up to display the text and

    image.

    */

    @Override

    publicComponent

    getListCellRendererComponent(JList list, Object value,intindex,booleanisSelected,booleancellHasFocus) {

    然后然后this就是继承的JLabel了,对它可以设置属性了:

    setIcon(icon);

    setText(pet);

    最后把设置好的控件返回就可以了,

    returnthis;

    当然你也可以设置更复杂的控件,比如继承JButton可以设置成按钮的样式.

    Swing的MVC模式非常的好,当你需要更改控件的显示的时候只需要继承控件的基本UI,重写你需要重写的部位就可以了,这儿想下拉框的按钮不显示向下的箭头,只需要继承BasicComboBoxUI,重写createArrowButton方法就可以了.

    345.jpg

    重写UI

    privatestaticclassMyComboBoxUIextendsBasicComboBoxUI {

    publicstaticComponentUI createUI(JComponent c) {

    returnnewMyComboBoxUI();

    }

    @Override

    protectedJButton createArrowButton() {

    JButtonbutton=newBasicArrowButton(BasicArrowButton.EAST);

    returnbutton;

    }

    }

    当你需要修改JCombobox的UI的时候,只需要调用setUI方法就可以了.

    JComboBox comboBox =newJComboBox(labels);

    comboBox.setUI((ComboBoxUI)

    MyComboBoxUI.createUI(comboBox));

    对于修改JCombobox的显示可以从两个方向考虑,一个是修改MetalComboBoxUI,一个是继承ListCellRenderer.在通过设置UI和Renderer使界面修改.

    先看完成后的界面:

    346.jpg

    5c69f83fda33dc6521aa0e8a1ad94824.png

    工程的目录结构如下:

    2f6b9c30a538bd02238e5808f076f065.png

    先设置JCombobox下拉框是否有线,为了使以后扩展容易,设置为接口:

    /**

    *theinterfacethattheJComboBoxcanhavelineenable.

    */

    publicinterfaceLineEnable {

    /**

    *setbean.

    *@paramisLineEnable

    *isLineenable

    */

    publicvoidsetLineEnabled(booleanisLineEnable);

    /**

    *getbean.

    *@returnisLineenable

    */

    publicbooleanisLineEnabled();

    }

    同样的对于JCombobox下拉框是否可以选择也设置为接口:

    /**

    *theinterfacethattheJComboBoxcanselectenable.

    */

    publicinterfaceSelectEnable {

    /**

    *setbean.

    *@paramisSelectEnable

    *isSelectenable

    */

    publicvoidsetSelectEnabled(booleanisSelectEnable);

    /**

    *getbean.

    *@returnisSelectenable

    */

    publicbooleanisSelectEnabled();

    }

    当然需要别的属性,比如颜色、形状等也可以再设置相同的接口.

    对于JCombobox的没一个Item,都可以通过实现这些接口获得相应的显示:

    /**

    *theitemsthatyouwanttoshowinJComboBox.

    */

    publicclassMyComboBoxItemimplementsSelectEnable, LineEnable {

    对于特殊的JCombobox设置Item时,设置MyComboBoxItem就可以使Item具有选择可否和是否是线的样式.

    它具有3个属性:

    /**

    *JComboBoxitems.

    */

    privateObjectcomboxItem=null;

    /**

    *isselectenabled.

    */

    booleanisSelectEnabled=true;

    /**

    *islineenabled.

    */

    booleanisLineEnabled=false;

    可以通过设置它们得到JCombobox样式,这个类就是一个简单的Java Bean.

    然后就是设置JCombobox的选项的显示,实现ListCellRenderer接口,通过对组件的重写设置描绘它的新属性:

    /**

    *JComboBoxcellrenderer.

    */

    publicclassMyComboBoxRendererextendsJLabelimplementsListCellRenderer, ActionListener

    {

    重写它的方法:

    /**

    *Returnacomponentthathasbeenconfiguredtodisplaythespecified

    *value.

    */

    @Override

    publicComponent

    getListCellRendererComponent(JList list, Object value,intindex,booleanisSelected,booleancellHasFocus) {

    先设置它的显示

    String item = (value ==null) ?"": value.toString();

    再设置是否是线:

    if(((LineEnable) value).isLineEnabled()) {

    returnnewJSeparator(JSeparator.HORIZONTAL);

    }

    接着设置tooltip,提示是否可以显示:

    if(-1 < index) {

    if(((SelectEnable) value).isSelectEnabled()) {

    list.setToolTipText("You select is : "+ item);

    }else{

    list.setToolTipText("You cn't select : "+ item

    +", It

    select unEnable.");

    }

    }

    最后设置是否可以显示:

    if(!((SelectEnable)

    value).isSelectEnabled()) {

    setBackground(list.getBackground());     setForeground(UIManager.getColor("Label.disabledForeground"));

    }

    然后还是需要设置某些选择不可选时候的设置不可选:

    /**

    *Thelistenerinterfaceforreceivingactionevents.

    */

    publicvoidactionPerformed(ActionEvent e) {

    Object tempItem =combox.getSelectedItem();

    当是线的Item不可选,返回之前选项

    if(((LineEnable) tempItem).isLineEnabled()) {

    combox.setSelectedItem(currentItem);

    }else{

    currentItem= tempItem;

    }

    当是不可选的Item不可选,返回之前选项

    if(!((SelectEnable) tempItem).isSelectEnabled()) {

    combox.setSelectedItem(currentItem);

    }else{

    currentItem= tempItem;

    }

    }

    接下来的类就是设置JCombobox的UI了,

    /**

    *MetalUIforJComboBox.

    */

    publicclassMyComboBoxUIextendsMetalComboBoxUI {

    这里的UI设置主要是设置选择不可选的项时清除,并对JCombobox的下拉的菜单设置

    /**

    *showthepopupmenusize.

    */

    @Override

    publicvoidshow() {

    Dimension popupSize = ((MyComboBox)comboBox).getPopupSize();

    // reset size.

    popupSize.setSize(popupSize.width,

    getPopupHeightForRowCount(comboBox.getMaximumRowCount()));

    Rectangle popupBounds = computePopupBounds(0,comboBox

    .getBounds().height, popupSize.width, popupSize.height);

    // set max and mini size.

    scroller.setMaximumSize(popupBounds.getSize());

    scroller.setPreferredSize(popupBounds.getSize());

    scroller.setMinimumSize(popupBounds.getSize());

    // Invalidates the container.

    list.invalidate();

    // set select.

    intselectedIndex

    =comboBox.getSelectedIndex();

    if(selectedIndex

    == -1) {

    list.clearSelection();

    }else{

    list.setSelectedIndex(selectedIndex);

    }

    list.ensureIndexIsVisible(list.getSelectedIndex());

    setLightWeightPopupEnabled(comboBox.isLightWeightPopupEnabled());

    // show it.

    show(comboBox, popupBounds.x, popupBounds.y);

    }

    然后在UI的newBasicComboPopup(comboBox) {

    popup.getAccessibleContext().setAccessibleParent(comboBox);

    就可以了.

    最后的类就是自己的MyComboBox了,这个类其实也可以不要,只需要你在新建自己特殊的JCombobox时,不要忘记设置UI和传入的Item是MyComboBoxItem就可以了,这里为了方便自己实现了,以后使用时只需要New MyComboBox就可以了.

    /**

    *theJComboBoxthatithavesomeownmethod.

    */

    publicclassMyComboBoxextendsJComboBox {

    在构造函数里设置UI:

    setUI(newMyComboBoxUI());

    另外为了显示宽度合适,它提供了设置popupWidth的方法:

    publicDimension getPopupSize() {

    Dimension size = getSize();

    // reset size.

    if(popupWidth< 1) {

    popupWidth= size.width;

    }

    returnnewDimension(popupWidth, size.height);

    }

    这样一个属于自己的JComboBox就设置完成了,使用方法如下:

    MyComboBoxItem [] items = {newMyComboBoxItem("Astart"),

    newMyComboBoxItem("BGold",true,true),

    newMyComboBoxItem("ilove",false),

    newMyComboBoxItem("fire

    your game",true),

    newMyComboBoxItem("",true,true),

    newMyComboBoxItem("NIHA",false),

    newMyComboBoxItem("生活"),

    newMyComboBoxItem("",false,true) };

    JComboBoxjComboBox=newMyComboBox(items);

    jComboBox.setRenderer(newMyComboBoxRenderer(jComboBox));

    以后就可以当做一个普通的Java控件使用了.

    展开全文
  • 本文整理匯總了Java中javax.swing.JComboBox.setEditable方法的典型用法代碼示例。如果您正苦於以下問題:Java JComboBox.setEditable方法的具體用法?Java JComboBox.setEditable怎麽用?Java JComboBox....

    本文整理匯總了Java中javax.swing.JComboBox.setEditable方法的典型用法代碼示例。如果您正苦於以下問題:Java JComboBox.setEditable方法的具體用法?Java JComboBox.setEditable怎麽用?Java JComboBox.setEditable使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.swing.JComboBox的用法示例。

    在下文中一共展示了JComboBox.setEditable方法的19個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Java代碼示例。

    示例1: addChoice

    ​點讚 3

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    /** Create a choice menu.

    * @param name The name used to identify the entry (when calling get).

    * @param label The label to attach to the entry.

    * @param values The list of possible choices.

    * @param defaultChoice Default choice.

    * @param editable True if an arbitrary choice can be entered, in addition

    * to the choices in values.

    * @param background The background color for the editable part.

    */

    public void addChoice(

    String name,

    String label,

    String[] values,

    String defaultChoice,

    boolean editable,

    Color background) {

    JLabel lbl = new JLabel(label + ": ");

    lbl.setBackground(_background);

    JComboBox combobox = new JComboBox(values);

    combobox.setEditable(editable);

    // FIXME: Typical of Swing, the following does not set

    // the background color. How does one set the background

    // color?

    combobox.setBackground(background);

    combobox.setSelectedItem(defaultChoice);

    _addPair(name, lbl, combobox, combobox);

    // Add the listener last so that there is no notification

    // of the first value.

    combobox.addItemListener(new QueryItemListener(name));

    }

    開發者ID:OpenDA-Association,項目名稱:OpenDA,代碼行數:31,

    示例2: addAndGetKeyForGlobalData

    ​點讚 3

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    private Object[] addAndGetKeyForGlobalData(GlobalDataModel gdModel) {

    Object[] objects = new Object[2];

    JComboBox jcb = new JComboBox(gdModel.getKeys().toArray());

    jcb.setEditable(true);

    JOptionPane.showMessageDialog(null, jcb, "Select or Enter a GlobalId", JOptionPane.QUESTION_MESSAGE);

    String key = Objects.toString(jcb.getSelectedItem(), "");

    if (key.trim().isEmpty()) {

    key = "#gd1";

    } else if (!key.startsWith("#")) {

    key = "#" + key;

    }

    objects[0] = key;

    if (gdModel.getRowCount() == 0

    || !gdModel.getKeys().contains(key)) {

    gdModel.addRecord();

    gdModel.setValueAt(key, gdModel.getRowCount() - 1, 0);

    objects[1] = gdModel.getRowCount() - 1;

    } else if (gdModel.getKeys().contains(key)) {

    objects[1] = gdModel.getRecordIndexByKey(key);

    }

    return objects;

    }

    開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:26,

    示例3: confirm

    ​點讚 3

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    public void confirm(EventObject fe) {

    JTextField tf = (JTextField) fe.getSource();

    JComboBox combo = (JComboBox) tf.getParent();

    if (combo==null)

    return;

    if (fe instanceof FocusEvent) {

    combo.getEditor().getEditorComponent().removeFocusListener(this);

    } else {

    combo.getEditor().getEditorComponent().removeKeyListener(this);

    }

    Configuration config = lastSelected;

    config.setDisplayName(tf.getText());

    combo.setSelectedItem(config);

    combo.setEditable(false);

    currentActiveItem = null;

    }

    開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:17,

    示例4: InputDataPanel

    ​點讚 3

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    public InputDataPanel(List previouslyUsedURLs) {

    setSize(new Dimension(900, 300));

    setPreferredSize(new Dimension(900, 300));

    setMinimumSize(new Dimension(450, 300));

    setLayout(null);

    JLabel lblInputDataUrl = new JLabel("Input data URL");

    lblInputDataUrl.setBounds(12, 12, 105, 15);

    add(lblInputDataUrl);

    lblUrlIsInvalid = new JLabel("URL is invalid!");

    lblUrlIsInvalid.setVisible(false);

    lblUrlIsInvalid.setBounds(12, 70, 105, 15);

    add(lblUrlIsInvalid);

    btnValidate = new JButton("Validate");

    btnValidate.setBounds(335, 34, 93, 25);

    //add(btnValidate);

    comboBox = new JComboBox();

    comboBox.setEditable(true);

    comboBox.setBounds(12, 34, 311, 24);

    comboBox.setModel(new URLComboBoxModel(previouslyUsedURLs));

    add(comboBox);

    }

    開發者ID:roscisz,項目名稱:KernelHive,代碼行數:26,

    示例5: confirm

    ​點讚 3

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    private void confirm(EventObject fe) {

    JTextField tf = (JTextField) fe.getSource();

    JComboBox combo = (JComboBox) tf.getParent();

    if (combo==null)

    return;

    if (fe instanceof FocusEvent) {

    combo.getEditor().getEditorComponent().removeFocusListener(this);

    } else {

    combo.getEditor().getEditorComponent().removeKeyListener(this);

    }

    Configuration config = configName==null ?

    ConfigurationsManager.getDefault().duplicate(lastSelected, tf.getText(), tf.getText()):

    ConfigurationsManager.getDefault().create(tf.getText(), tf.getText());

    combo.setSelectedItem(config);

    combo.setEditable(false);

    }

    開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:17,

    示例6: createAndShowGUI

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    private static void createAndShowGUI() {

    frame = new JFrame();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setSize(200, 200);

    frame.setLocation(100, 100);

    table = new JTable(

    new String[][]{{TEST1}}, new String[]{"Header"});

    JComboBox comboBox = new JComboBox<>();

    comboBox.setEditable(true);

    table.getColumnModel().getColumn(0).setCellEditor(

    new DefaultCellEditor(comboBox));

    frame.getContentPane().add(table);

    frame.setVisible(true);

    }

    開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:16,

    示例7: getCellEditor

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    @Override

    public TableCellEditor getCellEditor(int row, int column) {

    JComboBox typeBox = new JComboBox(Attributes.KNOWN_ATTRIBUTE_TYPES);

    typeBox.setEditable(true);

    typeBox.setBackground(javax.swing.UIManager.getColor("Table.cellBackground"));

    return new DefaultCellEditor(typeBox);

    }

    示例8: actionPerformed

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    @Override

    public void actionPerformed(ActionEvent ae) {

    currentActiveItem = this;

    JComboBox combo = (JComboBox) ae.getSource();

    combo.setEditable(true);

    combo.getEditor().getEditorComponent().addFocusListener(this);

    combo.getEditor().getEditorComponent().addKeyListener(this);

    combo.addPopupMenuListener(this);

    combo.setSelectedItem(configName == null ? lastSelected + "1" : configName);

    }

    開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:12,

    示例9: AccountTransferDialog

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    /**

    * Set up and show the dialog. The first Component argument determines which

    * frame the dialog depends on; it should be a component in the dialog's

    * controlling frame. The second Component argument should be null if you

    * want the dialog to come up with its left corner in the center of the

    * screen; otherwise, it should be the component on top of which the dialog

    * should appear.

    */

    public AccountTransferDialog(Component frameComp, Component locationComp,

    String title, Object[] brokers,I_TickerManager tickerManager) {

    super(frameComp, locationComp, title, tickerManager);

    brokerList = new JComboBox(brokers);

    brokerList.setEditable(true);

    brokerList.setSelectedIndex(0);

    newBrokerField = new JTextField(FIELD_LEN);

    newBrokerField.setEditable(true);

    newBrokerField.setText("");

    newBrokerField.addKeyListener(this);

    dateFieldLabel = new JLabel("Siirtopäivä: ");

    dateFieldLabel.setLabelFor(dateChooser);

    brokerFieldLabel = new JLabel("Vanha välittäjä: ");

    brokerFieldLabel.setLabelFor(brokerList);

    newBrokerFieldLabel = new JLabel("Uusi välittäjä: ");

    newBrokerFieldLabel.setLabelFor(newBrokerField);

    init(getDialogLabels(), getDialogComponents());

    }

    開發者ID:skarna1,項目名稱:javaportfolio,代碼行數:35,

    示例10: setupGui

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    private void setupGui()

    {

    JLabel typeLabel = new JLabel(CurrentLocale.get("com.tle.admin.schema.manager.transformdialog.name")); //$NON-NLS-1$

    JLabel fileLabel = new JLabel(CurrentLocale.get("com.tle.admin.schema.manager.transformdialog.xsl")); //$NON-NLS-1$

    schemaType = new JComboBox();

    schemaType.setEditable(true);

    fileSelector = new FileSelector(CurrentLocale.get("com.tle.admin.schema.manager.transformdialog.browse")); //$NON-NLS-1$

    fileSelector.setFileFilter(FileFilterAdapter.XSLT());

    ok = new JButton(CurrentLocale.get("com.tle.admin.ok")); //$NON-NLS-1$

    JButton cancel = new JButton(CurrentLocale.get("com.tle.admin.cancel")); //$NON-NLS-1$

    ok.addActionListener(this);

    cancel.addActionListener(this);

    final int height1 = typeLabel.getPreferredSize().height;

    final int height2 = schemaType.getPreferredSize().height;

    final int height3 = fileSelector.getPreferredSize().height;

    final int height4 = ok.getPreferredSize().height;

    final int width1 = cancel.getPreferredSize().width;

    final int[] rows = {height1, height2, height1, height3, height4,};

    final int[] cols = {TableLayout.FILL, width1, width1,};

    all = new JPanel(new TableLayout(rows, cols));

    all.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    all.add(typeLabel, new Rectangle(0, 0, 3, 1));

    all.add(schemaType, new Rectangle(0, 1, 3, 1));

    all.add(fileLabel, new Rectangle(0, 2, 3, 1));

    all.add(fileSelector, new Rectangle(0, 3, 3, 1));

    all.add(ok, new Rectangle(1, 4, 1, 1));

    all.add(cancel, new Rectangle(2, 4, 1, 1));

    }

    開發者ID:equella,項目名稱:Equella,代碼行數:36,

    示例11: DataComboBoxSupport

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    /** Not private because used in tests. */

    DataComboBoxSupport(JComboBox comboBox, DataComboBoxModel dataModel, boolean allowAdding) {

    this.dataModel = dataModel;

    this.allowAdding = allowAdding;

    comboBox.setEditable(false);

    comboBox.setModel(new ItemComboBoxModel());

    comboBox.setRenderer(new ItemListCellRenderer());

    comboBox.addActionListener(new ItemActionListener());

    comboBox.addPopupMenuListener(new ItemPopupMenuListener());

    }

    開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:14,

    示例12: initAntTargetEditor

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    private void initAntTargetEditor(List targets) {

    JComboBox combo = new JComboBox();

    combo.setEditable(true);

    for (String target : targets) {

    combo.addItem(target);

    }

    customTargets.setDefaultEditor(JComboBox.class, new DefaultCellEditor(combo));

    }

    開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:9,

    示例13: setEmptyModel

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    private void setEmptyModel(JComboBox combo) {

    if (combo != null) {

    combo.setModel(WizardUtils.createComboEmptyModel());

    combo.setEnabled(false);

    combo.setEditable(false);

    checkValidity();

    }

    }

    開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:9,

    示例14: CapitalRepaymentDialog

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    /**

    * Set up and show the dialog. The first Component argument determines which

    * frame the dialog depends on; it should be a component in the dialog's

    * controlling frame. The second Component argument should be null if you

    * want the dialog to come up with its left corner in the center of the

    * screen; otherwise, it should be the component on top of which the dialog

    * should appear.

    */

    public CapitalRepaymentDialog(Component frameComp, Component locationComp,

    String title, Object[] brokers, Object[] sectors,

    Map> stocks, I_TickerManager tickerManager) {

    super(frameComp, locationComp, title, tickerManager);

    this.stocks = stocks;

    // Brokers

    brokerList = new JComboBox(brokers);

    brokerList.setEditable(true);

    // Sectors

    sectorList = new JComboBox(sectors);

    sectorList.setActionCommand(SECTOR_CHANGED);

    sectorList.addActionListener(this);

    // Stocks

    stocksList = new JComboBox();

    updateStockList((String) sectorList.getSelectedItem());

    stocksList.setActionCommand(STOCK_SELECTED);

    stocksList.addActionListener(this);

    amountField.addKeyListener(this);

    costField.addKeyListener(this);

    totalCostField.setEditable(false);

    totalCostField.setText("0.00");

    sectorFieldLabel = new JLabel("Toimiala: ");

    sectorFieldLabel.setLabelFor(sectorList);

    stockFieldLabel = new JLabel("Arvopaperi: ");

    stockFieldLabel.setLabelFor(stocksList);

    dateFieldLabel = new JLabel("Maksupäivä: ");

    dateFieldLabel.setLabelFor(dateChooser);

    amountFieldLabel = new JLabel("Määrä: ");

    amountFieldLabel.setLabelFor(amountField);

    costFieldLabel = new JLabel("Palautus/osake: ");

    costFieldLabel.setLabelFor(costField);

    brokerFieldLabel = new JLabel("Välittäjä: ");

    brokerFieldLabel.setLabelFor(brokerList);

    totalCostFieldLabel = new JLabel("yhteensä: ");

    totalCostFieldLabel.setLabelFor(totalCostField);

    String stockName = (String) stocksList.getSelectedItem();

    updateRateField(stockName);

    init(getDialogLabels(), getDialogComponents());

    }

    開發者ID:skarna1,項目名稱:javaportfolio,代碼行數:65,

    示例15: ClassTable

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    ClassTable() {

    super(new ClassTableModel());

    disabledCellRenderer = new DisabledCellRenderer();

    //BEGIN Federico Dall'Orso 8/3/2005

    //NEW

    classTypeComboBoxCell = new ComboBoxCell(CLASS_TYPENAMES);

    deleteButton = new JButton(deleteOneClass);

    deleteButtonCellRenderer = new ButtonCellEditor(deleteButton);

    enableDeletes();

    rowHeader.setRowHeight(18);

    setRowHeight(18);

    //END Federico Dall'Orso 8/3/2005

    JComboBox classTypeBox = new JComboBox(CLASS_TYPENAMES);

    classTypeCellEditor = new DefaultCellEditor(classTypeBox);

    classTypeBox.setEditable(false);

    setColumnSelectionAllowed(false);

    setRowSelectionAllowed(true);

    // not beautiful, but effective. See ClassTableModel.getColumnClass()

    setDefaultRenderer(DisabledCellRenderer.class, disabledCellRenderer);

    setDefaultEditor(String.class, classTypeCellEditor);

    setDisplaysScrollLabels(true);

    installKeyboardAction(getInputMap(), getActionMap(), deleteClass);

    mouseHandler = new ExactTable.MouseHandler(makeMouseMenu());

    mouseHandler.install();

    help.addHelp(this,

    "Click or drag to select classes; to edit data single-click and start typing. Right-click for a list of available operations");

    help.addHelp(moreRowsLabel, "There are more classes: scroll down to see them");

    help.addHelp(selectAllButton, "Click to select all classes");

    tableHeader.setToolTipText(null);

    rowHeader.setToolTipText(null);

    help.addHelp(rowHeader, "Click, SHIFT-click or drag to select classes");

    }

    開發者ID:HOMlab,項目名稱:QN-ACTR-Release,代碼行數:42,

    示例16: SubscriptionDialog

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    /**

    * Set up and show the dialog. The first Component argument determines which

    * frame the dialog depends on; it should be a component in the dialog's

    * controlling frame. The second Component argument should be null if you

    * want the dialog to come up with its left corner in the center of the

    * screen; otherwise, it should be the component on top of which the dialog

    * should appear.

    */

    public SubscriptionDialog(Component frameComp, Component locationComp, String title,

    Object[] brokers, Object[] sectors, Map> stocks, I_TickerManager tickerManager) {

    super(frameComp, locationComp, title, tickerManager);

    this.stocks = stocks;

    // Brokers

    brokerList = new JComboBox(brokers);

    brokerList.setEditable(true);

    // Sectors

    sectorList = new JComboBox(sectors);

    sectorList.setActionCommand(SECTOR_CHANGED);

    sectorList.addActionListener(this);

    // Stocks

    stocksList = new JComboBox();

    updateStockList((String) sectorList.getSelectedItem());

    stocksList.setActionCommand(STOCK_SELECTED);

    stocksList.addActionListener(this);

    amountField.addKeyListener(this);

    costField.addKeyListener(this);

    taxPurchaseDateChooser = new JDateChooser(Calendar.getInstance().getTime());

    taxPurchaseDateChooser.setLocale(new Locale("fi", "FI"));

    totalCostField.setEditable(false);

    totalCostField.setText("0.00");

    sectorFieldLabel = new JLabel("Toimiala: ");

    sectorFieldLabel.setLabelFor(sectorList);

    stockFieldLabel = new JLabel("Arvopaperi: ");

    stockFieldLabel.setLabelFor(stocksList);

    dateFieldLabel = new JLabel("Merkintäpäivä: ");

    dateFieldLabel.setLabelFor(dateChooser);

    taxDateFieldLabel= new JLabel("Hankintapäivä verotuksessa: ");

    taxDateFieldLabel.setLabelFor(taxPurchaseDateChooser);

    amountFieldLabel = new JLabel("Määrä: ");

    amountFieldLabel.setLabelFor(amountField);

    costFieldLabel = new JLabel("Merkintähinta: ");

    costFieldLabel.setLabelFor(costField);

    brokerFieldLabel = new JLabel("Välittäjä: ");

    brokerFieldLabel.setLabelFor(brokerList);

    totalCostFieldLabel = new JLabel("yhteensä: ");

    totalCostFieldLabel.setLabelFor(totalCostField);

    init(getDialogLabels(), getDialogComponents());

    }

    開發者ID:skarna1,項目名稱:javaportfolio,代碼行數:67,

    示例17: StationTable

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    StationTable() {

    super(new StationTableModel());

    //BEGIN Federico Dall'Orso 8/3/2005

    //station type cell renderers

    //NEW

    LD_disabled_StationTypeCell = new ComboBoxCell(STATION_TYPENAMES);

    LD_disabled_StationTypeCell.getComboBox().setEnabled(false);

    LD_enabled_StationTypeCell = new ComboBoxCell(STATION_TYPENAMES_LD_ENABLED);

    LD_enabled_StationTypeCell.getComboBox().setEnabled(false);

    //14/3/2005

    deleteButton = new JButton(deleteOneStation);

    deleteButtonCellRenderer = new ButtonCellEditor(deleteButton);

    enableDeletes();

    rowHeader.setRowHeight(CommonConstants.ROW_HEIGHT);

    setRowHeight(CommonConstants.ROW_HEIGHT);

    //END Federico Dall'Orso

    /* a station type cell editor for open/mixed systems */

    JComboBox stationTypeBox = new JComboBox(STATION_TYPENAMES);

    stationTypeBox.setEditable(false);

    stationTypeBox.setEnabled(false);

    LD_disabled_StationTypeEditor = new DefaultCellEditor(stationTypeBox);

    stationTypeBox.setEnabled(false);

    /* a station type cell editor for closed systems */

    JComboBox LD_enabled_StationTypeBox = new JComboBox(STATION_TYPENAMES_LD_ENABLED);

    LD_enabled_StationTypeBox.setEditable(false);

    LD_enabled_StationTypeBox.setEnabled(false);

    LD_enabled_StationTypeEditor = new DefaultCellEditor(LD_enabled_StationTypeBox);

    LD_enabled_StationTypeBox.setEnabled(false);

    setColumnSelectionAllowed(false);

    setRowSelectionAllowed(true);

    setDisplaysScrollLabels(true);

    installKeyboardAction(getInputMap(), getActionMap(), deleteStation);

    mouseHandler = new ExactTable.MouseHandler(makeMouseMenu());

    mouseHandler.install();

    help.addHelp(this,

    "Click or drag to select stations; to edit data single-click and start typing. Right-click for a list of available operations");

    help.addHelp(moreRowsLabel, "There are more stations: scroll down to see them");

    help.addHelp(selectAllButton, "Click to select all stations");

    tableHeader.setToolTipText(null);

    rowHeader.setToolTipText(null);

    help.addHelp(rowHeader, "Click, SHIFT-click or drag to select stations");

    }

    開發者ID:max6cn,項目名稱:jmt,代碼行數:52,

    示例18: StationTable

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    StationTable() {

    super(new StationTableModel());

    //BEGIN Federico Dall'Orso 8/3/2005

    //station type cell renderers

    //NEW

    LD_disabled_StationTypeCell = new ComboBoxCell(STATION_TYPENAMES);

    LD_enabled_StationTypeCell = new ComboBoxCell(STATION_TYPENAMES_LD_ENABLED);

    //14/3/2005

    deleteButton = new JButton(deleteOneStation);

    deleteButtonCellRenderer = new ButtonCellEditor(deleteButton);

    enableDeletes();

    rowHeader.setRowHeight(18);

    setRowHeight(18);

    //END Federico Dall'Orso

    /* a station type cell editor for open/mixed systems */

    JComboBox stationTypeBox = new JComboBox(STATION_TYPENAMES);

    stationTypeBox.setEditable(false);

    LD_disabled_StationTypeEditor = new DefaultCellEditor(stationTypeBox);

    /* a station type cell editor for closed systems */

    JComboBox LD_enabled_StationTypeBox = new JComboBox(STATION_TYPENAMES_LD_ENABLED);

    LD_enabled_StationTypeBox.setEditable(false);

    LD_enabled_StationTypeEditor = new DefaultCellEditor(LD_enabled_StationTypeBox);

    setColumnSelectionAllowed(false);

    setRowSelectionAllowed(true);

    setDisplaysScrollLabels(true);

    installKeyboardAction(getInputMap(), getActionMap(), deleteStation);

    mouseHandler = new ExactTable.MouseHandler(makeMouseMenu());

    mouseHandler.install();

    help.addHelp(this,

    "Click or drag to select stations; to edit data single-click and start typing. Right-click for a list of available operations");

    help.addHelp(moreRowsLabel, "There are more stations: scroll down to see them");

    help.addHelp(selectAllButton, "Click to select all stations");

    tableHeader.setToolTipText(null);

    rowHeader.setToolTipText(null);

    help.addHelp(rowHeader, "Click, SHIFT-click or drag to select stations");

    }

    開發者ID:HOMlab,項目名稱:QN-ACTR-Release,代碼行數:44,

    示例19: ClassTable

    ​點讚 2

    import javax.swing.JComboBox; //導入方法依賴的package包/類

    ClassTable() {

    super(new ClassTableModel());

    setName("ClassTable");

    disabledCellRenderer = new DisabledCellRenderer();

    //BEGIN Federico Dall'Orso 8/3/2005

    //NEW

    classTypeComboBoxCell = new ComboBoxCell(CLASS_TYPENAMES);

    deleteButton = new JButton(deleteOneClass);

    deleteButtonCellRenderer = new ButtonCellEditor(deleteButton);

    enableDeletes();

    rowHeader.setRowHeight(CommonConstants.ROW_HEIGHT);

    setRowHeight(CommonConstants.ROW_HEIGHT);

    //END Federico Dall'Orso 8/3/2005

    JComboBox classTypeBox = new JComboBox(CLASS_TYPENAMES);

    classTypeCellEditor = new DefaultCellEditor(classTypeBox);

    classTypeBox.setEditable(false);

    setColumnSelectionAllowed(false);

    setRowSelectionAllowed(true);

    // not beautiful, but effective. See ClassTableModel.getColumnClass()

    setDefaultRenderer(DisabledCellRenderer.class, disabledCellRenderer);

    setDefaultEditor(String.class, classTypeCellEditor);

    setDisplaysScrollLabels(true);

    installKeyboardAction(getInputMap(), getActionMap(), deleteClass);

    mouseHandler = new ExactTable.MouseHandler(makeMouseMenu());

    mouseHandler.install();

    help.addHelp(this,

    "Click or drag to select classes; to edit data single-click and start typing. Right-click for a list of available operations");

    help.addHelp(moreRowsLabel, "There are more classes: scroll down to see them");

    help.addHelp(selectAllButton, "Click to select all classes");

    tableHeader.setToolTipText(null);

    rowHeader.setToolTipText(null);

    help.addHelp(rowHeader, "Click, SHIFT-click or drag to select classes");

    }

    開發者ID:max6cn,項目名稱:jmt,代碼行數:43,

    注:本文中的javax.swing.JComboBox.setEditable方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

    展开全文
  • 參考資料:問題的產生:在看JComboBox組件的監聽事件時,運行講解到的實例(增加了幾個輸出語句來跟蹤它的反應)碰到下面的問題:1,JComboBox組件在添加了ActionListener和ItemListener監聽器時,兩個監聽器都對...
  • JComboBox自动过滤,很好用~,能添加到swing,无ui限制
  • JComboBox下拉框多选

    热门讨论 2012-04-25 23:31:45
    一个多选的JComboBox完整例子,JComboBox下面包含JCheckBox
  • 参考资料:问题的产生:在看JComboBox组件的监听事件时,运行讲解到的实例(增加了几个输出语句来跟踪它的反应)碰到下面的问题:1,JComboBox组件在添加了ActionListener和ItemListener监听器时,两个监听器都对...
  • Swing JComboBox

    2021-03-08 14:26:35
    JComboBox类是一个组合按钮或可编辑字段和下拉列表的组件。类声明以下是javax.swing.JComboBox类的声明 -public class JComboBoxextends JComponentimplements ItemSelectable, ListDataListener, ActionListener, ...
  • 本文整理匯總了Java中javax.swing.JComboBox.getSelectedItem方法的典型用法代碼示例。如果您正苦於以下問題:Java JComboBox.getSelectedItem方法的具體用法?Java JComboBox.getSelectedItem怎麽用?Java ...
  • JComboBox 多选

    千次阅读 2018-05-01 00:38:05
    import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.ListCellRenderer; import javax....
  • combobox_privince.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { JComboBox source = (JComboBox) evt.getSource(); //根据获取的省份找到它下面的级别的市 String ...
  • JComboBox宽度

    2021-07-16 23:11:48
    I have created a jComboBox but it takes the full width of the frame. how to set the width fixed.yes borderlayout for the frame and box layout for the panel. i am adding the code here:import javax.swi....
  • [ XJTUSE ]JAVA语言基础知识——7.10 JList、JComboBox实现列表框
  • import javax.swing.JComboBox; import java.awt.event.ActionListener; import java.sql.*; import java.util.*; import javax.swing.DefaultComboBoxModel; import javax.swing.JOptionPane; public class Update_...
  • 过去重写过几次JComboBox类,都是实现了自动匹配输入更改下拉框选项的功能,但是与之前的所写的程序的耦合度太高,因此便想要重写一个实现功能的同时还是高内聚的JComboBox类。 原本的下拉框数据: 未输入时: / ...
  • JComboBox comboBox可以实现下拉菜单,可以作用于给用户提供选项 一、JComboBox下拉列表的用法总结 声明一个JComboBox类的语法比较特殊,有点类似列表的声明,举例如下 JComboBox<String> cb = new JComboBox();...
  • Java的JComboBox详解

    万次阅读 多人点赞 2019-01-07 09:28:47
    将按钮或可编辑字段与下拉列表组合的组件。用户可以从下拉列表中选择值,下拉列表在用户请求时显示。如果使组合框处于可编辑状态,则组合框将包括用户可在...  此类实现 JComboBox 类的可访问性支持。 static...
  • 自己写的一个中国省市区三级联动,本来想打包成jar的,但是xml不知道为什么没跟进来,所有把所有代码贴上了
  • 本文整理匯總了Java中javax.swing.JComboBox.setSelectedIndex方法的典型用法代碼示例。如果您正苦於以下問題:Java JComboBox.setSelectedIndex方法的具體用法?Java JComboBox.setSelectedIndex怎麽用?Java ...
  • JComboBox

    2015-06-01 23:15:00
    package swing.combox; import java.awt.FlowLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; public class JcomboxDemo...
  • I'm trying to listen to a change of selection in a Java JComboBox. I have tried to use an ActionListener but the problem is this: the action listener does something like thispublic void actionPerforme...
  • java 中jcombobox怎么用

    2021-02-12 13:21:56
    1. 构造方法:* JComboBox() 建立一个JComboBox组件.* JComboBox(ComboBoxModel model) 根据model建立一个JComboBox组件.* JComboBox(Objext[] items) 利用数组对象建立一个JComboBox组件.* JComboBox(Vector items) ...
  • JComboBox的下拉按钮添加监听

    千次阅读 2020-12-27 21:54:29
    JComboBox的下拉按钮添加监听JComboBox的下拉按钮添加监听1.问题描述2.需求分析3.代码示例4.结果演示 JComboBox的下拉按钮添加监听 系统:Win10 JDK:1.8.0_121 IDEA:2017.3.2 1.问题描述 在使用一个JComboBox...
  • Java程序设计 图形用户界面 【十二】下拉列表JComboBox 下拉列表JComboBox JList是以列表框的形式进行显示的 有列表又可以自己输入数据这种组件就称为下拉列表框 JComboBox类可以完成这样的功能 JComboBox类的常用...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 10,915
精华内容 4,366
关键字:

jcombobox