Java: How do I do a “onclick” for TextField?

后端 未结 3 1758
长发绾君心
长发绾君心 2021-01-15 07:14

I want to make my text field clear the text when someone clicks it. How can I do this?

相关标签:
3条回答
  • 2021-01-15 07:21

    Probably, you need addMouseListener().

    upd It would be smt like

    TextField a = ...;
      a.addMouseListener(new MouseAdapter(){
       public void mouseReleased(MouseEvent e) {
        //some stuff
       }
    });
    

    upd2 fix keyListener to MouseListener

    0 讨论(0)
  • 2021-01-15 07:29

    Try this:

      TextField.setText("defaultText");
    
        TextField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                reSet(evt);
            }
        });
    
      TextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                reSet(evt);
            }
      });
    
      void reSet(java.awt.event.KeyEvent evt) {
          String temp = jTextField1.getText();
          TextField.setText(temp.equals("defaultText")? "" : temp);
      }
    
    0 讨论(0)
  • 2021-01-15 07:39

    on java.awt.TextField you can add a MouseListener like so

    TextField field = new TextField();
    field.addMouseListener(new MouseListener() {
    
        public void mouseClicked(MouseEvent e) {
    
        }
    
        public void mousePressed(MouseEvent e) {
    
        }
    
        public void mouseReleased(MouseEvent e) {
    
        }
    
        public void mouseEntered(MouseEvent e) {
    
        }
    
        public void mouseExited(MouseEvent e) {
    
        }
    
    });
    

    The reason being that java.awt.TextField is a subclass of java.awt.TextComponent (which, in turn, is a subclass of java.awt.Component). The Component class has a addMouseListener() method.

    Alternatively, you can replace MouseListener with java.awt.event.MouseAdapter has it encapsulates all of MouseListener, MouseWheelListener and MouseMotionListener methods.

    From JavaDoc (of MouseAdapter):

    An abstract adapter class for receiving mouse events. The methods in this class are empty. This class exists as convenience for creating listener objects.

    Mouse events let you track when a mouse is pressed, released, clicked, moved, dragged, when it enters a component, when it exits and when a mouse wheel is moved.

    0 讨论(0)
提交回复
热议问题