May
8
2008

Java: JTextField Background Image



Comments available as RSS 2.0

This snippet will create a JTextBox and draw an image on the right hand side. It also sets the margin accordingly to prevent the user typing into that area.

JTextField myTextField = new JTextField(20) {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
	try {
            URL url = this.getClass().getResource("image.png");
            final java.awt.image.BufferedImage image = javax.imageio.ImageIO.read(url);
            Border border = UIManager.getBorder("TextField.border");
            JTextField defaultField = new JTextField();
            final int x = getWidth() - border.getBorderInsets(defaultField).right - image.getWidth();
            setMargin(new Insets(2, 2, 2, getWidth() - x));
            int y = (getHeight() - image.getHeight())/2;
            g.drawImage(image, x, y, this);
        } catch(Exception ignore) {}
    }
};

2 thoughts on “Java: JTextField Background Image

  1. Pingback: Toying With Swing « Dark Views

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">