我理解这个问题已被多次提出,但是要认真地说。什么是在Java中禁用JComboBox的第一项的最简单方法。我有以下代码,我想禁用“选择一个状态”,因此它强制用户选择一个状态,如果他们没有,那么它会打印一个空字符串
states = new JComboBox<String>(new String[] {"Select a State",
"AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA",
"HI","ID","IL","IN","IA","KS","KY","LA","ME","MD",
"MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ",
"NM","NY","NC","ND","OH","OK","OR","PA","RI","SC",
"SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"});
states.setEditable(false);
答案 0 :(得分:1)
结帐Combo Box Prompt。当组合框中未选择任何项目时,它将显示消息。
答案 1 :(得分:0)
基本上保持简单,你可以使用conditional
语句:
states.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// now there's nothing happen when we select the first item
if(states.getSelectedIndex()>0){
System.out.println("YOU CLICK INDEX-"+states.getSelectedIndex());
}
}
}
);
因此,当用户点击第一个项目时,没有任何事情可以发生。这是完整的演示:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxDemo extends JFrame {
private JComboBox<String> states;
public ComboBoxDemo() {
super("JComboBox Demo");
states = new JComboBox<String>(new String[]{"Select a State",
"AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"});
setLayout(new FlowLayout(FlowLayout.CENTER));
add(states, BorderLayout.CENTER);
states.addItemListener(
new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// now there's nothing happen when we select the first item
if(states.getSelectedIndex()>0){
System.out.println("YOU CLICK INDEX- "+states.getSelectedIndex());
}
}
}
);
}
public static void main(String[] args) {
ComboBoxDemo g = new ComboBoxDemo();
g.setVisible(true);
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.setBounds(100, 100, 300, 300);
}
}