Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

java - Drag and move a picture inside a JLabel with mouseclick

I have an image inside a JLabel.

JLabel label = new JLabel(new ImageIcon("C:\image.jpg"));
label.setSize(300,300);

I want the following functionality.

-I click on a location inside the JLabel (on the image).

-With the mousebutton pressed, I can change the location of the image within the JLabel. (I drag the picture to different positions within the JLabel)

Well, this means that in many instances the picture will be cropped and outside of view.

Please tell me how to implement this functionality?

What are the correct event listeners to add to my JLabel?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First, I would recommended using a layout instead of setLayout(null) and setBounds(). Secondly, seperate the ImageIcon from the JLabel. Finally, set the JLabel and the ImageIcon as fields instead of a local variable.

You need to add a MouseListener and a MouseMotionListener.

label.addMouseMotionListener(new MouseAdapter()
{
    public void mouseMoved(MouseEvent arg0)
    {
        if(clicked)
        {
            label.x++
            label.y++
            label.repaint();
        }
    }
});

label.addMouseListener(new MouseAdapter()
{
    public void mousePressed(MouseEvent arg0)
    {
        clicked = !clicked;
    }
});

(Sorry for being wordy beforehand)

This causes the image of the label to appear where the label is, and when you your mouse over it it will move diagonal southeast. I created a new label class, where I override paintComponent and added in there a paint image icon method, where the x and y are variables. The idea will be to calculate a center point on your label, then move the x position of the image west if going west of that point (x--), south if going south(y--), ect. This would only move your image inside the label. If your mouse if outside of the label, the moving would stop. If parts of the image are outside of the label, then that part will not be shown. I would override paint compoent in your label class and move the image over, then set the icon for each movement.

public class Label1 extends JLabel
{
    public int x;
    public int y;
    ImageIcon imageIcon = new ImageIcon("path");

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
//No setLocation(x, y) method exists for an image icon or an image. You are on your own on this
        imageIcon.setLocation(x, y);
        label.setIcon(imageIcon);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...