gpt4 book ai didi

java - JComboBox getSelectedItem

转载 作者:行者123 更新时间:2023-11-30 03:13:18 26 4
gpt4 key购买 nike

刚接触 java,我不明白为什么我的 Action 监听器不能在 jcombobox 上工作。我想我已经按照网上的其他示例来 getSelectedItem,但没有发生任何事情。仅供引用,我的项目是一个单位转换器(希望使用 MVC,但这不是我的首要任务)。非常感谢任何帮助。谢谢,西蒙。

    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);
}

}



}

最佳答案

您已经声明了一个方法 addUnitCategoryListener() 用于将监听器注册到组合框,但您从未调用过此方法。这就是监听器从未注册的原因。

在构造函数末尾添加以下行,然后就可以了:

addUnitCategoryListener(new UnitCatListener());

关于java - JComboBox getSelectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com