java JComboBox getSelectedIndex() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12081696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:31:46  来源:igfitidea点击:

JComboBox getSelectedIndex() method

javaswingjcomboboxitemlistener

提问by Branislav Lazic

I was making a simple text editor where you can set font style,font size, clear all etc. To set font size I added JComboBox and implemented ItemListener. Here is my MainWindow class:

我正在制作一个简单的文本编辑器,您可以在其中设置字体样式、字体大小、清除所有内容等。为了设置字体大小,我添加了 JComboBox 并实现了 ItemListener。这是我的 MainWindow 类:

import javax.swing.*;

public class MainWindow extends JFrame{
Editor e = new Editor();

public MainWindow(){
    super(".:My Text Editor:.");
    getContentPane().add(e);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable(){
        public void run() {
            new MainWindow();
        }
    });

}

}

Here is my Editor class:

这是我的编辑器类:

import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class Editor extends JPanel{
JPanel optionPanel = new JPanel();
JTextArea editArea = new JTextArea();
JButton boldBtn = new JButton("Bold");
JButton italicBtn = new JButton("Italic");
JButton plainBtn = new JButton("Plain");
JButton clearBtn = new JButton("Clear all");
String [] fontSizes = {"10","11","12","13","14","15","16","17","18","19","20"};
int fontSize;
JComboBox combo = new JComboBox(fontSizes);

public Editor(){
    createUI();
    addEvents();
}

public void createUI(){
    optionPanel.add(boldBtn);
    optionPanel.add(italicBtn);
    optionPanel.add(plainBtn);
    optionPanel.add(combo);
    optionPanel.add(clearBtn);

    setLayout(new BorderLayout());
    add(optionPanel,BorderLayout.NORTH);
    add(new JScrollPane(editArea),BorderLayout.CENTER);
    setPreferredSize(new Dimension(640,480));
}

public void addEvents(){

    boldBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            editArea.setFont(new Font("Sans Serif",Font.BOLD,fontSize));
        }
    });

    italicBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            editArea.setFont(new Font("Sans Serif",Font.ITALIC,fontSize));

        }
    });

    plainBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            editArea.setFont(new Font("Sans Serif",Font.PLAIN,fontSize));
        }
    });

    combo.addItemListener(new ItemListener(){

        public void itemStateChanged(ItemEvent e){
            int ind = combo.getSelectedIndex();
            System.out.println(ind); 
            fontSize = Integer.parseInt(fontSizes[ind]);
            editArea.setFont(new Font("Sans Serif",Font.PLAIN,fontSize));
        }
    });

    clearBtn.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            editArea.setText("");
        }
    });
}

}

Now, weird thing what happened is when I put System.out.println(ind); line just to see what index the getSelectedIndex() method returns me. Depending on which item I click, it returns me this:

现在,奇怪的是当我把 System.out.println(ind); 行只是为了查看 getSelectedIndex() 方法返回给我的索引。根据我单击的项目,它返回给我:

1
1
0
0
2
2
3
3

Why is this happening? Shouldn't return me just 1 0 2 3? Thanks in advance.

为什么会这样?不应该只给我 1 0 2 3 吗?提前致谢。

回答by Dan D.

Whenever you change the selection in a JComboBox, the itemStateChanged event is triggered twice, once for DESELECT of the old selected item and once for SELECT for the new selected item.

每当您更改 JComboBox 中的选择时,都会触发 itemStateChanged 事件两次,一次用于旧选定项的 DESELECT,一次用于新选定项的 SELECT。

If you only want your code to be executed once, just do:

如果您只想执行一次代码,请执行以下操作:

if (e.getStateChange() == ItemEvent.SELECTED) {
...
}

回答by chubbsondubs

JCombobox fire itemStateChanged twice for SELECTED and DESELECTED that you differentiate with ItemEvent.getStateChanged(). So wrap your code in an if like this:

JCombobox 为 SELECTED 和 DESELECTED 触发 itemStateChanged 两次,您用 ItemEvent.getStateChanged() 区分它们。因此,将您的代码包装在这样的 if 中:

public void itemStateChanged( ItemEvent event ) {
    if( event.getStateChanged() == ItemEvent.SELECTED ) {
        // code here
    }
}

回答by phsym

Seems that itemStateChanged is triggered twice. I think that the ItemEvent parameter is not the same each time. Perhaps you should check the event type before doing something.

似乎 itemStateChanged 被触发了两次。我认为 ItemEvent 参数每次都不一样。也许您应该在做某事之前检查事件类型。

Sorry I can't check now, but I will do it later if you still need help.

抱歉,我现在无法查看,但如果您仍需要帮助,我会稍后查看。