Swinghacks -- add an image background to the text Control

Source: Internet
Author: User

First, this is a JTextField with a background image. If you use java to create an email client or a signature program and then add some background images to the input control, it would be nice. Of course, it can also work with the custom border written in the previous article. Let's take a look at the implementation principle. swing does not set the background image by default, so we still need to use the paintComponent method. Note that we should draw the background image before rewriting paintComponent, and then call super. the paintComponent (g) painting control ensures that the control content overwrites the background image. Code: [java] import java. io. *; import java. awt. *; import javax. swing. *; import javax. imageio. *; import java. awt. image. *; // put a texture in the background www.2cto. compublic class WatermarkTextField extends JTextField {BufferedImage img; TexturePaint texture; public WatermarkTextField (File file) throws IOException {super (); img = ImageIO. read (file); Rectangle rect = new Rectangle (0, 0, img. getWidth (null), img. getHeight (null); texture = new TexturePaint (img, rect); setOpaque (false);} public void paintComponent (Graphics g) {// first draw the background Graphics2D g2 = (Graphics2D) g; g2.setPaint (texture); g. fillRect (, getWidth (), getHeight (); // then draw the control, otherwise the control content will be overwritten by the background super. paintComponent (g );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.