【发布时间】:2015-06-04 12:58:26
【问题描述】:
在我的代码中,我有一个简单的 JComboBox,用于打开或关闭某个功能。 JComboBox 代码为:
public static JComboBox getErrorLoggingOnOrOff(){
String[] options = { "On", "Off" };
JComboBox combo = new JComboBox(options);
return combo;
}
问题在于,无论我何时单击“关闭”,它都会将值返回为开启状态。 JComboBox 在这里被调用:请注意,我已经包含了 System.out.println()(以及对 null 的检查)只是为了检查输出。
String option = combo.getSelectedItem().toString();
....
if(option.equals("On")){
System.out.println("On selected");
return;
}
else if(option.equals("Off")){
System.out.println("Off selected");
return;
}
else {
System.out.println("Null value for option.... :-/");
}
任何指针都将不胜感激,对于为什么会发生这种情况确实感到困惑,无疑是一个简单的疏忽。
问候,Reg.
编辑 这是完整的代码摘录
final JMenuItem enableErrorLogging = new JMenuItem("Enable Error Logging");
enableErrorLogging.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, ActionEvent.ALT_MASK));
enableErrorLogging.setMnemonic(KeyEvent.VK_M);
menu.add(enableErrorLogging);
enableErrorLogging.addActionListener( new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (ui.getWorkspace().getCurrentProject() == null) {
openProjectMessagePane();
return;
}
JComboBox combo = getErrorLoggingOnOrOff();
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JLabel("Turn Error Logging On Or Off"));
panel.add(combo);
String option = combo.getSelectedItem().toString();
try{
int r = JOptionPane.showConfirmDialog(frame, panel, "Enable Error Logging?",
JOptionPane.OK_OPTION, JOptionPane.PLAIN_MESSAGE);
if (r == JOptionPane.OK_OPTION) {
if(option.equals("On")){
System.out.println("On selected");
return;
}
else if(option.equals("Off")){
System.out.println("Off selected");
return;
}
else{
System.out.println("Null value for option.... :-/");
}
}
} catch (Exception ex) {
LOGGER.debug(ex);
}
}
});
【问题讨论】:
-
能否提供可运行版本的代码,还是太长了?
-
可能太长了...我会看看其他可能导致问题的摘录!
-
@bakalolo 把这个操作的所有代码放在那里,忽略我之前的评论。顺便感谢您的关注。
-
将
String option = combo.getSelectedItem().toString();放在您的if (r == JOptionPane.OK_OPTION)之后。我认为您在选择任何内容之前就获得了“selectedItem”。
标签: java string swing jcombobox