Search code examples
javajtextfieldmouselistener

Textfield Clearing String


I'm trying to make a program that when the user clicks the box the message will clear up. (Must be 6-15 characters) This thing will clear up when it will be clicked, I Tried using a mouse listener but it doesn't go when i click it.

Here's a snippet of the code :

    abc = new JTextField(" (Must be 6-15 characters)");         
    abc.setBounds(40,130,310,30);
    abc.setFont(new Font("Lucida Grande", Font.ITALIC, 14));
    abc.setForeground(Color.gray);                          
    abc.addMouseListener(new MouseAdapter() {
     public void mouseClicked(MouseEvent e) {
        abc.setText("");
      }
    });
    mainPanel.add(abc);

Solution

  • Code looks good. Be sure to @Override the mouseClicked method and declare abc as final.

        final JTextField abc = new JTextField(" (Must be 6-15 characters)");         
        abc.setBounds(40,130,310,30);
        abc.setFont(new Font("Lucida Grande", Font.ITALIC, 14));
        abc.setForeground(Color.gray);                          
        abc.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                abc.setText("");
            }
        });
        mainPanel.add(abc);