JComboBox选项选中后修改JLabel文本的实现问题
解决JComboBox选中选项触发JLabel文本修改的问题
错误原因
option[0]是字符串对象,根本没有isSelected()方法,这是报错的直接原因- 你的
JComboBox没有注册ActionListener,就算逻辑写对了,actionPerformed方法也不会被触发 - 原代码中类成员变量
option被局部变量覆盖,导致类成员option实际为null,后续无法正常调用
修正方案
- 给
JComboBox添加监听器,确保选中事件能触发actionPerformed方法 - 修改选中项的判断逻辑,使用JComboBox自带的方法获取选中内容或索引
- 修复类成员变量
option的赋值问题
关键修正点
- 初始化
box后添加监听器:box.addActionListener(this); - 替换错误的判断逻辑,两种常用方式任选:
方式一:通过选中的文本内容判断
public void actionPerformed(ActionEvent e){ String selected = (String) box.getSelectedItem(); if(selected.equals(option[0])){ reply.setText("1 inch = 2.54 centimeters"); } }
方式二:通过选中项的索引判断(第一个选项索引为0)
public void actionPerformed(ActionEvent e){ int selectedIndex = box.getSelectedIndex(); if(selectedIndex == 0){ reply.setText("1 inch = 2.54 centimeters"); } }
完整修正后的代码
import java.awt.*; import java.awt.event.*; import javax.swing.*; class Main extends JPanel implements ActionListener { JLabel question, res, reply; JCheckBox three, fortyThree, one, eightySeven, nine, ten; JButton submit; JComboBox<String> box; String option[]; public void main() { JFrame frm = new JFrame("GUI INTRO"); JPanel content = new JPanel(); frm.add(content); // 给类成员变量option赋值,而非定义局部变量 option = new String[]{"inches to centimeters", "miles to feet", "kilograms to pounds", "cups to fluid ounces"}; box = new JComboBox<>(option); box.setBounds(50,80,90,30); // 为JComboBox添加ActionListener box.addActionListener(this); reply = new JLabel(" "); content.add(box); content.add(reply); frm.setLayout(new FlowLayout()); frm.setSize(700,700); frm.setLocationRelativeTo(null); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setVisible(true); } public void actionPerformed(ActionEvent e){ // 二选一即可,这里用文本判断示例 String selected = (String) box.getSelectedItem(); if(selected.equals(option[0])){ reply.setText("1 inch = 2.54 centimeters"); } } public static void main(String[] args){ Main frame = new Main(); frame.main(); } }
内容的提问来源于stack exchange,提问作者Caitlyn
相关产品推荐
相关产品推荐

