javafocuslistener

Having trouble with FocusListener


I am having some trouble with this code I'm writing. What I want it to do is for a Focus Listener to watch to see if a user is focused on a certain text box. if not, the string "Search..." will be shown. However, Both instances of searchText in focusGained and focusLost are not recognized. I think the reason is because searchText is only in the scope of the gui method. The only problem is, I don't know how to make searchText available to focusGained and focusLost. I have already tried @Override, but that doesn't seem to work.

If someone can please help me with this, it would be greatly appreciated. Thanks!

    package org.plugandplay.project.project2_0;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;



public class gui extends JFrame implements ActionListener, FocusListener {

    public gui() {
        super("Project 2.0 Indev");
        setLookAndFeel();
        setSize(300, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        ImageIcon search = new ImageIcon("C:/Users/User/Documents/searchicon.png");
    JButton searchButton = new JButton(search);

    JTextField searchText = new JTextField("Search...");

    searchText.addFocusListener(this);
    searchText.setColumns(15);



    JToolBar toolbar = new JToolBar("Search...");
    toolbar.add(searchText);
    toolbar.add(searchButton);


    BorderLayout border = new BorderLayout();
    setLayout(border);
    add("North", toolbar);

} 
    @Override
    public void focusGained(FocusEvent ev) {
        searchText.setText("");
    }

    public void focusLost(FocusEvent ev) {
        searchText.setText("Search...");
    }

    public void actionPerformed(ActionEvent event) {



}

Solution

  • You are having a scope issue. You need to make searchText an object member:

    public class gui extends JFrame implements ActionListener, FocusListener {
    
        //put searchText here
        JTextField searchText;
    
    
        public gui() {
            super("Project 2.0 Indev");
            setLookAndFeel();
            setSize(300, 300);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    
            ImageIcon search = new ImageIcon("C:/Users/User/Documents/searchicon.png");
        JButton searchButton = new JButton(search);
        searchText = new JTextField("Search...");
        searchText.addFocusListener(this);
        searchText.setColumns(15);