Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SetLocation in JLabel

My assignment is getting the position of the mouse when clicked, and I'm pretty much done except for one thing: the position of my output. I am supposed to get this on the first click, but I get the correct output only if double clicked:

enter image description here

Here's what I get for the first click regardless of the position:

enter image description here

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Mouse {
public static void main(String[] args) {

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JLabel label = new JLabel();
    frame.add(panel);
    panel.add(label);
    panel.addMouseListener(new MouseAdapter() {
       @Override
        public void mouseClicked(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            label.setLocation(x,y);
            label.setText("(" + x + "," + y + ")");
        }
    });
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);
    }
 }
like image 305
imaginedrragon Avatar asked Jan 31 '26 12:01

imaginedrragon


2 Answers

JPanel, but default, is using a LayoutManager, normally I would discourage the you from trying to do with out it, but in your case, you might not have a choice.

Normally, I'd consider writing a layout manager which could deal with this, but that's beyond the scope of the requirements.

Instead, start by setting the panel's layout manager to null

JFrame frame = new JFrame();
JPanel panel = new JPanel(null);

Now you've done that, you become completely responsible for the management of the component, with regards to it's size and position, so, when mouseClicked is called, you need to set the text, location AND size of the label, for example.

panel.addMouseListener(new MouseAdapter() {
   @Override
    public void mouseClicked(MouseEvent e) {
        int x = e.getX();
        int y = e.getY();
        label.setLocation(x,y);
        label.setText("(" + x + "," + y + ")");
        label.setSize(label.getPreferredSize());
    }
});

Take a closer look at Laying Out Components Within a Container for more details about what the layout manager API does and how it works

like image 97
MadProgrammer Avatar answered Feb 03 '26 02:02

MadProgrammer


Option 2 is to display the text within a JPanel's paintComponent method. This way you wouldn't have to worry about using the dreaded null layout manager. For example:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class MousePosition extends JPanel {
    private static final int PREF_W = 600;
    private static final int PREF_H = PREF_W;
    // format String for display String
    protected static final String FORMAT = "(%d, %d)";
    private int xPos = -40;
    private int yPos = -40;
    private String displayText = "";

    public MousePosition() {
        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xPos = e.getX();
                yPos = e.getY();
                // use FORMAT String to create our display text
                displayText = String.format(FORMAT, xPos, yPos);
                repaint();
            }
        });
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString(displayText, xPos, yPos);

    }

    private static void createAndShowGui() {
        MousePosition mainPanel = new MousePosition();

        JFrame frame = new JFrame("MousePosition");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}
like image 44
Hovercraft Full Of Eels Avatar answered Feb 03 '26 03:02

Hovercraft Full Of Eels