有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing JCombobox可编辑Java编程

在我的可编辑组合框中。我想允许用户 在JComboBox中键入值的名称,如果所需值不可用,则应显示相应的错误消息。。(像JOptionPane) 我需要在这里使用getSelectedItem()

这是我的代码:

    import java.awt.FlowLayout;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;

    import javax.swing.*;
    public class JTunes extends JFrame implements ItemListener{
    private JComboBox lyrics;
    private JTextField price;
    double sum = 0;
    public JTunes(){
        super("Lyrics");
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        String[] lyrics1 = {"multiple", "data", "types", "used", "safely"};
        price = new JTextField(15);
         lyrics = new JComboBox(lyrics1);
         lyrics.setEditable(true);

         add(lyrics);
         add(price);
         lyrics.addItemListener(this);

    }

    public void itemStateChanged(ItemEvent e){
        String list = (String)lyrics.getSelectedItem();
            if(list.equals("multiple"))
                sum = 20;
            else if(list.equals("data"))
                sum = 30;
            else if(list.equals("types"))
                sum = 40;
            else if(list.equals("used"))
                sum = 50;
            else if(list.equals("safely"))
            sum = 60;


            price.setText(String.valueOf(sum));
    }
}

共 (2) 个答案

  1. # 1 楼答案

    如果我没弄错的话,您只需要看看jComboBox是否包含您正在搜索的文本。您应该能够使用以下功能:

    if(!jComboBox.contains("TEXT_TO_SEARCH") {    
        //Display error message accordingly. 
    }
    
  2. # 2 楼答案

    I want to allow the user to type the name of a value in the JComboBox and it should display an appropriate error message if the desired value is not available.

    这毫无意义。使用组合框的意义在于,用户只能选择列表中存在的项目

    lyrics.setEditable(true);
    

    去掉上面的代码,用户将只能选择有效的项目