Java-如何添加JComboBox标头 [英] Java - How to add JComboBox Header

查看:45
本文介绍了Java-如何添加JComboBox标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个JComboBox,其标题无法被选中..有什么帮助吗?如何使day元素只是标题?

I'm trying to make a JComboBox with a header that cannot be selected just displayed..any help? How can i make the day element just a header?

    m2.addItem("Day:");
    m2.addItem("1");
    m2.addItem("2");
    m2.addItem("3");
    m2.addItem("4");
    m2.addItem("5");
    m2.addItem("6");
    m2.addItem("7");
    m2.addItem("8");
    m2.addItem("9");
    m2.addItem("10");
    m2.addItem("11");
    m2.addItem("12");
    m2.addItem("13");
    m2.addItem("14");
    m2.addItem("15");
    m2.addItem("16");
    m2.addItem("17");
    m2.addItem("18");
    m2.addItem("19");
    m2.addItem("20");
    m2.addItem("21");
    m2.addItem("22");
    m2.addItem("23");
    m2.addItem("24");
    m2.addItem("25");
    m2.addItem("26");
    m2.addItem("27");
    m2.addItem("28");
    m2.addItem("29");
    m2.addItem("30");
    m2.addItemListener(null);
    m2.setBounds(900, 477, 50, 20);

推荐答案

好的,您可以正确添加一个头,如果要稍后使用,则可以避免使用第一个索引:

Ok you way is correct to add a head, if you want to use it later then you can avoid the first index :

m2.addItem("Day:");
m2.addItem("1");
m2.addItem("2");

if(m2.getSelectedIndex() != 0){
   //you can use your choise :
   String x = String.valueOf(m2.getSelectedItem());
}else{
   //you can print an error or avoid your action 
}

编辑

如果要选择默认值,请使用以下命令:

If you want to make a default selected then use this :

m2.addItem("Day:");
for(int i = 1; i <= 30; i++){
  m2.addItem(i+"");
}
//set the 1st element selected by default
m2.setSelectedIndex(1);

如果您不想使用索引,则还可以使用 m2.setSelectedItem 来选择项目

If you dont want to use index then you can use also m2.setSelectedItem to select the item

m2.setSelectedItem("5");

希望这可以为您提供帮助.

Hope this can help you.

这篇关于Java-如何添加JComboBox标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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