我是java的新手,我不明白为什么我的action监听器不能在jcombobox上工作。我想我已经在网上学习了getSelectedItem上的其他例子,但什么都没有发生。仅供参考,我的项目是一个单元转换器(使用MVC..hopefully,但这不是我的首要任务)。任何帮助都是非常感谢的。谢谢,西蒙。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class UnitConverterView extends JFrame{
//variables and components
private static final long serialVersionUID = -4673040337179571462L;
private JComboBox<String> unitCategory;
private JTextField fromValue = new JTextField(7);
private JComboBox<String> convertFrom;
private JLabel equalsLabel = new JLabel(" = ");
private JTextField toValue = new JTextField(7);
private JComboBox<String> convertTo;
//constructor
UnitConverterView(){
//set up the view and components
JPanel unitPanel = new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600,300);
String[] categories = {"Length","Weight","Speed","Temperature"};
unitCategory = new JComboBox<>(categories);
String[] tofromValues = {" "};
convertFrom = new JComboBox<>(tofromValues);
convertTo = new JComboBox<>(tofromValues);
unitPanel.add(unitCategory);
unitPanel.add(fromValue);
unitPanel.add(convertFrom);
unitPanel.add(equalsLabel);
unitPanel.add(toValue);
unitPanel.add(convertTo);
this.add(unitPanel);
}
//get value to convert from
public int getMeasurement() {
return Integer.parseInt(fromValue.getText());
}
//listen for unitCategory to be selected
void addUnitCategoryListener(ActionListener listenForUnitCategory) {
unitCategory.addActionListener(listenForUnitCategory);
}
class UnitCatListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
/*String unitSelected = (String) unitCategory.getSelectedItem();
if (e.getSource() == unitCategory) {
String unitName = (String) unitCategory.getSelectedItem();
System.out.println("UnitName = " + unitName);
changeText(unitName);
}*/
JComboBox cb = (JComboBox)e.getSource();
String unitName = (String) cb.getSelectedItem();
System.out.println("UnitName = " + unitName);
}
void changeText(String name) {
toValue.setText(name);
}
}
}发布于 2015-10-18 21:05:33
您已经声明了一个用于将侦听器注册到组合框的方法addUnitCategoryListener(),但您从未调用过此方法。这就是为什么监听程序从不注册的原因。
在构造函数的末尾添加下面这行代码,这样就没问题了:
addUnitCategoryListener(new UnitCatListener());发布于 2015-10-18 21:14:44
要简单地解决您的问题,请调用您创建的在组件上注册侦听器的方法。将以下代码添加到您的构造函数:
addUnitCategoryListener(new UnitCatListener());但是,有几件事你需要知道:
对于JComboBox,
ItemListener通常比ActionListener做得更好。如果用户选择了已经选择的项,则前一个不会触发事件(基本上,什么也不做)。通常在这些情况下你不需要做任何事情。新建(unitCategory.addActionListener UnitCatListener());
删除您的自定义方法。
changeText和getMeasurement从未使用过。
JComboBox而不是equalsLabel不需要equalsLabel作为字段-局部变量就可以-因为您以后不需要在任何地方引用它(除非您计划在运行时更改标签的属性)。https://stackoverflow.com/questions/33197323
复制相似问题