如何配置JComboBox创建时不选择FIRST元素? [英] How to configure JComboBox not to select FIRST element when created?

查看:37
本文介绍了如何配置JComboBox创建时不选择FIRST元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

更新:

通过Java SE 6 API:

From the Java SE 6 API:

公共JComboBox()创建一个JComboBox 使用默认数据模型.默认值 数据模型是的空列表 对象.使用addItem添加项目. 通过 默认数据中的第一项 型号已选定.

public JComboBox() Creates a JComboBox with a default data model. The default data model is an empty list of objects. Use addItem to add items. By default the first item in the data model becomes selected.

因此,我将API更改为JComboBox(model):

So I changed to JComboBox(model) as the API says:

公共JComboBox(ComboBoxModel aModel) 创建一个JComboBox,将其 现有ComboBoxModel中的项目. 由于提供了ComboBoxModel,因此 使用此创建的组合框 构造函数不创建默认值 组合框模型,并且可能会影响 插入,删除和添加方法的行为.

public JComboBox(ComboBoxModel aModel) Creates a JComboBox that takes its items from an existing ComboBoxModel. Since the ComboBoxModel is provided, a combo box created using this constructor does not create a default combo box model and may impact how the insert, remove and add methods behave.

我尝试了以下操作:

    DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.setSelectedItem(null);
    suggestionComboBox = new JComboBox(model);
    suggestionComboBox.setModel(model);

但是无法正常工作,仍在选择第一项.

But could not get it to work, the first item is still being selected.

任何能提出实际工作示例的人都会非常感激.

Anyone that can come up with a working example would be very much appreciated.

帖子的旧部分:

我正在使用JComboBox,并尝试在我的代码中使用setSelectionIndex(-1)(此代码位于caretInvoke()中)

I am using JComboBox, and tried using setSelectionIndex(-1) in my code (this code is placed in caretInvoke())

suggestionComboBox.removeAllItems();
    for (int i = 0; i < suggestions.length; i++) {
        suggestionComboBox.addItem(suggestions[i]);
    }
    suggestionComboBox.setSelectedIndex(-1);
    suggestionComboBox.setEnabled(true);

这是添加到窗格中时的初始设置:

This is the initial setting when it was added to a pane:

    suggestionComboBox = new JComboBox();
    suggestionComboBox.setEditable(false);
    suggestionComboBox.setPreferredSize(new Dimension(25, 25));
    suggestionComboBox.addActionListener(new SuggestionComboBoxListener());

当caretInvoke触发ComboBox初始化时,即使在用户选择元素之前,actionPerformed也已经触发(我在这里尝试了JOptionPane): http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo1.png http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo2.png http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo3.png

When the caretInvoke triggers the ComboBox initialisation, even before the user selects an element, the actionPerformed is already triggered (I tried a JOptionPane here): http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo1.png http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo2.png http://i126.photobucket.com/albums/p109/eXPeri3nc3/StackOverflow/combo3.png

问题是:当用户从ComboBox中选择一个元素时,我的程序会自动插入选定的文本.因此,无需用户选择任何内容,它就会自动插入.

The problem is: My program autoinserts the selected text when the user selects an element from the ComboBox. So without the user selecting anything, it is automatically inserted already.

这是我的SSCCE :(最后)

Here is my SSCCE: (finally)

package components;


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;

public class Temp extends JFrame {

    JTextPane textPane;
    AbstractDocument doc;
    JTextArea changeLog;
    String newline = "\n";
    private JComboBox suggestionComboBox;
    private JPanel suggestionPanel;
    private JLabel suggestionLabel;
    private JButton openButton, saveButton, aboutButton;

