Results 1 to 2 of 2
Thread: Background image in java
- 07-23-2007, 11:58 PM #1
Member
- Join Date
- Jul 2007
- Posts
- 40
- Rep Power
- 0
- 07-29-2007, 07:15 AM #2
Text on background image
Java Code:import java.awt.*; import java.awt.font.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.*; public class TextOnBackground extends JPanel { BufferedImage image; String text = "Hello World"; public TextOnBackground(BufferedImage image) { this.image = image; } protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); int w = getWidth(); int h = getHeight(); // Draw image, centered. int x = (w - image.getWidth())/2; int y = (h - image.getHeight())/2; g2.drawImage(image, x, y, this); // Draw text centered over image. Font font = g2.getFont().deriveFont(36f); g2.setFont(font); FontRenderContext frc = g2.getFontRenderContext(); float width = (float)font.getStringBounds(text, frc).getWidth(); LineMetrics lm = font.getLineMetrics(text, frc); float sx = (w - width)/2; float sy = (h + lm.getHeight())/2 - lm.getDescent(); g2.setPaint(Color.red); g2.drawString(text, sx, sy); } public static void main(String[] args) throws IOException { String path = "images/cougar.jpg"; BufferedImage image = ImageIO.read(new File(path)); TextOnBackground test = new TextOnBackground(image); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(test); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); } }
Similar Threads
-
Center background image
By Floetic in forum AWT / SwingReplies: 1Last Post: 04-24-2008, 05:50 PM -
GUI... setting my background to an image, im using a JFrame
By newtojava7 in forum New To JavaReplies: 2Last Post: 03-24-2008, 05:29 AM -
Converting multiple banded image into single banded image... Image enhancement
By archanajathan in forum Advanced JavaReplies: 0Last Post: 01-08-2008, 05:29 PM -
Set the background in Java
By barney in forum New To JavaReplies: 1Last Post: 08-07-2007, 07:13 AM -
Why this image background is black ?
By samson in forum Java 2DReplies: 1Last Post: 07-17-2007, 04:24 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks