Java 如何配置JComboBox在创建时不选择第一个元素?
问题: 更新: 从Java SE 6 API: 公共JComboBox()创建JComboBox 使用默认数据模型。默认值 数据模型是一个空的 物体。使用addItem添加项目By 默认为数据中的第一项 型号被选中。 因此,我改为JComboBox(模型),正如API所说: 公共JComboxBox(ComboxModel aModel) 创建一个JComboBox,它接受 现有ComboBoxModel中的项。 由于提供了ComboBoxModel,因此 使用此选项创建的组合框 构造函数不创建默认值 组合框模型,可能会影响 插入、删除和添加方法 我尝试了以下方法:Java 如何配置JComboBox在创建时不选择第一个元素?,java,swing,jcombobox,Java,Swing,Jcombobox,问题: 更新: 从Java SE 6 API: 公共JComboBox()创建JComboBox 使用默认数据模型。默认值 数据模型是一个空的 物体。使用addItem添加项目By 默认为数据中的第一项 型号被选中。 因此,我改为JComboBox(模型),正如API所说: 公共JComboxBox(ComboxModel aModel) 创建一个JComboBox,它接受 现有ComboBoxModel中的项。 由于提供了ComboBoxModel,因此 使用此选项创建的组合框 构造函数不创建
DefaultComboBoxModel model = new DefaultComboBoxModel();
model.setSelectedItem(null);
suggestionComboBox = new JComboBox(model);
suggestionComboBox.setModel(model);
但无法使其工作,仍在选择第一项
任何能想出一个可行的例子的人都将不胜感激
职位的旧部分: 我正在使用JComboBox,并尝试在代码中使用
setSelectionIndex(-1)
(此代码位于caretInvoke()
)
当caretInvoke触发组合框初始化时,甚至在用户选择元素之前,已触发执行的操作(我在这里尝试了JOptionPane):
问题是:当用户从组合框中选择元素时,我的程序会自动插入所选文本。因此,用户无需选择任何内容,它就会自动插入
在这种情况下,我如何克服这个问题?谢谢
这是我的SSCCE:(最后)
封装组件;
导入java.awt.BorderLayout;
导入java.awt.Dimension;
导入java.awt.GridLayout;
导入java.awt.Insets;
导入java.awt.Rectangle;
导入java.awt.event.ItemEvent;
导入java.awt.event.ItemListener;
导入javax.swing.JButton;
导入javax.swing.JComboBox;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JMenu;
导入javax.swing.JMenuBar;
导入javax.swing.JOptionPane;
导入javax.swing.JPanel;
导入javax.swing.JScrollPane;
导入javax.swing.JSplitPane;
导入javax.swing.JTextArea;
导入javax.swing.JTextPane;
导入javax.swing.JToolBar;
导入javax.swing.SwingUtilities;
导入javax.swing.UIManager;
导入javax.swing.event.CaretEvent;
导入javax.swing.event.CaretListener;
导入javax.swing.text.AbstractDocument;
导入javax.swing.text.BadLocationException;
导入javax.swing.text.StyledDocument;
公共类Temp扩展JFrame{
JTextPane textPane;
文件摘要;
JTextareachangelog;
字符串换行符=“\n”;
私有JComboBox建议组合框;
私人JPanel建议小组;
私人JLabel suggestionLabel;
私有JButton openButton、saveButton、aboutButton;
公共临时工(){
超级(“Snort规则集IDE”);
//创建文本窗格并对其进行配置。
textPane=新的JTextPane();
textPane.setCaretPosition(0);
setMargin(新的插图(5,5,5,5));
StyledDocument styledDoc=textPane.getStyledDocument();
if(抽象文档的styledDoc实例){
doc=(抽象文档)styledDoc;
//doc.setDocumentFilter(新DocumentSizeFilter(最大字符数));
}否则{
System.err.println(“文本窗格的文档不是抽象文档!”);
系统退出(-1);
}
JScrollPane scrollPane=新的JScrollPane(textPane);
scrollPane.setPreferredSize(新维度(700350));
//为状态日志创建文本区域并进行配置。
//changeLog=新的JTextArea(10,30);
//changeLog.setEditable(false);
//JScrollPane scrollPaneForLog=新的JScrollPane(changeLog);
//为建议区域创建JPanel
suggestionPanel=newjpanel(newborderlayout());
suggestionPanel.setVisible(true);
suggestionLabel=new JLabel(“建议目前未激活”);
suggestionLabel.setPreferredSize(新维度(100,50));
suggestionLabel.setMaximumSize(新尺寸(100,50));
suggestionComboBox=新建JComboBox();
suggestionComboBox.setEditable(false);
suggestionComboBox.setPreferredSize(新维度(25,25));
//suggestionComboBox.addActionListener(新建SuggestionComboxListener());
addItemListener(新建SuggestionComboxListener());
//suggestionComboBox.setSelectedIndex(-1);
//将suggestionLabel和suggestionComboBox添加到窗格
suggestionPanel.add(suggestionLabel,BorderLayout.CENTER);
suggestionPanel.add(suggestionComboBox,BorderLayout.PAGE_END);
JScrollPane sp=新的JScrollPane(suggestionPanel);
JScrollPane scrollPaneForSuggestion=新建JScrollPane(suggestionPanel);
//为更改日志和文本区域创建拆分窗格。
JSplitPane splitPane=新的JSplitPane(
JSplitPane.VERTICAL_SPLIT,
滚动窗格,滚动窗格建议);
splitPane.setOneTouchExpandable(true);
splitPane.setResizeWeight(1.0);
//禁用分隔器的移动
splitPane.setEnabled(false);
//splitPane.setDividerLocation(splitPane.getHeight());
//splitPane.setPreferredSize(新维度(640400));
//创建状态区域。
JPanel statusPane=newjpanel(newgridlayout(1,1));
CaretListenerLabel CaretListenerLabel=
新的CaretListenerLabel(“状态:就绪”);
statusPane.add(caretListenerLabel);
//创建工具栏
JToolBar toolBar=新的JToolBar();
工具栏。可设置浮动(false);
toolBar.setRollover(true);
openButton=新的JButton(“打开Snort规则集”);
工具栏。添加(打开按钮);
saveButton=newjbutton(“保存规则集”);
工具栏。添加(保存按钮);
toolBar.addSeparator();
aboutButton=新的JButton(“About”);
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());
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();
}
});
}
}
setSelectedItem(null);
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();
}
}
jComboBox1.setSelectedIndex(0);