Draw image icon on JLabel

Does anyone know how I can paint an icon on an already existing JLabel image without having the original image disappear partially or completely?
The way I have it set up right now is that the original image listens to MouseListener, and displays information on a textArea when I click on the map.
What I wish to do is to display an icon on the map image whenever I click on it.
I'm a rather amateur with Java, and don't know how to make interfaces interact with eachother, no matter how hard I try. I need to know if I can add something to my current code to get what I want. I have had tried to interact different classes with eachother, but I haven't been getting what I wanted. Please help me out!
I know how to display the icon on another panel, and make it move. but not on the same panel on the original picture.
Here's my code:
package screem.netrol.communication.event;
* @author Nazli
import java.awt.*;
import java.awt.image.*;
import java.awt.Component;
import java.awt.Image;
import java.awt.Color;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.net.*; // For class URL.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.MouseInputAdapter;
import java.applet.*;
public class MyMapPanel extends JPanel implements DataTurbineListener, MouseListener, ImageObserver
final static String newline = "\n";
JTextArea textArea; //= new JTextArea();
public static String url;
public static ImageIcon ic;
public static ImageIcon ic2 = new ImageIcon("http://www-jkn.ee.uec.ac.jp/tnklab/96/nakazawa/icons/colorball/small/BALL120.gif");
public static JLabel mapArea;
//public static JApplet mapArea;
//public static File output = new File("results.txt");
public static boolean showPoint;
public static int x;
public static int y;
private BufferedImage bufImg ;
private Image smallImg ;
int w;
int h;
/*public static BufferedImage bufImg ;
public static Image smallImg ; */
/* GeneralPath path;
final int PAD = 20;
final int N = 8; */
public static MyJFrame f;
public MyMapPanel() {}
public MyMapPanel(ImageIcon ic)
super(new FlowLayout (FlowLayout.CENTER, 0,0));
textArea = new JTextArea();
setImageIcon(ic);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(700,100));
//getContentPane().add(new MyPanel(), BorderLayout.CENTER);
//addMouseListener( new MusClk() ) ;
protected class MusClk extends MouseAdapter {
public void mouseClicked ( MouseEvent musEvt ) {
if( musEvt.getX() > bufImg.getWidth() || musEvt.getY() > bufImg.getHeight() ) {
return ;
Graphics g = bufImg.getGraphics() ;
int w = smallImg.getWidth( null ) ;
int h = smallImg.getHeight( null ) ;
g.drawImage( smallImg , musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , null ) ;
MyMapPanel.this.repaint( musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , w , h ) ;
public ImageIcon getImageIcon()
setImageIcon(ic);
return ic;
public void setImageIcon(ImageIcon ic)
//MyPanel panel = new MyPanel();
try{
URL u = new URL(url);
ic = new ImageIcon(u);
} catch (MalformedURLException e) {
System.out.println (e);
mapArea = new JLabel(ic, JLabel.CENTER);
add(mapArea);
mapArea.addMouseListener(this);
try {
URL u = new URL(url);
ic = new ImageIcon(u);
} catch (MalformedURLException e){
System.out.println(e);
mapArea = new JApplet();
add(mapArea);
mapArea.addMouseListener(this); */
/* public void setMouseEvent(MouseEvent e)
x = e.getX();
y = e.getY();
showPoint = true;
protected void paintComponent(Graphics g){ }
public void dataTurbineOutputEvent(DataTurbineEvent event){}
public void dataTurbineInputEvent(DataTurbineEvent event){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e) { }
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e)
//setMouseEvent(e);
//System.out.println("x="+x+" y="+y);
showPoint = true;
ImageIcon icon = new ImageIcon("C:/Documents and Settings/Nazli/My Documents/My Pictures/ball.gif");
w = icon.getIconWidth();
h = icon.getIconHeight();
bufImg = new BufferedImage(w , h , BufferedImage.TYPE_INT_RGB ) ;
Graphics g = bufImg.getGraphics();
g.drawImage( icon.getImage() , 0 , 0 , null ) ;
//MyMapPanel.this.repaint(e.getX() - w / 2 , e.getY() - h / 2 , w , h ) ;
/*Point p = e.getPoint();
Rectangle tag;
final int SIDE = 6;
tag = new Rectangle(0, 0, SIDE, SIDE);
float x = e.getX();
float y = e.getY();
tag.setLocation(p.x - SIDE/2, p.y - SIDE/2);
if(tag.contains(p.x,y))
showPoint = true;
setPoint(p);
//System.out.println("e.getX="+e.getX()+""+"e.getY="+e.getY());
saySomething("Position in pixels:(" + e.getX() + ", " + e.getY() + ")", e);
String s1 = computeLatLong(e.getX());
String s2 = computeLatLong(e.getY());
saySomething("Position in Lat/Long: (" + s1 + ", " + s2 + ")", e);
//g.drawImage(img, e.getX(), e.getY(), this);
//DrawImage d = new DrawImage();
//public void mouseClicked ( MouseEvent musEvt ) {
//DrawImage d = new DrawImage();
void saySomething(String eventDescription, MouseEvent e)
textArea.append(eventDescription + " detected on " + e.getComponent().getClass().getName() + "." + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
public String computeLatLong(double d)
double d1;
double seconds;
double minutes;
double m;
double s;
String rval;
d1 = d - Math.floor(d);
seconds = d1 / 3600;
minutes = seconds / 60;
m = minutes - Math.floor(minutes);
s = m * 60; //minutes converted to seconds
rval = (int)Math.floor(d) + "deg " + (int)minutes + "' " + (int)s + '"';
return rval;
public MyJFrame getFrame()
return f;
public static void main(String[] args) throws IOException {
//DrawImage d = new DrawImage();
System.out.println("x="+x+" y="+y);
ArrayList file = new ArrayList();
File input = new File("lat_lon.txt");
FileReader in = new FileReader(input);
File output = new File("archive3.txt");
FileWriter out = new FileWriter(output);
//FileWriter in2 = new FileWriter(input);
FileOutputStream outdata = new FileOutputStream(output);
PrintStream p = new PrintStream(outdata);
BufferedReader br = new BufferedReader(in, 4096);
BufferedWriter bw = new BufferedWriter(new FileWriter("lat_lon.txt", true));
String line; //each line in input file
String s=null; //Main string containing points information, to be written to the output file
while ((line = br.readLine()) != null )
file.add(line);
StringTokenizer st = new StringTokenizer(line,";");
while(st.hasMoreTokens())
s = st.nextToken();
p.println(s);
p.println("FINISHED DATA TRANSFER");
p.println("\n");
bw.write("DATA TRANSFERRED TO OUTPUT FILE");
bw.newLine();
bw.flush();
p.close();
//pops up the input dialogue window for the user to enter the image URL
url = JOptionPane.showInputDialog(null,"Provide image URL:\n","Map Image", JOptionPane.PLAIN_MESSAGE);
MyMapPanel panel = new MyMapPanel();
if(url != null)
panel.setImageIcon(ic);
MyMapPanel mp = new MyMapPanel(ic);
MyPanel panel2 = new MyPanel();
//MyMapPanel mp2 = new MyMapPanel();
JFrame jf = new JFrame();
f = new MyJFrame(700,400);
f.getContentPane().add(mp);
//f.getContentPane().add(panel2);
public static class MyJFrame extends JFrame {
// Constructor.
public MyJFrame (int width, int height)
// Set the title and other frame parameters.
this.setTitle ("GPS Map");
this.setResizable (true);
this.setSize (width, height);
// Create and add the panel.
MyMapPanel panel = new MyMapPanel();
//MyPanel p = new MyPanel();
//this.getContentPane().add (panel);
this.getContentPane().add(panel);
// Show the frame.
this.setVisible (true);
}

Hi,
I'm sorry that I didn't use the buttons to make the code readable for you. and I'm sure you don't want to hear how hectic my mind has been for the past few weeks, so I'm not going to explain why I didn't pay attention to the formatting. Although, I think it could have been possible to address my mistake in a less aggressive manner.
Here's my code in a better readable format. I appreciate your advice, it looks so much better now. I'd very much appreciate it if you can go over it.
In regards to your previous solution, I have to say that I've tried it before, but it hasn't worked for me, possibly because I'm not sure how to use it.
* @author Nazli
import java.awt.*;
import java.awt.image.*;
import java.awt.Component;
import java.awt.Image;
import java.awt.Color;
import javax.swing.*;
import javax.swing.ImageIcon;
import java.net.*; // For class URL.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.io.*;
import java.util.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.MouseInputAdapter;
import java.applet.*;
public class MyMapPanel extends JPanel implements DataTurbineListener, MouseListener, ImageObserver
final static String newline = "\n";
JTextArea textArea; //= new JTextArea();
public static String url;
public static ImageIcon ic;
public static ImageIcon ic2 = new ImageIcon("http://www-jkn.ee.uec.ac.jp/tnklab/96/nakazawa/icons/colorball/small /BALL120.gif");
public static JLabel mapArea;
//public static JApplet mapArea;
//public static File output = new File("results.txt");
public static boolean showPoint;
public static int x;
public static int y;
private BufferedImage bufImg ;
private Image smallImg ;
int w;
int h;
/*public static BufferedImage bufImg ;
public static Image smallImg ; */
/* GeneralPath path;
final int PAD = 20;
final int N = 8; */
public static MyJFrame f;
public MyMapPanel() {}
public MyMapPanel(ImageIcon ic)
super(new FlowLayout (FlowLayout.CENTER, 0,0));
textArea = new JTextArea();
setImageIcon(ic);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(700,100));
//getContentPane().add(new MyPanel(), BorderLayout.CENTER);
//addMouseListener( new MusClk() ) ;
protected class MusClk extends MouseAdapter {
public void mouseClicked ( MouseEvent musEvt ) {
if( musEvt.getX() > bufImg.getWidth() || musEvt.getY() > bufImg.getHeight() ) {
return ;
Graphics g = bufImg.getGraphics() ;
int w = smallImg.getWidth( null ) ;
int h = smallImg.getHeight( null ) ;
g.drawImage( smallImg , musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , null ) ;
MyMapPanel.this.repaint( musEvt.getX() - w / 2 , musEvt.getY() - h / 2 , w , h ) ;
public ImageIcon getImageIcon()
setImageIcon(ic);
return ic;
public void setImageIcon(ImageIcon ic)
//MyPanel panel = new MyPanel();
try{
URL u = new URL(url);
ic = new ImageIcon(u);
} catch (MalformedURLException e) {
System.out.println (e);
mapArea = new JLabel(ic, JLabel.CENTER);
add(mapArea);
mapArea.addMouseListener(this);
try {
URL u = new URL(url);
ic = new ImageIcon(u);
} catch (MalformedURLException e){
System.out.println(e);
mapArea = new JApplet();
add(mapArea);
mapArea.addMouseListener(this); */
/* public void setMouseEvent(MouseEvent e)
x = e.getX();
y = e.getY();
showPoint = true;
protected void paintComponent(Graphics g){ }
public void dataTurbineOutputEvent(DataTurbineEvent event){}
public void dataTurbineInputEvent(DataTurbineEvent event){}
public void mouseReleased(MouseEvent e){}
public void mousePressed(MouseEvent e) { }
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e)
//setMouseEvent(e);
//System.out.println("x="+x+" y="+y);
showPoint = true;
ImageIcon icon = new ImageIcon("C:/Documents and Settings/Nazli/My Documents/My Pictures/ball.gif");
w = icon.getIconWidth();
h = icon.getIconHeight();
bufImg = new BufferedImage(w , h , BufferedImage.TYPE_INT_RGB ) ;
Graphics g = bufImg.getGraphics();
g.drawImage( icon.getImage() , 0 , 0 , null ) ;
//MyMapPanel.this.repaint(e.getX() - w / 2 , e.getY() - h / 2 , w , h ) ;
/*Point p = e.getPoint();
Rectangle tag;
final int SIDE = 6;
tag = new Rectangle(0, 0, SIDE, SIDE);
float x = e.getX();
float y = e.getY();
tag.setLocation(p.x - SIDE/2, p.y - SIDE/2);
if(tag.contains(p.x,y))
showPoint = true;
setPoint(p);
//System.out.println("e.getX="+e.getX()+""+"e.getY="+e.getY());
saySomething("Position in pixels:(" + e.getX() + ", " + e.getY() + ")", e);
String s1 = computeLatLong(e.getX());
String s2 = computeLatLong(e.getY());
saySomething("Position in Lat/Long: (" + s1 + ", " + s2 + ")", e);
//g.drawImage(img, e.getX(), e.getY(), this);
//DrawImage d = new DrawImage();
//public void mouseClicked ( MouseEvent musEvt ) {
//DrawImage d = new DrawImage();
void saySomething(String eventDescription, MouseEvent e)
textArea.append(eventDescription + " detected on " + e.getComponent().getClass().getName() + "." + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
public String computeLatLong(double d)
double d1;
double seconds;
double minutes;
double m;
double s;
String rval;
d1 = d - Math.floor(d);
seconds = d1 / 3600;
minutes = seconds / 60;
m = minutes - Math.floor(minutes);
s = m * 60; //minutes converted to seconds
rval = (int)Math.floor(d) + "deg " + (int)minutes + "' " + (int)s + '"';
return rval;
public MyJFrame getFrame()
return f;
public static void main(String[] args) throws IOException {
//DrawImage d = new DrawImage();
System.out.println("x="+x+" y="+y);
ArrayList file = new ArrayList();
File input = new File("lat_lon.txt");
FileReader in = new FileReader(input);
File output = new File("archive3.txt");
FileWriter out = new FileWriter(output);
//FileWriter in2 = new FileWriter(input);
FileOutputStream outdata = new FileOutputStream(output);
PrintStream p = new PrintStream(outdata);
BufferedReader br = new BufferedReader(in, 4096);
BufferedWriter bw = new BufferedWriter(new FileWriter("lat_lon.txt", true));
String line; //each line in input file
String s=null; //Main string containing points information, to be written to the output file
while ((line = br.readLine()) != null )
file.add(line);
StringTokenizer st = new StringTokenizer(line,";");
while(st.hasMoreTokens())
s = st.nextToken();
p.println(s);
p.println("FINISHED DATA TRANSFER");
p.println("\n");
bw.write("DATA TRANSFERRED TO OUTPUT FILE");
bw.newLine();
bw.flush();
p.close();
//pops up the input dialogue window for the user to enter the image URL
url = JOptionPane.showInputDialog(null,"Provide image URL:\n","Map Image", JOptionPane.PLAIN_MESSAGE);
MyMapPanel panel = new MyMapPanel();
if(url != null)
panel.setImageIcon(ic);
MyMapPanel mp = new MyMapPanel(ic);
MyPanel panel2 = new MyPanel();
//MyMapPanel mp2 = new MyMapPanel();
JFrame jf = new JFrame();
f = new MyJFrame(700,400);
f.getContentPane().add(mp);
//f.getContentPane().add(panel2);
public static class MyJFrame extends JFrame {
// Constructor.
public MyJFrame (int width, int height)
// Set the title and other frame parameters.
this.setTitle ("GPS Map");
this.setResizable (true);
this.setSize (width, height);
// Create and add the panel.
MyMapPanel panel = new MyMapPanel();
//MyPanel p = new MyPanel();
//this.getContentPane().add (panel);
this.getContentPane().add(panel);
// Show the frame.
this.setVisible (true);
}

Similar Messages

  • Need help in displaying an Image in a JLabel

    Hi everyone,
    I am using a JLabel to display images on a particular screen. I am facing some problem while doing so..
    On my screen there are images of some garments. When the users select colors from a particular list, i should color this garment images and load it on the screen again with the colors. I have a floodfill class for filling the colors in the images. The problem I am facing is I am able to color the image properly with my floodfill class but when displaying the image on the same jlabel, the image gets distorted somehow.
    Everytime I color the image, I create an ImageIcon of the image and use the seticon method from the JLabel class. First I set the icon to null and then set it to the imageicon created. here is the code I use.
    If 'image' is the the image i have to load
    ImageIcon imgicon = new ImageIcon(image);
    jlabel.setIcon(null);
    jlabel.setIcon(imgicon);I am setting the icon to null because I have not found any other method to clear the previous image from the jlabel.
    Can anyone who has worked on images before and faced a similar situation help me with this?? Is there some other container I can use besides the JLabel to display the images perhaps?
    Thanks in advance.....
    Bharat

    And the thing is when I first go into that screen with the selected colors it is displaying the images perfectly.
    It is only giving problems when I pick different colors on the screenit really sounds like the problem is in your floodfill class.
    I have no idea what's in floodfill, but if you were e.g. using a JPanel and paintComponent,
    you would need to have as the first line in paintComponent()
    super.paintComponent(..);
    to clear the previous painting.
    if not, you would be just drawing over the top of the previous paintComponent(), and if the calculation of the
    painting area is not 100% exact, you may get the odd pixel not painted-over, meaning those pixels will display
    the old color.

  • How to add tool tips on Image Icon obj?

    how to add tool tips on Image Icon obj?

    Take a look at the link shown below where drawing is done on a JButton -- you can draw your image on a JLabel too.
    http://developer.java.sun.com/developer/TechTips/1999/tt0826.html
    By drawing on a JLabel or JButton, you can add tooltiptext when needed.
    ;o)
    V.V.

  • Having a problem with image IO and drawing image

    My question did not come out on the other posting. I am getting them image from a JPanel. I then convert the image into a renderedimage. Use the ImageIO.write method to convert to png format. I don't want to save the image on the local disk so it is writted to a ByteArrayOutputStream. I get the bytes from this and insert this into a blob field type.
    Then to paint the image onto the JPanel I try two methods to paint it on to the JPanel. I set the JPanel to be the width and size of the image. But I am getting a null pointer exception and I can't figure out why. If anyone could give me any suggestions I would really appreciate it.
    rImage = convertToRenderedImage(draw.drawPanel.offScreen, width11, drawPanelHeight, type);
    try{
    bo = new ByteArrayOutputStream();
    ImageIO.write(rImage, "png", bo);
    imageBytes = bo.toByteArray();
    }catch(IOException iox3)
    System.err.println(iox3);
    PreparedStatement statement12 = connection.prepareStatement(
    "INSERT INTO feed VALUES(?,?,?,?,?,?);");
    statement12.setBytes(2, imageBytes);
    icon = new ImageIcon(rs.getBytes("file"));
    image = icon.getImage();
    //base is the JPanel
    Graphics g2d = base.getGraphics();
    bytes = rs.getBytes("file");
    bInput = new ByteArrayInputStream(bytes);
    try
    bImage = ImageIO.read(bInput);
    catch(IOException e21)
    System.out.println("Error in imageIO transformation");
    //image is Image and bimage is bufferedimage
    image = bImage;
    Graphics g2d = base.getGraphics();
    g2d.drawImage(image, 0, 0, base);
    g2d.drawImage(image, 0, 0, base);

    Would it be possible for you to send out a small runnable testcase that I could try out with?
    Thanks,
    Kannan

  • How do you make an array of image icons and then call them?

    How do you make an array of image icons and then call them, i have searched all over the internet for making an array of icons, but i have
    found nothing. Below is my attempt at making an array of icons, but i cant seem to make it work. Basically, i want the image to match the value of the roll of the dice (rollVal)
    Any help would be greatly appreciated, some code or link to tuturial, ect.
    /** DiceRoller.java
    * Roll, print, Gui
    import javax.swing.*;
    public class DiceRoller extends JFrame
         private ImageIcon[] image  ;
         public String[] images = { "empty", "dice1.jpg",
                   "dice2.jpg", "dice3.jpg", "dice4.jpg",
                   "dice5.jpg", "dice6.jpg" };
         public Dice die;
         private int rollVal;
         public int rollNum;
         private JLabel j1;
         public DiceRoller(){
              j1= new JLabel("");
           die =new Dice();
           int rollVal;
           rollVal = die.roll();     
           image = new  ImageIcon[images.length];
         for(int i = 0; i < images.length; i++){
          image[i] = new ImageIcon(images);
         if (image!=null){
              j1.setIcon(image[rollVal]);
         System.out.println("Roll = "+die.roll());

    Demo:
    import java.awt.*;
    import java.net.*;
    import javax.swing.*;
    public class IconExample {
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    launch();
        static void launch() {
            try {
                Icon[] icons = new Icon[6];
                for(int i=0; i<icons.length; ++i) {
                    String url = "http://www.eureka-puzzle.be/cast/images/dice" + (i + 1) + ".jpg";
                    icons[i] = new ImageIcon(new URL(url));
                display(icons);
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
        static void display(Icon[] icons) {
            JPanel cp = new JPanel();
            for(Icon icon : icons) {
                cp.add(new JLabel(icon));
            JFrame f = new JFrame();
            f.setContentPane(cp);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • How to add multiple images to a JLabel from the jar file

    I want to add multiple images in a JLabel but the icon property only allows me to add one. I thought I could use html rendering to add the images I need by using the <img> tab, but I need to use a URL that points to the image.
    How do I point to an image inside the jar file? If I can't, is there another way to show multiple images in a JLabel from the jar file?

    Thanks, it works perfectly. It's a really smart way of fixing the problem too :)
    I also found your toggle button icon classes which is something I've also had a problem with.
    Thanks.

  • How to change this code to drag and drop image/icon into it??

    Dear Friends:
    I have following code is for drag/drop label, But I need to change to drag and drop image/icon into it.
    [1]. code 1:
    package swing.dnd;
    import java.awt.*;
    import javax.swing.*;
    public class TestDragComponent extends JFrame {
         public TestDragComponent() {
              super("Test");
              Container c = getContentPane();
              c.setLayout(new GridLayout(1,2));
              c.add(new MoveableComponentsContainer());
              c.add(new MoveableComponentsContainer());
              pack();
              setVisible(true);
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception ex) {
                   System.out.println(ex);
              new TestDragComponent();
    }[2]. Code 2:
    package swing.dnd;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    import java.awt.image.*;
    import java.awt.dnd.DragSource;
    import java.awt.dnd.DropTarget;
    public class MoveableComponentsContainer extends JPanel {     
         public DragSource dragSource;
         public DropTarget dropTarget;
         private static BufferedImage buffImage = null; //buff image
         private static Point cursorPoint = new Point();
         public MoveableComponentsContainer() {
              setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.white, Color.gray));
              setLayout(null);
              dragSource = new DragSource();
              ComponentDragSourceListener tdsl = new ComponentDragSourceListener();
              dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, new ComponentDragGestureListener(tdsl));
              ComponentDropTargetListener tdtl = new ComponentDropTargetListener();
              dropTarget = new DropTarget(this, DnDConstants.ACTION_MOVE, tdtl);
              setPreferredSize(new Dimension(400,400));
              addMoveableComponents();
         private void addMoveableComponents() {
              MoveableLabel lab = new MoveableLabel("label 1");
              add(lab);
              lab.setLocation(10,10);
              lab = new MoveableLabel("label 2");
              add(lab);
              lab.setLocation(40,40);
              lab = new MoveableLabel("label 3");
              add(lab);
              lab.setLocation(70,70);
              lab = new MoveableLabel("label 4");
              add(lab);
              lab.setLocation(100,100);
         final class ComponentDragSourceListener implements DragSourceListener {
              public void dragDropEnd(DragSourceDropEvent dsde) {
              public void dragEnter(DragSourceDragEvent dsde)  {
                   int action = dsde.getDropAction();
                   if (action == DnDConstants.ACTION_MOVE) {
                        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
                   else {
                        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
              public void dragOver(DragSourceDragEvent dsde) {
                   int action = dsde.getDropAction();
                   if (action == DnDConstants.ACTION_MOVE) {
                        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
                   else {
                        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
              public void dropActionChanged(DragSourceDragEvent dsde)  {
                   int action = dsde.getDropAction();
                   if (action == DnDConstants.ACTION_MOVE) {
                        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
                   else {
                        dsde.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
              public void dragExit(DragSourceEvent dse) {
                 dse.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
         final class ComponentDragGestureListener implements DragGestureListener {
              ComponentDragSourceListener tdsl;
              public ComponentDragGestureListener(ComponentDragSourceListener tdsl) {
                   this.tdsl = tdsl;
              public void dragGestureRecognized(DragGestureEvent dge) {
                   Component comp = getComponentAt(dge.getDragOrigin());
                   if (comp != null && comp != MoveableComponentsContainer.this) {
                        cursorPoint.setLocation(SwingUtilities.convertPoint(MoveableComponentsContainer.this, dge.getDragOrigin(), comp));
                        buffImage = new BufferedImage(comp.getWidth(), comp.getHeight(), java.awt.image.BufferedImage.TYPE_INT_ARGB_PRE);//buffered image reference passing the label's ht and width
                        Graphics2D graphics = buffImage.createGraphics();//creating the graphics for buffered image
                        graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));     //Sets the Composite for the Graphics2D context
                        boolean opacity = ((JComponent)comp).isOpaque();
                        if (opacity) {
                             ((JComponent)comp).setOpaque(false);                         
                        comp.paint(graphics); //painting the graphics to label
                        if (opacity) {
                             ((JComponent)comp).setOpaque(true);                         
                        graphics.dispose();
                        remove(comp);
                        dragSource.startDrag(dge, DragSource.DefaultMoveDrop , buffImage, cursorPoint, new TransferableComponent(comp), tdsl);     
                        revalidate();
                        repaint();
         final class ComponentDropTargetListener implements DropTargetListener {
              private Rectangle rect2D = new Rectangle();
              Insets insets;
              public void dragEnter(DropTargetDragEvent dtde) {
                   Point pt = dtde.getLocation();
                   paintImmediately(rect2D.getBounds());
                   rect2D.setRect((int) (pt.getX()-cursorPoint.getX()),(int) (pt.getY()-cursorPoint.getY()),buffImage.getWidth(),buffImage.getHeight());
                   ((Graphics2D) getGraphics()).drawImage(buffImage,(int) (pt.getX()-cursorPoint.getX()),(int) (pt.getY()-cursorPoint.getY()),MoveableComponentsContainer.this);
                   dtde.acceptDrag(dtde.getDropAction());
              public void dragExit(DropTargetEvent dte) {
                   paintImmediately(rect2D.getBounds());
              public void dragOver(DropTargetDragEvent dtde) {
                   Point pt = dtde.getLocation();
                   paintImmediately(rect2D.getBounds());
                   rect2D.setRect((int) (pt.getX()-cursorPoint.getX()),(int) (pt.getY()-cursorPoint.getY()),buffImage.getWidth(),buffImage.getHeight());
                   ((Graphics2D) getGraphics()).drawImage(buffImage,(int) (pt.getX()-cursorPoint.getX()),(int) (pt.getY()-cursorPoint.getY()),MoveableComponentsContainer.this);
                   dtde.acceptDrag(dtde.getDropAction());
              public void dropActionChanged(DropTargetDragEvent dtde) {
                   Point pt = dtde.getLocation();
                   paintImmediately(rect2D.getBounds());
                   rect2D.setRect((int) (pt.getX()-cursorPoint.getX()),(int) (pt.getY()-cursorPoint.getY()),buffImage.getWidth(),buffImage.getHeight());
                   ((Graphics2D) getGraphics()).drawImage(buffImage,(int) (pt.getX()-cursorPoint.getX()),(int) (pt.getY()-cursorPoint.getY()),MoveableComponentsContainer.this);
                   dtde.acceptDrag(dtde.getDropAction());
              public void drop(DropTargetDropEvent dtde) {
                   try {
                        paintImmediately(rect2D.getBounds());
                        int action = dtde.getDropAction();
                        Transferable transferable = dtde.getTransferable();
                        if (transferable.isDataFlavorSupported(TransferableComponent.COMPONENT_FLAVOR)) {
                             Component comp = (Component) transferable.getTransferData(TransferableComponent.COMPONENT_FLAVOR);
                             Point location = dtde.getLocation();
                             if (comp == null) {
                                  dtde.rejectDrop();
                                  dtde.dropComplete(false);
                                  revalidate();
                                  repaint();
                                  return;                              
                             else {                         
                                  add(comp, 0);
                                  comp.setLocation((int)(location.getX()-cursorPoint.getX()),(int)(location.getY()-cursorPoint.getY()));
                                  dtde.dropComplete(true);
                                  revalidate();
                                  repaint();
                                  return;
                        else {
                             dtde.rejectDrop();
                             dtde.dropComplete(false);
                             return;               
                   catch (Exception e) {     
                        System.out.println(e);
                        dtde.rejectDrop();
                        dtde.dropComplete(false);
    }Thanks so much for any help.
    Reagrds
    sunny

    Well, I don't really understand the DnD interface so maybe my chess board example will be easier to understand and modify:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=518707
    Basically what you would need to do is:
    a) on a mousePressed you would need to create a new JLabel with the icon from the clicked label and add the label to the glass pane
    b) mouseDragged code would be the same you just repaint the label as it is moved
    c) on a mouseReleased, you would need to check that the label is now positioned over your "drop panel" and then add the label to the panel using the panels coordinates not the glass pane coordinates.

  • How do I drag an image icon or image from one panel to another panel?

    Please help.
    I know to need how to drag an image icon from one panel to the other. For example, the first panel would shows the image files that is inside my folder. How can i code it so that I can drag the image that appear on the first panel into the second panel which will hold the images that I want to embed my barcode inside?
    The thumbnail size of the image and showing all the image files in my folder was done already, I only need to know how can I make the image icon to be able to drag from one panel to the other.
    Thanks.

    I found this code in some websites:
    public class ImageSelection extends TransferHandler {
         private static final DataFlavor flavors[] = {DataFlavor.imageFlavor};
         public int getSourceActions(JComponent c) {
              return TransferHandler.COPY;
         public boolean canImport(JComponent comp, DataFlavor flavor[]){
              if (!(comp instanceof JLabel)){
                   return false;
              for (int i=0, n=flavor.length; i<n; i++){
                   for (int j=0, m=flavors.length; j<m; j++){
                        if (flavor.equals(flavors[j])){
                             return true;
              return false;
         public Transferable createTransferable(JComponent comp) {
              if (comp instanceof JLabel) {
                   JLabel label = (JLabel)comp;
                   Icon icon = label.getIcon();
                   if (icon instanceof ImageIcon){
                        final Image image = ((ImageIcon)icon).getImage();
                        final JLabel source = label;
                        Transferable transferable = new Transferable(){
                             public Object getTransferData(DataFlavor flavor){
                                  if (isDataFlavorSupported(flavor)){
                                       return image;
                                  return null;
                             public DataFlavor[] getTransferDataFlavors(){
                                  return flavors;
                             public boolean isDataFlavorSupported(DataFlavor flavor){
                                  return flavor.equals(DataFlavor.imageFlavor);
                        return transferable;
              return null;
         public boolean importData(JComponent comp, Transferable t){
              if (comp instanceof JLabel){
                   JLabel label = (JLabel)comp;
                   if (t.isDataFlavorSupported(flavors[0])){
                        try {
                             Image image = (Image)t.getTransferData(flavors[0]);
                             ImageIcon icon = new ImageIcon(image);
                             label.setIcon(icon);
                             return true;
                        catch (UnsupportedFlavorException ignored){
                        catch (IOException ignored) {
              return false;
    What this codes does is to get the image from the imageicon and replace the image to the imageicon that you drag the source from. However, I had no clue how I can get the source's file name. Anyone can teach me how?
    Thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Blast from the past: How do I draw image maps in Dreamweaver CC 2014?

    Need to update some old stuff, and can´t find where to draw image-maps on images.

    First, you need to be in Design View to get the image map tools to appear.
    Once there, the image map icons should show when you select an image. If they don't, you may have your Properties panel collapsed. In the bottom right corner of the Properties panel, there's a tiny triangle, click that to expand the panel to include the image map tools.

  • Scalable Image in a JLabel

    Hi,
    I am writing an About dialog that is just a frame filled with an image that I have made for the About screen. The problem is that I want the image size to be exactly fit to the JFrame. setBounds seem to be not right when I setBounds to the Image Size (e.g. 400x297). Is there a way to scale the Image in the JLabel to fit the frame, or scale the frame to fit the Image, or find the right values for setBounds ? Here is the code.
    import java.awt.*;
    import javax.swing.*;
    class About {
         About(){
              JFrame frm = new JFrame("About");
              frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frm.setBounds(400,400,430,330);
              frm.getContentPane().setLayout(new BorderLayout());
                                              frm.setUndecorated(true); // SkinLF
              frm.getRootPane().setWindowDecorationStyle(JRootPane.FRAME); // SkinLF
              frm.setDefaultLookAndFeelDecorated(true);  // SkinLF
              frm.setResizable(false);
              JLabel about = new JLabel(new ImageIcon("about.jpg"));
              frm.getContentPane().add(about,BorderLayout.CENTER);
              frm.setVisible(true);          
    }

    hi , hi , hi ,
    I read you code well and understand that you want to fit the image in the
    frame to the frame to image ,
    if this is oky , then : your code is poor , because it poor idea to use the JLabel to put in it your image , the best idea is to extends JPanel Class
    and to override the paint method - paint( Graphics g ) { .... }
    method and draw your image here , as the following code show :
    public class PanelImage extends JPanel {
                         Image yourImage ;
                         public PanelImage( Image im ) {
                                this.yourImage = im ;
                         public void paint( Graphics g ) {
                                super.paint( g ) ;
                                g.drawImage( 0 , 0 , this.getWight() , this.getHeight() , this.yourImage);
    and add the instance from this class to your JFrame and your are very happy very happy , It is Java .
    Regards , M_darim ( SCJP 5 ) .

  • Draw image over jtable header

    hello, I am trying to draw an image (its a little image of a custom sort indicator) over the header of a jTable, but after extensive reading of the api docs about TableCellRenderer and DefaultTableCellRenderer I cannot come to a solution.
    What I want is something like this: let the renderer do the paint and after that I grab the graphics and draw the image over it...
    please let me know if I need to restate my problem

    I extended DefaultTableCellRenderer like you say in your article, but while doing so it lost the default Metal L&F. It become like an ordinary cell of the table. Below is the code:
    class DefaultTableHeaderCellRenderer extends javax.swing.table.DefaultTableCellRenderer {
       @Override
       public Component getTableCellRendererComponent(JTable table, Object value,
             boolean isSelected, boolean hasFocus, int row, int column)
          super.getTableCellRendererComponent(table, value,
                isSelected, hasFocus, row, column);
          //setIcon(getIcon(table, column));
          setBorder(UIManager.getBorder("TableHeader.cellBorder"));
          return this;
        protected Icon getIcon(JTable table, int column) {
           ImageIcon icon = new ImageIcon("imagens/sortdown.png");
           return icon;
    }then in my class I call:
    this.getTableHeader().setDefaultRenderer(new DefaultTableHeaderCellRenderer());You can see I commented setIcon. It works, the icon is drawn, but this is not what I am after, I wanted to draw the icon over the Metal L&F. Also, is there a way to draw the icon at a specified position?
    thanks for the help

  • Drawing image Urgent!

    hai Guys!
    is it possible to draw image in xor mode using drawregion or drawimage if yes then how it can be done!

    hi frens..
    Is there way of drawing an image on Frame
    without erasing previous image. Each time the
    repaint() is called for drawing new image on frame
    using Graphics object, repaint() just clears the
    previous images , but i want previous image to be
    sustained .
    ImageIcon WhiteIcon = new ImageIcon("White.GIF");
    JL = new JLabel(null ,WhiteIcon, 0 );
    f.add(JL);Hope this will do.

  • Image Icon not showing in "get info" for OS 10.9.4

         I  now have PS CC 2014 and the image icons are showing the "generic" .jpg and .psd files in the "get info" finder window, but on my desktop the images are showing their
         proper image icon.
         I was previously using PS CS 5 and the icons are showing up in the "get info" window, but with PS CC 2014 these icons are showing up as generic.
         To be clear the images I saved using PS CS 5 are showing the icons vs. the images I saved in CC 2014 where the icons are not showing in the "get info" window.
         I've compared preference settings with PS 2014 and PS 5 but their basically about the same.
         I'm including 2 images so you can see what I'm explaining. IMG_1627 is a PS CC2014 created image and Arturo is a PS 5 image.
         I did read about other PS users having similar issues but it looked to be unresolved.
         You may think what's the big deal, but I use these image icons to label my folders. A "trick" I've doing for over decade which helps keep my folders visually on track for me.
         Is anyone out there able to solve this issue??  

    I do on occasion get jpgs and pngs that won't render a thumbnail or preview in MacOS.  I have 10.9.5
    I don't have this problem, although I just have CC and CC 2014 on my Macbook.
    I would open those up in Preview.app and try a Save As... and I would get the thumbnail and thumbnail preview back.
    Not really the best idea,but you can see if it helps.
    These  are my file saving options, perhaps there is something there you can try.
    Gene

  • How can I draw image in a vbean?

    How can I draw image in a vbean?
    this is my code :
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         boolean ImageLoaded = false;
         public void paint(Graphics g) {
              if (ImageLoaded) {
                   System.out.println("yes~~~");
                   g.drawImage(img, 0, 0, null);
              } else
                   System.out.println("no~~~");
         public boolean imageUpdate(Image img, int infoflags, int x, int y, int w,
                   int h) {
              if (infoflags == ALLBITS) {
                   System.out.println("yes");
                   ImageLoaded = true;
                   repaint();
                   return false;
              } else
                   return true;
         public void init(IHandler arg0) {
              super.init(arg0);
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   Image offScreenImage = createImage(size().width, size().height);
                   Graphics offScreenGC = offScreenImage.getGraphics();
                   System.out.println(offScreenGC.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    but when I run it in forms
    when it run Graphics offScreenGC = offScreenImage.getGraphics();
    It throw a exception:
    java.lang.NullPointerException     at com.avicit.aepcs.calendar.PrintEmailLogo.init(PrintEmailLogo.java:72)     at oracle.forms.handler.UICommon.instantiate(Unknown Source)     at oracle.forms.handler.UICommon.onCreate(Unknown Source)     at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)     at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)     at oracle.forms.engine.Runform.processMessage(Unknown Source)     at oracle.forms.engine.Runform.processSet(Unknown Source)     at oracle.forms.engine.Runform.onMessageReal(Unknown Source)     at oracle.forms.engine.Runform.onMessage(Unknown Source)     at oracle.forms.engine.Runform.processEventEnd(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)     at java.awt.Component.dispatchEventImpl(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.EventQueue.dispatchEvent(Unknown Source)     at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)     at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)     at java.awt.EventDispatchThread.pumpEvents(Unknown Source)     at java.awt.EventDispatchThread.run(Unknown Source)
    I change it to:
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JFrame;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         public void paint(Graphics g) {
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   g.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void init(IHandler arg0) {
              super.init(arg0);
    But it display nothing.
    It isn't paint continuous.
    what's wrong in my vbean?
    please help me.

    The following code works fine for me:
    package oracle.forms.fd;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.CustomEvent;
    import oracle.forms.ui.VBean;
    public class test extends VBean {
      private URL url;
      private URL m_codeBase; 
      private Image img;
    public void paint(Graphics g) {
      // draw the image
      g.drawImage(img, 0, 0, this);
    public void init(IHandler arg0) {
       super.init(arg0);
       // load image file
       img = loadImage("file:///c:/coyote.jpg");   
    public test()
        super();
       *  Load an image from JAR file, Client machine or Internet URL  *
      private Image loadImage(String imageName)
        URL imageURL = null;
        boolean loadSuccess = false;
        Image img = null ;
        //JAR
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          try
            img = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            return img ;
          catch (Exception ilex)
            System.out.println("Error loading image from JAR: " + ilex.toString());
        else
          System.out.println("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          System.out.println("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else if(imageName.toLowerCase().startsWith("file:"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
              System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          System.out.println("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
                    System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          System.out.println("Error image " + imageName + " could not be located");
        return img ;
    }Francois

  • Can one add more than one photo layer to a draw image?

    I cannot seem to find a way to add more than one photo or photo layer to a Draw image, but the Draw page on Adobe seems to imply multiple photos can be added. How might I accomplish this? Thanks for your time.

    Unfortunately, Draw is currently limited to one photo layer, and only one photo within that layer.
    Hope that helps,
    Frank
    Draw Engineering

Maybe you are looking for

  • BSI Tax Factory on ECC 6.0 Unicode

    I'm looking for some help with using BSI Tax Factory on an ECC 6.0 Unicode System.  Does anyone have any experience with using BSI Tax Factory on the Unicode version of ECC 6.0? Were there any special steps that were taken in order to make it work? I

  • My iPod turned off and it will not turn back on or connect to iTunes.

    I was writing a note in my iPod Touch & it just shut off on me. The battery was fully charged, and now it will not turn on or connect to iTunes. I only had my iPod for 3 months... I do not know what to do..

  • After upgrading my iPhone 4s to iOS8 my battery life has been cut in half

    After upgrading my iPhone 4s to iOS8 my battery life has been cut in half Mail is 44% of the battery - I get about 300 emails through MSexchange and 25 through hotmail and .25 from cogeco. Home & Lock Screen is 19% Phone is 14% Calendar 11% Is there

  • How to read a part of a TDMS file?

    Hi, I'm having problems loading back a part of a TDMS file. Im currently trying to use the offset and count input on TDMS read. But the offset value doesn't seem to make any difference: If I set offset to 5 and count to 10 it still puts out 10 data p

  • Quantity field fro char or date data type

    Hi, I am using DELVRY03 idoc type and some of the quantity fields are empty not being used, is it a good idea if I can use these quantity fields for Char type or datetype data. Regards Rinku