Discussion Locked

Random text over a random image

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Is there a way to generate a random text over a random image in java? If so can the sample code be sent. I know to generate it using PHP . But i want it in java. Any help on this will be appreciated.
thanks
surendran

3 replies

by cdumitru

Using Swing (JFC):
The text will be displayed by a JLabel component non-opaque (whose content can be set with setText method) inserted in a JPanel component whose paintComponent method is overwritten to draw the image in its Graphics. Sample code:
// Setup code
class ImagePanel extends JPanel{
private Image image;

public void setImage(Image img){
image = img;
repaint();
}

public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null){
g.drawImage(image, 0, 0, this);
}
}
}

ImagePanel panel = new ImagePanel();
JLabel text = new JLabel();
text.setOpaque(false);
panel.add(text);

// Working code
text.setText("Sample Text");
panel.setImage(new ImageIcon("myImage.jpg").getImage());

You can customize the font and color of the text using text.setFont(java.awt.Font) method.
For a multiline text you can use a JTextArea instead of JLabel. For multiple fonts inside the text you can use a JTextPane. For using HTML tags you can use a JEditorPane.

You can also customize the paintComponent method to draw the image tiled or stretched.

by spalasseri

The answer helped me. We too implemented using applets. got the result in a servlet and implemented in our application server atg dynamo.

thanks for the suggestion. The only drawback that we have now is the applet takes few seconds more to load compared to the rest of the page.

thanks
pal

This discussion is closed to new replies.