    public Temp() {
        super("Snort Ruleset IDE");
        //Create the text pane and configure it.
        textPane = new JTextPane();
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5, 5, 5, 5));
        StyledDocument styledDoc = textPane.getStyledDocument();
        if (styledDoc instanceof AbstractDocument) {
            doc = (AbstractDocument) styledDoc;
            //doc.setDocumentFilter(new DocumentSizeFilter(MAX_CHARACTERS));
        } else {
            System.err.println("Text pane's document isn't an AbstractDocument!");
            System.exit(-1);
        }
        JScrollPane scrollPane = new JScrollPane(textPane);
        scrollPane.setPreferredSize(new Dimension(700, 350));

        //Create the text area for the status log and configure it.
        //changeLog = new JTextArea(10, 30);
        //changeLog.setEditable(false);
        //JScrollPane scrollPaneForLog = new JScrollPane(changeLog);

        //Create a JPanel for the suggestion area
        suggestionPanel = new JPanel(new BorderLayout());
        suggestionPanel.setVisible(true);
        suggestionLabel = new JLabel("Suggestion is not active at the moment.");
        suggestionLabel.setPreferredSize(new Dimension(100, 50));
        suggestionLabel.setMaximumSize(new Dimension(100, 50));
        suggestionComboBox = new JComboBox();
        suggestionComboBox.setEditable(false);
        suggestionComboBox.setPreferredSize(new Dimension(25, 25));
        //suggestionComboBox.addActionListener(new SuggestionComboBoxListener());
        suggestionComboBox.addItemListener(new SuggestionComboBoxListener());
        //suggestionComboBox.setSelectedIndex(-1);

        //add the suggestionLabel and suggestionComboBox to pane
        suggestionPanel.add(suggestionLabel, BorderLayout.CENTER);
        suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);
        JScrollPane sp = new JScrollPane(suggestionPanel);
        JScrollPane scrollPaneForSuggestion = new JScrollPane(suggestionPanel);

        //Create a split pane for the change log and the text area.
        JSplitPane splitPane = new JSplitPane(
                JSplitPane.VERTICAL_SPLIT,
                scrollPane, scrollPaneForSuggestion);
        splitPane.setOneTouchExpandable(true);
        splitPane.setResizeWeight(1.0);
        //Disables the moving of divider
        splitPane.setEnabled(false);

        //splitPane.setDividerLocation(splitPane.getHeight());
        //splitPane.setPreferredSize(new Dimension(640,400));

        //Create the status area.
        JPanel statusPane = new JPanel(new GridLayout(1, 1));
        CaretListenerLabel caretListenerLabel =
                new CaretListenerLabel("Status: Ready");
        statusPane.add(caretListenerLabel);

        //Create the toolbar
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.setRollover(true);

        openButton = new JButton("Open Snort Ruleset");
        toolBar.add(openButton);
        saveButton = new JButton("Save Ruleset");
        toolBar.add(saveButton);
        toolBar.addSeparator();
        aboutButton = new JButton("About");
        toolBar.add(aboutButton);

        //Add the components.
        getContentPane().add(toolBar, BorderLayout.PAGE_START);
        getContentPane().add(splitPane, BorderLayout.CENTER);
        getContentPane().add(statusPane, BorderLayout.PAGE_END);

        JMenu editMenu = createEditMenu();
        JMenu styleMenu = createStyleMenu();
        JMenuBar mb = new JMenuBar();
        mb.add(editMenu);
        mb.add(styleMenu);
        setJMenuBar(mb);


        //Put the initial text into the text pane.
        //initDocument();
        textPane.setCaretPosition(0);

        //Start watching for undoable edits and caret changes.
        textPane.addCaretListener(caretListenerLabel);

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                textPane.requestFocusInWindow();
            }
        });

    }

    //This listens for and reports caret movements.
    protected class CaretListenerLabel extends JLabel
            implements CaretListener {

        public CaretListenerLabel(String label) {
            super(label);
        }

        //Might not be invoked from the event dispatch thread.
        public void caretUpdate(CaretEvent e) {
            caretInvoke(e.getDot(), e.getMark());
        }

        protected void caretInvoke(final int dot, final int mark) {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    try {
                        Rectangle caretCoords = textPane.modelToView(dot);
                                    //Find suggestion
                                        suggestionComboBox.removeAllItems();
                                        for (int i = 0; i < 5; i++) {
                                            suggestionComboBox.addItem(Integer.toString(i));
                                        }
                                        //suggestionComboBox.setSelectedItem(null);
                                        suggestionComboBox.setEnabled(true);
                                        suggestionLabel.setText("The following keywords are normally used as well. Click to use keyword(s). ");
                                        //changeLog.setText("The following keywords are suggested to be used together: " + str);
                    } catch (BadLocationException ble) {
                        setText("caret: text position: " + dot + newline);
                        System.out.println("Bad Location Exception");
                    }
                }
            });
        }
    }

    public class SuggestionComboBoxListener implements ItemListener {

        //public void actionPerformed(ActionEvent e) {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                JComboBox cb = (JComboBox)e.getSource();
                String selection = (String) cb.getSelectedItem();
                JOptionPane.showMessageDialog(null, "Item is selected", "Information", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    /*
     * Menu Creation
     */
    //Create the edit menu.
    protected JMenu createEditMenu() {
        JMenu menu = new JMenu("Edit");
        return menu;
    }

    protected JMenu createStyleMenu() {
        JMenu menu = new JMenu("Style");
        return menu;
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        final Temp frame = new Temp();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    //The standard main method.
    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

推荐答案

在对组合框进行任何更改之前,需要删除ItemListener并在完成后将其重新添加.

You need to remove the ItemListener before you make any changes to the combo-box and add it back when you are done.

类似这样的东西:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class Suggestions {

    private JFrame frame;
    private JTextPane textPane;
    private JComboBox suggestionComboBox;
    private SuggestionComboBoxListener selectionListener;

    public Suggestions() {
        frame = new JFrame("Snort Ruleset IDE");

        textPane = new JTextPane();
        textPane.setCaretPosition(0);
        textPane.setMargin(new Insets(5, 5, 5, 5));
        textPane.addCaretListener(new SuggestionCaretListener());
        JScrollPane textEntryScrollPane = new JScrollPane(textPane);
        textEntryScrollPane.setPreferredSize(new Dimension(300, 400));

        selectionListener = new SuggestionComboBoxListener(frame);
        suggestionComboBox = new JComboBox();
        suggestionComboBox.setEditable(false);
        suggestionComboBox.setPreferredSize(new Dimension(25, 25));
        suggestionComboBox.addItemListener(selectionListener);

        JPanel suggestionPanel = new JPanel(new BorderLayout());
        suggestionPanel.add(suggestionComboBox, BorderLayout.PAGE_END);

        frame.getContentPane().add(textEntryScrollPane, BorderLayout.NORTH);
        frame.getContentPane().add(suggestionPanel, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private final class SuggestionCaretListener implements CaretListener {
        @Override
        public void caretUpdate(CaretEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    generateSuggestions();
                }
            });
        }
    }

    public static final class SuggestionComboBoxListener implements ItemListener {
        Component parent;
        public SuggestionComboBoxListener(Component parent) {
            this.parent = parent;
        }
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                 JComboBox cb = (JComboBox) e.getSource();
                 String selection = (String) cb.getSelectedItem();
                 JOptionPane.showMessageDialog(parent, "The selected item is: " + selection, "Information",
                 JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }

    void generateSuggestions() {
        suggestionComboBox.removeItemListener(selectionListener);
        suggestionComboBox.removeAllItems();
        for (int i = 0; i < 5; i++) {
            suggestionComboBox.addItem(Integer.toString(i));
        }
        suggestionComboBox.setEnabled(true);
        suggestionComboBox.addItemListener(selectionListener);
    }

    public static void main(String[] args) {
        new Suggestions();
    }
}

顺便说一句,您发布的不是SSCCE,而是代码的转储. SSCCE应该只具有足够的代码来重现您遇到的问题.

BTW, what you posted is not an SSCCE it is a dump of your code. An SSCCE should only have enough code to reproduce the issue you are experiencing.

这篇关于如何配置JComboBox创建时不选择FIRST元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