Get X and Y of a click on an ImageIcon, Java - java

I'm looking to add interactivity to an image but cannot see a way off adding a mouselistener to it. I would like to get the X & Y of where whas clicked on the image.
The Flow if the image is:
tileset = new ImageIcon("xx.png"); //ImageIcon Image that wants to be clicked
label.setIcon(tileset); // assigned to a label
panel.add(label); //assigned to a panel
tileScrollPane = new JScrollPane(panel); // Assigned to a scrollable pane
frame.add(tileScrollPane, BorderLayout.CENTER); // then onto a JFrame

You should be able to add a MouseListener to the label:
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent event) {
// Handle click - coordinates in event.
}
});

Related

Drag and Drop JLabel in top of another JLabel

I have JPanel with two images as JLabels. I'm trying drag right side image and drop it on top of left side image and it should stay there after mouse released. Currently i'm able to drag the image but it goes under the drop location image. Second problem is when I press mouse on image, that location is different from actual image boundaries. How can I get the exact location relative to main panel?
Here is my coding.
public class loadLayout extends JPanel{
#Override
public boolean isOptimizedDrawingEnabled() {
return false;
}
public loadLayout(){
setLayout(new GridLayout(0, 2));
setPreferredSize(new Dimension(600, 400));
setMaximumSize(new Dimension(600, 400));
setMinimumSize(new Dimension(600, 400));
try {
BufferedImage img = ImageIO.read(new File("test.jpg"));
JPanel leftP = new JPanel(null);
JLabel leftL = new JLabel(new ImageIcon(img));
leftL.setSize(img.getWidth(), img.getHeight());
leftL.setLocation(10, 10);
leftP.add(leftL);
JPanel rightP = new JPanel();
BufferedImage img2 = ImageIO.read(new File("dragger.png"));
JLabel rightL = new JLabel(new ImageIcon(img2));
rightL.setSize(img2.getWidth(), img2.getHeight());
rightP.add(rightL);
add(leftP);
add(rightP);
MouseAdapter mouseHandler = new MouseAdapter() {
private Point delta;
#Override
public void mousePressed(MouseEvent e) {
imagePoint = SwingUtilities.convertPoint(rightL, rightL.getX(), rightL.getY(), loadLayout.this);
Point origin = e.getPoint();
Rectangle bounds = new Rectangle(imagePoint, new Dimension(rightL.getWidth(), rightL.getHeight()));
if (bounds.contains(origin)) {
delta = new Point(origin.x - imagePoint.x, origin.y - imagePoint.y);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (delta != null) {
imagePoint = e.getPoint();
imagePoint.translate(-delta.x, -delta.y);
rightL.setLocation(imagePoint);
}
}
#Override
public void mouseReleased(MouseEvent e) {
if(delta != null){
rightL.setLocation(delta);
revalidate();
repaint();
}
delta = null;
}
};
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
} catch (IOException ex) {
Logger.getLogger(DragnDropTest1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Location to press to drag the image.
How it should be after..
I have JPanel with two images as JLabels
Looks to me like you have a panel that contains 2 panels. Each of those panels contains a label. Why do you add each label to a second panel?
Get rid of the "wrapper" panels and just add the labels directly to the main panel.
I'm trying drag right side image and drop it on top of left side image and it should stay there after mouse released
Swing paints components based on Z Order. As a component is added to the panel the ZOrder is increased and the component with the highest ZOrder is painted first, so basically the last component added to the panel is painted first.
So in your case the right label is painted before the left label.
If you want to drag the right label so it is painted AFTER the left label, then in your mousePressed code you can change the ZOrder of the component by using
JPanel parent = e.getComponent().getParent;
parent.setComponentZOrder(e.getComponent(), 0);
Now the component will be painted last as you drag it over the panel.

Remove Panel from layout only

I have a frame where the layout is null. There is a panel attached to it that has a flow layout.
My code has it so that a button press creates a new panel that gets added to the first panel (the one attached to the frame). Then I have a mouse listener that lets you drag the newly created panel around.
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent me) {
x = me.getX();
y = me.getY();
}
});
panel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent me) {
me.translatePoint(me.getComponent().getLocation().x-x, me.getComponent().getLocation().y-y);
panel.setLocation(me.getX(), me.getY());
}
});
However, when I press the button for it to create a new panel, it creates a new panel while returning the it to the flow layout. I've tried removing the panel but when I drag the new panel over it, it gets erased. While if I revalidate and repaint the panel after removing it, it vanishes.
So how do I prevent it from getting erased or remove it from the layout only?
Try changing the layout to null, I don't think what you're asking is possible.

How can I click on a picture and then make that picture appear in a new JFrame? [duplicate]

