0

I´m new with JLabel, i wonder if it's possible to set the text in a coordenate specific (x,y) over an image.

Like this:

enter image description here

So the text is "HI"

 label.setText("HI");
 label.setIcon(icon);

I'm trying to say that label contains an image and a text but i want to locate it in a specific position like the image above.

I don't want to use label.setHorizontalTextPosition(i); or setVerticalTextPosition(i);

Sorry for my bad english Thanks in advance ^ ^

Luisk4
  • 377
  • 1
  • 5
  • 12
  • Is this what you looking for? `label.setBounds(x, y, width, height);` – aleksandar Mar 28 '16 at 21:33
  • no, i want to locate the text of an JLabel that contains an image at specific position. I don't speak english very well so it's difficult to explain me – Luisk4 Mar 28 '16 at 21:40
  • Possible duplicate of [Placing a JLabel at a specific x,y coordinate on a JPanel](http://stackoverflow.com/questions/12119327/placing-a-jlabel-at-a-specific-x-y-coordinate-on-a-jpanel) – OneCricketeer Mar 28 '16 at 21:43
  • Pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Mar 28 '16 at 21:48

3 Answers3

3

By overriding the paintComponent method, text can be drawn in any position.

JLabel label = new JLabel(icon) {
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("Hi", 10, 10); //these are x and y positions
    }
};
rdonuk
  • 3,921
  • 21
  • 39
3

There are any number of, reasonable, ways to do it.

However, you should avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

GridBagLayout and GridBagConstraints#insets

Example

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            setLayout(new GridBagLayout());
            BufferedImage img = ImageIO.read(...);
            JLabel background = new JLabel(new ImageIcon(img));
            background.setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(1, 46, 9, 0);
            gbc.anchor = GridBagConstraints.SOUTH;
            gbc.weighty = 1;

            JLabel message = new JLabel("Go that way!");
            message.setVerticalAlignment(JLabel.BOTTOM);
            background.add(message, gbc);

            add(background);
        }

    }

}

Graphics2D

You could paint the text directly onto the image, but as you can see, it becomes considerably more complex

Image

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            JLabel background = new JLabel();

            BufferedImage img = ImageIO.read(...);
            Graphics2D g2d = img.createGraphics();
            g2d.setFont(background.getFont());
            String text = "Go that way!";
            FontMetrics fm = g2d.getFontMetrics();

            int x = 46 + (((img.getWidth() - 46) - fm.stringWidth(text)) / 2);
            int y = (((img.getHeight() - fm.getHeight())) + fm.getAscent()) - 9;
            g2d.setColor(Color.BLACK);
            g2d.drawString(text, x, y);
            g2d.dispose();

            background.setIcon(new ImageIcon(img));
            add(background);
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You can follow this Example, also take a look on setLocation() method for Components like JLabel, also try to use Layouts to manage better the position for each Component.

This guy also work with location with JLabel, you can see how he does the work and apply it in your project.

Example

JLabel label = new JLabel("Hi");
panel.add(label);
//This is to get the width and height
Dimension size = label.getPreferredSize();
//You can change 100(x) and 100(y) for your likes, so you can put that JLabel wherever you want
label.setBounds(100, 100, size.width, size.height);

You'll have to know what x and what y you want to put the JLabel right there.

If you want to do that, just do what tong1 did, but showing the x and y to know where exactly you want it.

Create a Container

Container container= getContentPane();

Add the JLabel on it

container.add(label);

Add an MouseListener() to get the x and y

container.addMouseListener(new MouseAdapter(){ 
        public void mouseClicked(MouseEvent e){
        //x and y are ints.
            x = e.getX();
            y = e.getY();
            label.setBounds(x,y,150,50);
        }
    });
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • [*"Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline."*](http://stackoverflow.com/help/how-to-answer) – MadProgrammer Mar 28 '16 at 21:47
  • @MadProgrammer updated, that is clear or shall I put more information? – Skizo-ozᴉʞS ツ Mar 28 '16 at 21:54
  • But, there is not a way to do it in the same JLabel (the image and text)? – Luisk4 Mar 28 '16 at 22:00