遇到JComboBox和JButton问题

时间:2017-05-21 03:16:39

标签: java swing jbutton jcombobox classcastexception

基本上我正在编写一个简单的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");
    }
    }

1 个答案:

答案 0 :(得分:0)

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