I wanted to make a text like this:
Thistext"transparent" when clicked it disappears and if you can start writing in dialog ... does anyone know how to do this in Java?
Help me out!
I wanted to make a text like this:
Thistext"transparent" when clicked it disappears and if you can start writing in dialog ... does anyone know how to do this in Java?
Help me out!
I have. The trick is you create a JTextField
with two other components inside : A JLabel
with cue text and an image with the icon. And then you use DocumentListener
to capture the changes of the text of JTextField
to decide whether JLabel
should be visible or not.
Here's the code:
JImage.java :
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
/**
* @author Victor Stafusa
*/
public class JImage extends JComponent {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public JImage() {
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
Dimension d = new Dimension(image == null ? 0 : image.getWidth(), image == null ? 0 : image.getHeight());
this.setPreferredSize(d);
}
@Override
protected void paintComponent(Graphics g) {
if (image == null) return;
g.drawImage(image, 0, 0, null);
}
}
JSearchField.java :
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
/**
* @author Victor Stafusa
*/
public class JSearchField extends JTextField {
private static final long serialVersionUID = 1L;
private final JLabel emptyTextLabel;
private final JImage iconImage;
public JSearchField() {
this.emptyTextLabel = new JLabel();
this.iconImage = new JImage();
this.setLayout(new BorderLayout());
this.add(emptyTextLabel, BorderLayout.WEST);
this.add(iconImage, BorderLayout.EAST);
DocumentListener listener = new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
emptyTextLabel.setVisible(getText().isEmpty());
}
@Override
public void removeUpdate(DocumentEvent e) {
emptyTextLabel.setVisible(getText().isEmpty());
}
@Override
public void changedUpdate(DocumentEvent e) {
emptyTextLabel.setVisible(getText().isEmpty());
}
};
this.getDocument().addDocumentListener(listener);
}
public String getEmptyText() {
return emptyTextLabel.getText();
}
public void setEmptyText(String emptyText) {
emptyTextLabel.setText(emptyText);
}
public BufferedImage getIcon() {
return iconImage.getImage();
}
public void setIcon(BufferedImage icon) {
iconImage.setImage(icon);
}
// Você pode usar este método se precisar fazer alterações no JLabel.
public JLabel getEmptyTextLabel() {
return emptyTextLabel;
}
// Você pode usar este método se precisar fazer alterações no JImage.
public JImage getEmptyTextImage() {
return iconImage;
}
}
And to test this, here's a class that creates a screen with a JSearchField
:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @author Victor Stafusa
*/
public class Transparente {
public static void main(String[] args) {
// Executa tudo dentro da EDT.
EventQueue.invokeLater(Transparente::run);
}
// No seu projeto, é melhor você substituir isso por algo que carregue o ícone
// a partir de um arquivo local ou desenhe de dentro da aplicação, ao invés de baixar da internet.
private static BufferedImage carregarIcone() {
try {
// Ícone criado por Jonathan Lamim e obtido a partir de http://www.iconesbr.net/down_ico/6231/search
// Lembre-se de sempre certificar-se que a sua licença de uso de imagem é adequada caso vá usar imagens de terceiros.
// No caso deste ícone específico, ver mais informações em http://www.iconesbr.net/sobre
return ImageIO.read(new URL("http://www.iconesbr.net/iconesbr/2008/08/6231/6231_16x16.png"));
} catch (IOException e) {
return null;
}
}
private static void run() {
// Cria uma tela com uma panel principal dentro. Usa esta panel para definir
// o tamanho mínimo e preferencial da janela.
JFrame jf = new JFrame();
jf.setTitle("Teste JSearchField");
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel jp = new JPanel();
Dimension d = new Dimension(350, 50);
jf.add(jp);
jp.setMinimumSize(d);
jp.setPreferredSize(d);
jf.pack();
Dimension sd = Toolkit.getDefaultToolkit().getScreenSize();
jf.setLocation((sd.width - jf.getWidth()) / 2, (sd.height - jf.getHeight()) / 2);
// Vamos usar o posicionamento absoluto.
jp.setLayout(null);
// Cria o JSearchField e o acrescenta a panel principal.
JSearchField text = new JSearchField();
text.setEmptyText("Pesquise...");
text.setIcon(carregarIcone());
jp.add(text);
text.setBounds(10, 10, 130, 20);
// Exibe a tela.
jf.setVisible(true);
}
}
Here's the result:
ThetopscreenisasitappearswhenthetextofJSearchField
isempty.ThebottomscreenisasitappearsafterItyped"test."
And finally, notice that I'm downloading the link icon. In your case you should not make the code download it from the internet, but load it from some local file or even draw it inside the application.