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) {}
    }
};

Viewing 1 Comment

Trackbacks

close Reblog this comment
blog comments powered by Disqus