Java – setlocation in jlabel

My task is to get the position of the mouse when I click, except for one thing: the position of the output I should get this on the first click, but only double clicking can get the correct output:

This is the first click I got, regardless of the location:

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);
    }
 }

Solution

JPanel, but by default, is using layoutmanager. Usually I will prevent you from trying to use it, but in your case, you may not have a choice

Usually, I'll consider writing a layout manager that can solve this problem, but it's beyond the scope of requirements

Instead, first set the layout manager of the panel to null

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

Now that you have completed this work, you are fully responsible for the management of the component about its size and location. Therefore, when mouseClick is called, you need to set the text, location and size of the label, such as

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 the layout out components within a container to learn more about the functionality of the Layout Manager API and how it works

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>