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) {}
    }
};
Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Comments

  1. Tom says:

    Thanks! This is exactly what I was looking for.

  2. [...] JTextField with background image (as in the location field in your browser) [...]

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment

Powered by WP Hashcash