Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The easy way is to use a JLabel with an Icon and Text. Then set the horizontal/vertical text position to CENTER and the text is painted in the center of the image.</p> <p>From your code it looks like you are trying to paint the text near the bottom of the image. In this case you can use the JLabel with an Icon as a container. Then you can set the layout to something like a BoxLayout and add another label with the text.</p> <p>No custom painting is required for either approach.</p> <pre><code>import java.awt.*; import javax.swing.*; public class LabelImageText extends JPanel { public LabelImageText() { JLabel label1 = new JLabel( new ColorIcon(Color.ORANGE, 100, 100) ); label1.setText( "Easy Way" ); label1.setHorizontalTextPosition(JLabel.CENTER); label1.setVerticalTextPosition(JLabel.CENTER); add( label1 ); JLabel label2 = new JLabel( new ColorIcon(Color.YELLOW, 200, 150) ); label2.setLayout( new BoxLayout(label2, BoxLayout.Y_AXIS) ); add( label2 ); JLabel text = new JLabel( "More Control" ); text.setAlignmentX(JLabel.CENTER_ALIGNMENT); label2.add( Box.createVerticalGlue() ); label2.add( text ); label2.add( Box.createVerticalStrut(10) ); } public static class ColorIcon implements Icon { private Color color; private int width; private int height; public ColorIcon(Color color, int width, int height) { this.color = color; this.width = width; this.height = height; } public int getIconWidth() { return width; } public int getIconHeight() { return height; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(color); g.fillRect(x, y, width, height); } } private static void createAndShowUI() { JFrame frame = new JFrame("LabelImageText"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add( new LabelImageText() ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible( true ); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } </code></pre> <blockquote> <p>I mean I have to write a text in the center of the image and then save the image</p> </blockquote> <p>You can use <a href="http://tips4java.wordpress.com/2008/10/13/screen-image/">Screen Image</a> to create an image of any component. This assumes you are displaying the image and text on a GUI.</p> <p>Or, if you are talking about just reading in an image adding text to the image and then saving the image, then you will need to create a BufferedImage and draw the image on it and then draw the text on it. You will need to use the FontMetrics class as mentioned by Trashgod. My suggestion won't help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload