"Transparent" text in java

Asked

Viewed 1,530 times

3

I wanted to do a text similar to this:

Imagem This "transparent" text, when clicked it disappears and you can start writing in the dialog box... someone knows how to do it in Java?

Help me, people, help me!

  • www.code.google.com/p/xswingx/

1 answer

3


I got it. The trick is you create a JTextField with two other components inside: One JLabel with the suggestion text and an image with the icon. And then you use the DocumentListener to capture text changes JTextField to decide whether the JLabel should be visible or not.

Here is 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);
    }
}

That is the result:

Telas com um JSearchField

The top screen is how it appears when the text of JSearchField is empty. The bottom screen is as it appears after I have typed "test".

And finally, note that I am downloading the icon of http://www.iconesbr.net/iconesbr/2008/08/6231/6231_16x16.png. In your case you should not make the code download it from the internet, but rather upload it from some local file or even draw it within the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.