【问题标题】:Having trouble with JComboBox and JButtonJComboBox 和 JButton 遇到问题
【发布时间】:2017-05-21 03:16:38
【问题描述】:

基本上我正在编写一个简单的 TCP-UDP 多客户端 GUI,我的程序在程序的以下部分抛出错误。我有一个JComboBox,其中包含元素TCPUDP。因此,如果选择了元素TCP 并且我按下connect,那么我应该能够调用TCPconnection方法,但它没有这样做。它抛出一个错误:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: 
    javax.swing.JButton cannot be cast to javax.swing.JComboBox

请帮帮我!

@Override
public void actionPerformed(ActionEvent e)
{
    String command = e.getActionCommand();

    JComboBox comboBox = (JComboBox)e.getSource();
    Object selected = comboBox.getSelectedItem();
    String comboItem = selected.toString();
    System.out.println(comboItem); //GOOD!
    if(comboItem.equals("TCP"))
    {
        isTCPconnection = true;
        if(isTCPconnection)
        {
            System.out.println("TCPconnection is true"); //GOOD!
        }
    }
    if(comboItem.equals("UDP"))
    {
        isUDPconnection = true;
    }

    if(command.equals("connect") && isTCPconnection) //PROBABLY HERE!
    {
        TCPconnection(serverName,serverPort);
        System.out.println("TCPconnection");
    }
    }

【问题讨论】:

  • 这是你的按钮的动作监听器,是吗?
  • @KevinAnderson 是的......
  • 那么,e.getSource() 是您的按钮。所以JComboBox comboBox = (JComboBox)e.getSource(); 行试图将JButton 转换为JComboBox。这就是错误。
  • @KevinAnderson 我该如何解决?
  • 程序中的某处必须有一个变量引用您的组合框。调用getSelectedItem() 时只需使用该变量即可。当然摆脱JComboBox comboBox = (JComboBox)e.getSource();

标签: java swing jbutton jcombobox classcastexception


【解决方案1】:

您在 JButton(可能适用)上添加了 actionPerformed,而不是组合框。 从类而不是从源中获取 JComboBox。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2013-12-18
    • 2015-07-28
    相关资源
    最近更新 更多