问题:

更新:

从Java SE 6 API:

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.

所以我改为JComboBox(模型),因为API说:

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

但无法让它工作,第一个项目仍然被选中.

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

帖子的老部分:

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

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

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

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

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

在这种情况下如何克服这个问题呢?谢谢.

这是我的SSCCE :(最后)

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));
        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,并在完成后将其添加回来.

像这样的东西:

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));
        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,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应该只有足够的代码来重现您遇到的问题.

java – 如何配置JComboBox在创建时不选择FIRST元素?的更多相关文章

  1. iOS – UIToolBar作为UITextView的inputAccessoryView

    这是我的代码:解决方法如果工具栏中没有其他附近的按钮,工具栏似乎会将按钮的活动区域扩展到其边界之外.Apple工程师必须认为最好是猜测用户打算按哪个而不是根本不做出反应.

  2. iOS 10,UIToolbar背景颜色不会改变

    我有一个应用程序,自iOS8以来一直存在.它的工作方式是你有一个UITableView并点击单元格来产生一个分数,取决于底部的UI工具栏使用此方法改变颜色的分数:然后每当用这个点击表格视图时调用它:functableView(tableView:UITableView,didSelectRowAtIndexPathindexPath:NSIndexPath){事情是,它自从我构建应用程序以来一直有

  3. Xcode / iOS:如何隐藏Navigation-和ToolBar向下滚动?

    我想在iPhone上隐藏两个滚动条.当我向上滚动时,他们应该再次出现..我该如何处理?

  4. ios – 使用cameraOverlayView与UIImagePickerController

    我在图书馆里找不到这样的对象.任何帮助感激不尽.解决方法这是代码:在你的头文件中声明这一点:从ApplePhotoPicker添加此OverlayView.h和.m类.使用自定义相机按钮拍摄照片的操作:输出将如下图所示:快乐编码:)

  5. swift UI专项训练18 ToolBar工具条

    ToolBar属于目标操作,不需要代理。网界面上拖一个Toolbar拖到界面底部。toolbar的元素如下:Style主要是设置样式,比如浅色和黑色的。Item是工具栏上的按钮,跟导航栏很相似。我们可以选择系统中已有的,比如我们选择done那么toolbar上的按钮就会变成这样:样式非常多,大家可以试试。action中使用了注册,所以transhclick后面要跟着冒号,使用的系统样式是Trash,这是系统自带的是一个垃圾桶的样式。

  6. Android工具栏setNavigationIcon不起作用

    谢谢.解决方法我想你可以这样设置在syncState()之后放入setNavigationIcon

  7. 选项卡图标和文本均使用android设计支持库

    解决方法你是什么意思未被选中.你能分享一下你想要达到的目标以及你现在所处的位置.我不推荐你的做法.它做了很多不需要的东西来解决你的问题.我建议使用TabLayout类中的图标和文本,只需设置图标和文本.或者,如果需要,甚至是自定义布局,但使用TabLayout中的text1和图标.这样做有什么问题吗?

  8. android – requestLayout()调用不当

    你有其他调用requestLayout()的代码吗?您是否有任何代码可以进行广泛的布局子级更改,例如使视图GONE?>这是什么时候发生的?只是在开始时,就在所有观点布局之前?您有可疑的视图,称为requestLayout()不正确,您需要找到谁,何时以及为什么以前进行布局重组.

  9. 如何在TabLayout android中的活动中获取tab click事件

    这是我的活动中onCreate函数的实现.我需要动态创建标签.为简单起见,我制作了两个标签.我想在点击选项卡时更改编辑文本值.editText处于同一活动中.如何在活动中获得Tabclick事件?

  10. 图标和标题之间的工具栏中的填充/空格(Android 24)

    使用新的Android24,我发现工具栏上的图标和标题有更宽的填充,我找不到任何解决方法.例:MainActivity.java:activity_main.xml中:解决方法您可以在工具栏中添加此属性以避免此填充.

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部