This question already has answers here:
How to find JLabel that was clicked and show ImageIcon from it?
(2 answers)
Closed 7 years ago.
I have a JFrame opening with 12 different pictures. I want to click on one and then in the new JFrame, show that same picture. In my code, shirts is my JFrame with the 12 pictures and I want the clicked picture to appear in the new JFrame called sizes. I made an ArrayList of type JLabel called select. Here is my code:
final JFrame shirts = new JFrame("T-shirts");
JPanel panel = new JPanel(new GridLayout(4, 4, 3, 3));
for (int i = 1; i < 13; i++) {
l = new JLabel(new ImageIcon("T-shirts/"+i+".jpg"), JLabel.CENTER);
l.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
l.setFont(l.getFont().deriveFont(20f));
panel.add(l);
select.add(l);
}//end of for loop
panel.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
sizes = new JFrame("Shopping");
sizes.setVisible(true);
sizes.setSize(500, 500);
sizes.setLocation(100,200);
shirts.dispose();
for(int i=0; i<12; i++){
if(e.getSource()==select.get(i)){
JLabel addition = newJLabel(newImageIcon(select.get(i).getText()));
//sizes.add(select.get(i));//Picture isn't added!!
}//end of if
}//end of for
}//end of method
});//end of listener
shirts.setContentPane(panel);
shirts.setSize(1000, 1000);
shirts.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
shirts.setVisible(true);
Start with How to Write a Mouse Listener.
Basically, you want to register a MouseListener with the JLabel which represents your picture and implement it's mouseClicked method.
You then want to get the Icon property of the JLabel that was clicked and pass that to your new frame, which you can simply use to set the Icon property of another JLabel
Something like...
addition.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel) e.getComponent();
Icon icon = label.getIcon();
// Create new frame and pass it the icon value
}
});
as an example
You might also like to take a look at The Use of Multiple JFrames, Good/Bad Practice? and consider using either a CardLayout or JDialog instead of another JFrame ... which could become messy
You can use a JButton and make it look like a JLabel:
JButton button = new JButton( new ImageIcon("..." ));
button.setBorderPainted( false );
button.setContentFilled( false );
button.setFocusPainted( false );
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
Icon icon = button.getIcon();
// do something with the Icon.
}
});
Then you can add an ActionListener to the button.
An ActionListener is more reliable than using a MouseListener and handling the mouseClicked event. The mouseClicked event is only generated when a mousePressed and mouseReleased event is generated at the same mouse point. So if the mouse moves by even pixel between the two event you will not get a mouseClicked event which users think is a random problem.
Try making each picture a JButton, or at least placing an invisible button behind each picture. Then, when they are pressed in the ActionListener extended class, have the new JFrame be created, with the picture large.

Text not displayed when mouse is rolled over JLabel

With NetBeans (Java), I am having problems in JLabel. I have assigned an image as the icon of that JLabel.
Problem - 1st:
I want to display some text (e.g - logout) below that icon (image). How to do this?
Problem - 2nd:
I want to display some text when mouse is rolled over that JLabel. What should I do?
So , please guys tell me how to these things by writing code.
I recommend reading the basic Oracle tutorials which describe in detail how to accomplish this. You can use a MouseMotionListener to determine when the mouse is rolled over the JLabel, and you can position the JLabel text underneath the Icon of the JLabel by setting its vertical text position as described in the JLabel Tutorial. This should have all been found with a simple internet search of your questions, something that your question suggests was not done (and should have been) before asking
1.
Create a JPanel that contains two JLabels. This way you can control the layout of the internal components.
I used BoxLayout with the parameter BoxLayout.Y_AXIS to get the label below the icon.
2.
Add a MouseListener using the method component.addMouseListener(new MouseAdapter() { ... });, you'll need to create a MouseAdapter and implement any methods you need (click here).
Here is a working example for you buddy... Adapt this however you need to.
Note: You'll need to change the file-path of the ImageIcon()
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel container = new JPanel();
JPanel iconLabelPanel = new JPanel();
String TEXT_FIELD_TEXT = "Hover over the logout label.";
JLabel icon = new JLabel(new ImageIcon("C:\\Users\\Gary\\Google Drive\\Pictures\\puush\\ss (2015-02-19 at 06.00.00).png"));
JLabel label = new JLabel("Logout!");
JTextField textField = new JTextField(TEXT_FIELD_TEXT);
//Add a mouse motion listener for the JLabel
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
//Set text of another component
textField.setText("You're over Logout!");
}
#Override
public void mouseExited(MouseEvent e) {
//Set text of another component
textField.setText(TEXT_FIELD_TEXT);
}
});
//Add components and set parameters for iconLabelPanel
iconLabelPanel.setLayout(new BoxLayout(iconLabelPanel, BoxLayout.PAGE_AXIS));
iconLabelPanel.add(icon);
iconLabelPanel.add(label);
//Add components and set parameters for container
container.setLayout(new BoxLayout(container, BoxLayout.PAGE_AXIS));
container.add(iconLabelPanel);
container.add(textField);
//Set parameters for frame
frame.add(container);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400, 400);
frame.setVisible(true);
}

Java. Swing. Absolute position

I need to set component's location in a window.
I need to draw component on a GlassPane near another component, which was clicked. I pass the component, which raises click event to some manager, there I want to get coordinates where to paint.
public void mouseClicked(MouseEvent e) {
ApplicationManager.getInstance().drawOnGlassPane((Component e.getSource());
}
public void drawOnGlassPane(final Component caller) {
mainFrame = (JFrame) SwingUtilities.getWindowAncestor(caller);
JPanel glassPane = (JPanel) mainFrame.getGlassPane();
glassPane.setVisible(true);
Point where = caller.getLocationOnScreen();
JButton btn = new JButton("on glass pane");
btn.setBounds((int) where.getX(), (int) (where.getY() + caller.getHeight()), 50, 20);
glassPane.add(btn);
}
}
The new component appears in a wrong place. How could I set correct location?
this question is described including example in the tutorial about How to Use Root Panes, another example here and here

Categories