Search code examples
javaswingeventspaneljtextfield

'void' type not allowed here - listener to a parameter


Why you can't add a listener to a object which is a parameter?

panelThird.add(new JTextField( "Write here !" ).addActionListener(
        new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                dlm.addElement(e.getActionCommand());
            }
        }), 
        BorderLayout.SOUTH);

Solution

  • addActionListener has a return type of void - so you can't write:

    panelThird.add(new JTextField(...).addActionListener(...));
    

    Instead, you need:

    JTextField field = new JTextField(...);
    field.addActionListener(...);
    panelThird.add(field);