我正在测试此代码,以确保它在完成其余开关盒之前按预期运行。该应用程序运行良好,但是当单击组合框选项时,应该根据适当的情况显示一个字符串。我不知道为什么这不起作用。我尝试调试,但坦率地说我没有看到任何问题。任何帮助都会很棒。这是代码:
package combobox;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SolicitorComBox extends JFrame implements ActionListener {
String[] MuniArray = {"Allepo", "Avalon",};
JComboBox MuniList = new JComboBox (MuniArray);
JLabel lblText = new JLabel();
public static void main(String[] args) {
SolicitorComBox fr = new SolicitorComBox();
centerFrame(fr);
fr.setVisible(true);
}
private static void centerFrame(SolicitorComBox fr) {
}
public SolicitorComBox() {
setLayout (new FlowLayout());
setSize (400, 300);
setTitle ("Solicitor Search");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MuniList.setSelectedIndex(0);
MuniList.addActionListener(this);
add(MuniList);
add(lblText);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == MuniList) {
JComboBox cb = (JComboBox).e.getSource();
String msg = (String)cb.getSelectedItem();
switch (msg) {
case "Allepo": lblText.setText("The attorney is Joe!");
break;
case "Avalon": lblText.setText("The attorney is Dana!");
break;
答案 0 :(得分:1)
在actionPerformed()
中进行更改
(JComboBox).e.getSource();
到
(JComboBox) e.getSource();
您必须强制转换为JComboBox