How to set Text like Placeholder in JTextfield in swing

前端 未结 3 841
离开以前
离开以前 2020-12-06 20:40

I want to put some texts in text-Field when the form is load which instruct to user and when user click on that text-filed the texts remove automatically.

 t         


        
3条回答
  •  独厮守ぢ
    2020-12-06 20:56

    JTextField busqueda = new JTextField(20);  
    
    add(busqueda);   
    busqueda.setHorizontalAlignment(SwingConstants.CENTER);  
    
    if (busqueda.getText().length() == 0) {  
        busqueda.setText("Buscar");  
        busqueda.setForeground(new Color(150, 150, 150));  
    }  
    
    busqueda.addFocusListener(new FocusListener() {  
    
        @Override  
        public void focusGained(FocusEvent e) {  
            busqueda.setText("");  
            busqueda.setForeground(new Color(50, 50, 50));  
        }  
    
        @Override  
        public void focusLost(FocusEvent e) { 
    
            if (busqueda.getText().length() == 0) {  
                busqueda.setText("Buscar");  
                busqueda.setForeground(new Color(150, 150, 150));  
            }  
    
        }  
    });
    

提交回复
热议问题