PARA MAS INFORMACION VISITAR LA PAGINA DE LA API DE JAVA
aqui un ejemplo que nos presenta un sombra cuando gana el foco se elimina el texto y deje que el usuario escriba y cuando pierde el foco aparece el texto por defecto
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package principal;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Principal extends JFrame{
JTextSombra txtnombre,txttel,txtcorreo;
public Principal() {
JPanel pdatos=new JPanel();
pdatos.setLayout(new GridLayout(3,2));
pdatos.add(new JLabel("Nombre: "));
txtnombre=new JTextSombra("Escriba su aqui su nombre");
pdatos.add(txtnombre);
pdatos.add(new JLabel("Telefono: "));
txttel=new JTextSombra(20);
pdatos.add(txttel);
pdatos.add(new JLabel("E-maiil: "));
txtcorreo=new JTextSombra("Correo Electronico",20);
pdatos.add(txtcorreo);
JButton btnmostrar=new JButton("Mostrar");
btnmostrar.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Nombre: "+txtnombre.getText()+", Telefono: "+txttel.getText()+", Correo Electronico: "+txtcorreo.getText());
}
});
add(pdatos);
JPanel pboton=new JPanel();
pboton.add(btnmostrar);
add(pboton,BorderLayout.SOUTH);
}
public static void main(String arg[]){
Principal p=new Principal();
p.setVisible(true);
p.setBounds(0, 0, 400, 180);
p.setLocationRelativeTo(null);
p.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
//LA CLASE JTextSombra
package principal;
import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JTextField;
public class JTextSombra extends JTextField implements FocusListener {
String texto = "Escriba aqui...";
public JTextSombra() {
this.setText(texto);
this.setForeground(Color.RED);
this.addFocusListener(this);
}
public JTextSombra(int lg) {
super(lg);
this.addFocusListener(this);
}
public JTextSombra(String texto) {
this.texto = texto;
this.setText(texto);
this.setForeground(Color.RED);
this.addFocusListener(this);
}
public JTextSombra(String texto, int lg) {
super(lg);
this.texto = texto;
this.setText(texto);
this.setForeground(Color.RED);
this.addFocusListener(this);
}
public void focusLost(FocusEvent arg0) {
if (JTextSombra.this.getText().equalsIgnoreCase("")) {
JTextSombra.this.setText(texto);
JTextSombra.this.setForeground(Color.RED);
}
}
@Override
public void focusGained(FocusEvent fe) {
if (JTextSombra.this.getText().equalsIgnoreCase(texto)) {
JTextSombra.this.setText("");
JTextSombra.this.setForeground(Color.black);
}
}
}






0 comentarios:
Publicar un comentario