This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I would like to add an Image to JPanel after the Mouse Click. I've read dozens of information about this topic, however have a problem...I've tried three different variants of code to add an image, however each time got just a blank screen - no picture. Pliz help.
Thanks! Everything is ok now This is the workable code:
Maybe someone could also advise me how to move the created JLabel: label with the mouse on the screen? I'd like to allow the user to position the images on the screen. I've used label.setLocation(MouseInfo.getPointerInfo().getLocation().x-jPanel1.getX(),MouseInfo.getPointerInfo().getLocation().y-jPanel1.getY()); inside the private void jLabel1MousePressed(java.awt.event.MouseEvent evt). However, it doesn't work.
To position components manually you must set its layout manager to null. However, this also means that you must set the preferred size manually. After that you can use setLocation or setBounds to place the component. Note that without a layout manager the added component will initially have a size of 0x0. By calling you can give it its desired size, then use setLocation to move it around.
If you want to drag your label around you should try searching first. There are quite some examples for that.
Joined: Aug 24, 2010
Thanks a lot! I've updated the code by setting null layout manager and positioning JLabel: label by hand. Everything works correctly!
However, if I want JLabel: label to respond on my mouse click and get a position of the mouse cursor, then it doesn't work. What makes me confused is that MouseEvent is set to JLabel: jLabel1 and not to JLabel: label...Could someone tell me how to set the event handling to JLabel: label? Maybe some web links...? Now I have the following code (it doesn't work in the way I want):
Joined: Aug 24, 2010
This is how I try to solve my problem (still doesn't work correctly):