javaswingactionlistenermouselistenerfocuslistener

FocusListener cannot be added like other Listeners?


In my code when I try to add a FocusListener to a JTextField, it says

ChatClient.java:30: error: incompatible types: ChatClient cannot be converted to FocusListener
    text.addFocusListener(this);

But adding a MouseListener works just fine. Why is it like that? Creating another class with FocusListener works. I would like to know the difference between adding a MouseListener and a FocusListener. Is there any other way to simply add FocusListener without writing a separate class for it?

public void makeUI(){
    text = new JTextField(defaultMessage);
    text.setBounds(10,620,295,40);
    text.addFocusListener(this);
    add(text);
    button = new JButton("SEND");
    button.setBounds(310,620,80,40);
    button.setForeground(Color.WHITE);
    button.setBackground(Color.decode("#11A458"));
    button.setFocusPainted(false);
    button.addActionListener(this);
    add(button);
    setSize(400,700);
    setLayout(null);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public void focusGained(FocusEvent ae){
    if(text.getText().equals(defaultMessage)){
        text.setText("");
    }
  }
  public void focusLost(FocusEvent ae){
    if(text.getText().isEmpty()){
      text.setText(defaultMessage);
    }
  }

Solution

  • I see that you have added focusGained and focusLost methods, but does your class implement FocusListener interface?

    So, the code should be something like:

    /**
     * 1. this implements FocusListener is important
     * 2. another interfaces you had here before also should be present
     */
    public class YourClass implements FocusListener {  
    
            public void makeUI(){
                text = new JTextField(defaultMessage);
                text.setBounds(10,620,295,40);
                text.addFocusListener(this);
                add(text);
                button = new JButton("SEND");
                button.setBounds(310,620,80,40);
                button.setForeground(Color.WHITE);
                button.setBackground(Color.decode("#11A458"));
                button.setFocusPainted(false);
                button.addActionListener(this);
                add(button);
                setSize(400,700);
                setLayout(null);
                setVisible(true);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
    
            @Override
            public void focusGained(FocusEvent ae){
                if(text.getText().equals(defaultMessage)){
                    text.setText("");
                }
            }
    
            @Override
            public void focusLost(FocusEvent ae){
                if(text.getText().isEmpty()){
                    text.setText(defaultMessage);
                }
            }
    
    }