JLabel DnD

I found a tutorial on how to get a JLabel to work with drag and drop. I modified the code given to use a JList and a JLabel. I got the JList to be able to drag a list element onto the JLabel and the label display the text. However, if you drag one element, and then drag another element, the first element is replaced.
I want to be able to drag multiple elements onto the JLabel from the JList. Here is my code, can anyone give me a hand?
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LabelDnD extends JPanel {
     JList list;
    JLabel label;
    String[] data = new String[] {"Red", "Green", "Blue"};
    public LabelDnD() {
        super(new GridLayout(2, 1));
        list = new JList(data);
        list.setDragEnabled(true);
        JPanel tfpanel = new JPanel(new GridLayout(1,1));
        TitledBorder t1 = BorderFactory.createTitledBorder("JList");
        tfpanel.add(list);
        tfpanel.setBorder(t1);
        label = new JLabel("I'm a Label!", SwingConstants.LEADING);
        label.setTransferHandler(new TransferHandler("text"));
        MouseListener listener = new DragMouseAdapter();
        label.addMouseListener(listener);
        JPanel lpanel = new JPanel(new GridLayout(1,1));
        TitledBorder t2 = BorderFactory.createTitledBorder("JLabel");
        lpanel.add(label);
        lpanel.setBorder(t2);
        add(tfpanel);
        add(lpanel);
        setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
    private class DragMouseAdapter extends MouseAdapter {
        public void mousePressed(MouseEvent e) {
            JComponent c = (JComponent)e.getSource();
            TransferHandler handler = c.getTransferHandler();
            handler.exportAsDrag(c, e, TransferHandler.COPY);
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("LabelDnD");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JComponent newContentPane = new LabelDnD();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
}

Some of you need to learn some netiquette.The proper netiquette is to do some work yourself
before posting. This includes reading the API and
tutorials (which you appear to have done), but it
also involved searching the forum to see if you
question has been asked and answered previously.
Since the vast majority of people who have Swing
related questions post in the Swing forum, then you
have the best chance to find the answer there.
If you don't find an answer then you post a question
and we attempt to answer it.
Now the next person who searches the forum has a
better chance of finding the answer on a related
question.
If all the information is in one place then we don't
have to keep repeating ourselves in multiple forums
all the time.
Try answering a few questions before you become a
netiquette expert.First I would like to apologize for my comment earlier, it was a little rude. However, as an Administrator of a small programming forum, I'm used to giving detailed answers to posts, even if a similar question was previously asked. To be honest, every question I have answered in my forum could have been found if the user did a minute of searching, but sometimes its the one on one help, and question specific response, that allows the user to actually understand what they are doing. Perhaps I have spoiled myself.
I can understand in a forum as large as this, your probably tired of answering the same questions over and over again. And its your right to answer them or not. I did do a quick search on google and the only thing I was able to find was as the code above that got me this far. I figured if there were any queries relevant to my question posted in this forum, google would have found them.
Anyway, this topic can be locked / deleted as I have used a different solution.
Thanks anyway, maybe next time I'll remember the correct forum to post in. :|

Similar Messages

  • Drag a JLabel, drop in a JList

    I'm trying to implement a drop-and-drag feature in my program.
    I have a class Book, which extends a JLabel with and ID field (as a string) and a get and set method for the ID in it, as well as a toString method which returns the ID.
    I need to drag the label over a JList and add the label's ID to the list, directly below the selected index over which the mouse dropped.
    So far i have tried to override the transferhandler with example String and List handlers i found on the site (at http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/ListTransferHandler.java and http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/StringTransferHandler.java ) however, it seems the problem keeps getting bigger the more i try to edit them.
    Also, i have tried to implement Serializable and Transferable Book's, but I'm not entirely familiar with how to use the dataflavors, so that could also be causing the problem.
    I have tried a few possible scenarios with the transfer handler and so far this is getting me the most results:
    public class dragtest extends JPanel {
    public dragtest() {
    super(new GridLayout(3,1));
    add(createArea());
    add(createList());
    add(createBookcase(17));
    private JPanel createList() {
    DefaultListModel listModel = new DefaultListModel();
    listModel.addElement("List one");
    listModel.addElement("List two");
    listModel.addElement("List three");
    JList list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    JScrollPane scrollPane = new JScrollPane(list);
    scrollPane.setPreferredSize(new Dimension(400,100));
    // do not allow list items to be dragged
    list.setDragEnabled(false);
    // list.setDropTarget();
    // DropTarget dt = new DropTarget();
    // list.setDropTarget(dt);
    list.setTransferHandler(new ListTransferHandler());
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.setBorder(BorderFactory.createTitledBorder("List"));
    return panel;
    private JPanel createBookcase(int amount) {
    JPanel bookCase = new JPanel();
    int X1 = 30; // height from top
    int X2 = 20; // height to bottom
    int Y1 = 20; // distance from sides
    int Y2 = 10; // distance between images
    int Z1 = 60; // width of image
    int Z2 = 80; // height of image
    int numLabelsInCol = 5;
    int numDone = 0;
    int x = 0;
    for (int y = 0; y < numLabelsInCol; y++) {
    if (numDone < amount) {
    Book lbl = new Book(numDone, "address");
    lbl.setBounds( (Y1 + y * (Z1 + Y2)), (X1 + x * (Z2 + X2 + X1)), Z1, Z2);
    bookCase.add(lbl);
    String text = lbl.ID;
    lbl.setText(text);
    numDone++;
    lbl.setTransferHandler(new TransferHandler("text"));
    MouseListener listener = new DragMouseAdapter();
    lbl.addMouseListener(listener);
    bookCase.setPreferredSize(new Dimension(400, 100));
    return bookCase;
    private class DragMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent e) {
    JComponent c = (JComponent) e.getSource();
    TransferHandler handler = c.getTransferHandler();
    handler.exportAsDrag(c, e, TransferHandler.COPY);
    I realise it might be a little unconventional, the way i implement the transfer handler, but this actually prints out the ID on a JTextArea, however a list does not even react when i drag or drop the label over it. It does not even show a shaded area under which the mouse is.
    I have tried a multitude of examples but none of them have dealt with this. The only one which deals with JLabels dropped on a JList does not care for the order, however my program focuses on it.
    Please could anyone help?

    1) Swing related questions should be posted in the Swing forum
    2) When you poste code use the "code" formatting tags so the code retains its original formatting
    Using the ExtendedDnDDemo, from the Swing tutorial you referenced above, as the test program I created the following method:
        private JPanel createLabel() {
             JLabel label = new JLabel("Dnd Label");
            label.setTransferHandler(new LabelTransferHandler());
            label.addMouseListener( new MouseAdapter()
                 public void mousePressed(MouseEvent e)
                     JComponent c = (JComponent)e.getSource();
                     TransferHandler handler = c.getTransferHandler();
                     handler.exportAsDrag(c, e, TransferHandler.COPY);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(label, BorderLayout.CENTER);
            panel.setBorder(BorderFactory.createTitledBorder("Label"));
            return panel;
        }And the following class:
    * LabelTransferHandler.java is used by the 1.4
    * ExtendedDnDDemo.java example.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    public class LabelTransferHandler extends StringTransferHandler {
        // Get the text for export.
        protected String exportString(JComponent c) {
            JLabel label = (JLabel)c;
            return label.getText();
        //Take the incoming string and set the text of the label
        protected void importString(JComponent c, String str) {
            JLabel label = (JLabel)c;
            label.setText(str);
        protected void cleanup(JComponent c, boolean remove) {
    }

  • Java DnD with Jlabels

    Hello.
    I’m making a drawing program and using draggable icons with Java dnd by extending JLabel and implementing Transferable. Thus, the JLabel carries the drawn icon while dragging and dropped.
    First issue
    The dragging works fine most of the time, but some kind of icon combination results in strange behaviour (all icons are created from same class).
    On dragEnter I get instances from dtde.getTransferable() that’s not Transferable. Instances that’s not meant to be dragged and not able to start a drag from a DragGestureEvent, because its not implementing a DragGestureListener. Why does dtde.getTransferable() return such instances?
    dtde.getTransferable() also claiming odd classes to be not serializable (e.g. BasicStroke). I guess this is a result of the above problem.
    Second issue
    The time it takes for the following code to return increases, as the number of instantiated transferable icons increase. It takes 1-2 seconds given 10 transferable JLabels.
    Object o = dtde.getTransferable().getTransferData(DataFlavor.stringFlavor);The icon implementation of getTransferData(DataFlavor):
    if (flavor != DataFlavor.stringFlavor)
          throw new UnsupportedFlavorException(flavor);
    return this;This is rather different from traditional string dragging. Does somebody have any experience using transferable JLabels?

    Following link may help you understand: http://forums.java.net/jive/thread.jspa?threadID=9196

  • DnD icon won't go away on Redhat 9

    Background:
    I recently updated my OS to RedHat 9 (2.4.20-6). Previously on Redhat 7.3 (kernel upgraded to 2.4.18ish) everything worked OK.
    java -version
    java version "1.4.1-beta"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1-beta-b14)
    Java HotSpot(TM) Client VM (build 1.4.1-beta-b14, mixed mode)
    Problem:
    After dragging and dropping an object the drag icon/cursor turns black/reverse-video and does not go away until I drag another object or move the icon/cursor out of the window. The problem did not occur before my upgrade so I imaging it is not a java problem. I would like to know if anyone can repeat the problem or if anyone else has seen it. One Caveate... if you do anything after the drop that causes an icon repaint (like the OptionPane that is commented out in the code below) the problem does not appear. I have not been able to reproduce the problem outside of java.
    thanks
    Brad
    Example:
    This code by Gupta is a simple example to demonstrate the problem.
    file DNDComponentInterface.java
    <code>
    public interface DNDComponentInterface{
    public void addElement( Object s);
    public void removeElement();
    </code>
    file DNDList.java
    <code>
    /**his is an example of a component, which serves as a DragSource as
    * well as Drop Target.
    * To illustrate the concept, JList has been used as a droppable target
    * and a draggable source.
    * Any component can be used instead of a JList.
    * The code also contains debugging messages which can be used for
    * diagnostics and understanding the flow of events.
    * @version 1.0
    import java.awt.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    import java.util.Hashtable;
    import java.util.List;
    import java.util.Iterator;
    import java.io.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.JList;
    import javax.swing.DefaultListModel;
    public class DNDList extends JList
    implements DNDComponentInterface, DropTargetListener,DragSourceListener, DragGestureListener {
    * enables this component to be a dropTarget
    DropTarget dropTarget = null;
    * enables this component to be a Drag Source
    DragSource dragSource = null;
    * constructor - initializes the DropTarget and DragSource.
    public DNDList() {
    dropTarget = new DropTarget (this, this);
    dragSource = new DragSource();
    dragSource.createDefaultDragGestureRecognizer( this, DnDConstants.ACTION_MOVE, this);
    * is invoked when you are dragging over the DropSite
    public void dragEnter (DropTargetDragEvent event) {
    // debug messages for diagnostics
    System.out.println( "dragEnter");
    event.acceptDrag (DnDConstants.ACTION_MOVE);
    * is invoked when you are exit the DropSite without dropping
    public void dragExit (DropTargetEvent event) {
    System.out.println( "dragExit");
    * is invoked when a drag operation is going on
    public void dragOver (DropTargetDragEvent event) {
    System.out.println( "dragOver");
    * a drop has occurred
    public void drop (DropTargetDropEvent event) {
    try {
    Transferable transferable = event.getTransferable();
    // we accept only Strings
    if (transferable.isDataFlavorSupported (DataFlavor.stringFlavor)){
    // KBS
    //event.acceptDrop(DnDConstants.ACTION_MOVE);
    //event.getDropTargetContext().dropComplete(true);
    // KBS
    // KBS Added this
    /* You must leave this commented out to replicate the DND icon ghost problem
    int answer = JOptionPane.showConfirmDialog(this,
    "Are you sure?",
    "Warning",
    JOptionPane.YES_NO_OPTION);
    int answer = JOptionPane.YES_OPTION;
    if (answer == JOptionPane.YES_OPTION)
    // KBS To here
    event.acceptDrop(DnDConstants.ACTION_MOVE);
    String s = (String)transferable.getTransferData ( DataFlavor.stringFlavor);
    addElement( s );
    event.getDropTargetContext().dropComplete(true);
    // KBS Added this
    // KBS To here
    else{
    event.rejectDrop();
    catch (IOException exception) {
    exception.printStackTrace();
    System.err.println( "Exception" + exception.getMessage());
    event.rejectDrop();
    catch (UnsupportedFlavorException ufException ) {
    ufException.printStackTrace();
    System.err.println( "Exception" + ufException.getMessage());
    event.rejectDrop();
    * is invoked if the use modifies the current drop gesture
    public void dropActionChanged ( DropTargetDragEvent event ) {
    * a drag gesture has been initiated
    public void dragGestureRecognized( DragGestureEvent event) {
    Object selected = getSelectedValue();
    if ( selected != null ){
    StringSelection text = new StringSelection( selected.toString());
    // as the name suggests, starts the dragging
    dragSource.startDrag (event, DragSource.DefaultMoveDrop, text, this);
    } else {
    System.out.println( "nothing was selected");
    * this message goes to DragSourceListener, informing it that the dragging
    * has ended
    public void dragDropEnd (DragSourceDropEvent event) {  
    if ( event.getDropSuccess()){
    removeElement();
    * this message goes to DragSourceListener, informing it that the dragging
    * has entered the DropSite
    public void dragEnter (DragSourceDragEvent event) {
    System.out.println( " dragEnter");
    * this message goes to DragSourceListener, informing it that the dragging
    * has exited the DropSite
    public void dragExit (DragSourceEvent event) {
    System.out.println( "dragExit");
    * this message goes to DragSourceListener, informing it that the dragging is currently
    * ocurring over the DropSite
    public void dragOver (DragSourceDragEvent event) {
    System.out.println( "dragExit");
    * is invoked when the user changes the dropAction
    public void dropActionChanged ( DragSourceDragEvent event) {
    System.out.println( "dropActionChanged");
    * adds elements to itself
    public void addElement( Object s ){
    (( DefaultListModel )getModel()).addElement (s.toString());
    * removes an element from itself
    public void removeElement(){
    (( DefaultListModel)getModel()).removeElement( getSelectedValue());
    </code>
    file TestDND.java
    <code.
    * The tester class for the DNDList. This class creates the lists,
    * positions them in a frame, populates the list with the default
    * data.
    * @version 1.0
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestDND
    public static void main (String args[]) {
    TestDND testDND = new TestDND();
    * constructor
    * creates the frame, the lists in it and sets the data in the lists
    public TestDND()
    JFrame f = new JFrame("Drag and Drop Lists");
    DNDList sourceList = new DNDList();
    // add data to the source List
    DefaultListModel sourceModel = new DefaultListModel();
    sourceModel.addElement( "Source Item1");
    sourceModel.addElement( "Source Item2");
    sourceModel.addElement( "Source Item3");
    sourceModel.addElement( "Source Item4");
    // gets the panel with the List and a heading for the List
    JPanel sourcePanel = getListPanel(sourceList, "SourceList", sourceModel);
    DNDList targetList = new DNDList();
    // add data to the target List
    DefaultListModel targetModel = new DefaultListModel();
    targetModel.addElement( "Target Item1");
    targetModel.addElement( "Target Item2");
    targetModel.addElement( "Target Item3");
    targetModel.addElement( "Target Item4");
    JPanel targetPanel = getListPanel(targetList, "TargetList", targetModel);
    JPanel mainPanel = new JPanel();
         mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
    mainPanel.add( sourcePanel );
    mainPanel.add( targetPanel );
    f.getContentPane().add( mainPanel );
    f.setSize (300, 300);
    f.addWindowListener (new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    f.setVisible (true);
    * a convenience method
    * used for positioning of the ListBox and the Label.
    * @param list - the special DND List
    * @param labelName - the heading for the list
    * @param listModel - model for the list
    private JPanel getListPanel(DNDList list, String labelName, DefaultListModel listModel ){ 
    JPanel listPanel = new JPanel();
    JScrollPane scrollPane = new JScrollPane(list);
    list.setModel(listModel);
    JLabel nameListName = new JLabel(labelName );
    listPanel.setLayout( new BorderLayout());
    listPanel.add(nameListName, BorderLayout.NORTH);
    listPanel.add( scrollPane, BorderLayout.CENTER);
    return listPanel;
    </code>

    HI,
    Try Resetting your iPhone
    Carolyn

  • Java Drag and Drop from JMenu to JLabel

    Hello Fellow Coders,
    I am working on quite a large project right now. What I am trying to do is the following:
    1. When a user clicks on a custom button (extends JLabel) a context Menu opens. (works already)
    2. Now the user must be able to drag text from that menu onto another custom button.
    3. When the user drops that text on the target, the copied text should be written into a sql database.
    How can I accomplish that?
    I can't seem to find the right starting point.
    Best Regards
    Oliver

    Hey folks,
    after half a day of research and API studies I figured it out now. Since JMenu doesn't offer DnD Support AFAIK I had to switch to a JLIST.
    Then I had to write my own Transfer Handler / extend the Default Transfer Handler and now it works great. I'll post a few code snippets, maybe this is useful to somebody. I havn't tested it through yet, so it's definitly not bug free.
    This is the String TransferHandler from Sun (saved some work :) )
    public abstract class StringTransferHandler extends TransferHandler {
        protected abstract String exportString(JComponent c);
        protected abstract void importString(JComponent c, String str);
        protected abstract void cleanup(JComponent c, boolean remove);
        protected Transferable createTransferable(JComponent c) {
            return new StringSelection(exportString(c));
        public int getSourceActions(JComponent c) {
            return MOVE;
        public boolean importData(JComponent c, Transferable t) {
            if (canImport(c, t.getTransferDataFlavors())) {
                try {
                    String str = (String)t.getTransferData(DataFlavor.stringFlavor);
                    importString(c, str);
                    return true;
                } catch (UnsupportedFlavorException ufe) {
                } catch (IOException ioe) {
            return false;
        protected void exportDone(JComponent c, Transferable data, int action) {
            cleanup(c, action == MOVE);
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (DataFlavor.stringFlavor.equals(flavors)) {
    return true;
    return false;
    My Custom transfer handler, you'll get the idea i supposepublic class BookingTransferHandler extends StringTransferHandler {
    protected void importString(JComponent c, String str) {
         KasseDB.splitTable(str, c.getName());
    You'll have to implement a few more methods, i didn't post. If you need more code just contact me, I'll send you a working example.
    KasseDB.splitTable() is the workhorse that does the Database work.
    Don't forget to set the TransferHandler on your targets with target.setTransferHandler(new BookingTransferhandler()) as in my case.
    Best Regards
    Oliver                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Can anyone help in resizing the JLabel object

    Hi,
    can anyone help me in resizing the JLabel object after being dropped onto the DropContainer. I'm providing the code below
    import javax.swing.*;
    import java.awt.*;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.dnd.*;
    import java.io.File;
    import java.io.Serializable;
    import java.awt.event.*;
    import java.awt.Insets;
    import java.awt.Dimension;
    public class project2 extends JApplet implements Runnable{
    private DragContainer dragcontainer;
    private DropContainer dropcontainer;
    private DefaultListModel listModel,listModel1;
    public void start() {
    Thread kicker = new Thread(this);
    kicker.start();
    public void run() {
    project2 dndapplet = new project2();
    dndapplet.init();
    public void init() {
    try {
    getContentPane().setLayout(new BorderLayout());
    listModel = new DefaultListModel();
    dragcontainer = new DragContainer(listModel);
    getContentPane().add(BorderLayout.WEST, new JScrollPane(dragcontainer));
    listModel1=new DefaultListModel();
    dropcontainer = new DropContainer(listModel1);
    getContentPane().add(BorderLayout.CENTER,new JScrollPane(dropcontainer));
    catch (Exception e) {
    System.out.println("error");
    fillUpList("images");
    setSize(700, 300);
    public static void main(String[] args) {
    Frame f = new Frame("dndframe");
    project2 dndapplet = new project2();
    //Point pos=new Point();
    f.add(dndapplet);
    dndapplet.init();
    dndapplet.start();
    f.show();
    private void fillUpList(String directory) {
    File dir = new File(directory);
    File[] files = dir.listFiles();
    for (int i = 0; i < 11; i++) {
    listModel.addElement(new ImageIcon(directory + "\\" + files.getName()));
    class Cursor extends Object implements Serializable
    public static final int SE_RESIZE_CURSOR=0;
    int cursor;
    public Cursor(int SE_RESIZE_CURSOR)
    cursor=SE_RESIZE_CURSOR;
    class ImageTransferable implements Transferable, Serializable
    ImageIcon imageIcon;
    public static final DataFlavor IMAGE_FLAVOR = DataFlavor.imageFlavor;
    public DataFlavor[] getTransferDataFlavors()
    return new DataFlavor[] {IMAGE_FLAVOR};
    public ImageTransferable(ImageIcon imageIcon)
    this.imageIcon = imageIcon;
    public Object getTransferData(DataFlavor f) throws UnsupportedFlavorException
    if (!isDataFlavorSupported(f))
    throw new UnsupportedFlavorException(f);
    return imageIcon;
    public boolean isDataFlavorSupported(DataFlavor aFlavor)
    return IMAGE_FLAVOR.equals(aFlavor);
    class DragContainer extends JList implements DragGestureListener, DragSourceListener
    private DragSource iDragSource = null;
    public DragContainer(ListModel lm)
    super(lm);
    iDragSource = new DragSource();
    iDragSource.createDefaultDragGestureRecognizer(this,DnDConstants.ACTION_COPY_OR_MOVE, this);
    public void dragGestureRecognized(DragGestureEvent aEvt)
    ImageIcon imageSelected = (ImageIcon) getSelectedValue();
    ImageTransferable imsel = new ImageTransferable(imageSelected);
    if (imageSelected != null)
    System.out.println("startdrag...");
    iDragSource.startDrag(aEvt, DragSource.DefaultCopyNoDrop, imsel, this);
    else
    System.out.println("Nothing Selected");
    public void dropActionChanged(DropTargetDragEvent event)
    public void dropActionChanged(DragSourceDragEvent event)
    public void dragDropEnd(DragSourceDropEvent event)
    public void dragEnter(DragSourceDragEvent event)
    public void dragExit(DragSourceEvent event)
    public void dragOver(DragSourceDragEvent event)
    DragSourceContext context = event.getDragSourceContext();
    context.setCursor(null);
    context.setCursor(DragSource.DefaultCopyDrop);
    class DropContainer extends JList implements DropTargetListener,MouseListener
    private DropTarget iDropTarget = null;
    private int acceptableActions = DnDConstants.ACTION_COPY_OR_MOVE;
    JLabel imgLabel=null;
    public int dropX;
    public int dropY;
    public int x;
    public int y;
    public DropContainer(ListModel lm1)
    super(lm1);
    iDropTarget = new DropTarget(this, this);
    setBackground(Color.white);
    public void drop(DropTargetDropEvent aEvt)
    Point location=null;
    ImageIcon icon=null;
    Transferable transferable=null;
    //int dropX=0;
    //int dropY=0;
    try
    transferable = aEvt.getTransferable();
    location=new Point();
    if(transferable.isDataFlavorSupported(ImageTransferable.IMAGE_FLAVOR))
    aEvt.acceptDrop(acceptableActions);
    icon = (ImageIcon)
    transferable.getTransferData(ImageTransferable.IMAGE_FLAVOR);
    setLayout(null);
    imgLabel=new JLabel();
    imgLabel.setIcon(icon);
    imgLabel.addMouseListener(this);
    location=aEvt.getLocation();
    dropX=location.x;
    dropY=location.y;
    imgLabel.setBounds(dropX,dropY,icon.getIconWidth(),icon.getIconHeight());
    this.add(imgLabel);
    SwingUtilities.updateComponentTreeUI(this.getRootPane());
    aEvt.getDropTargetContext().dropComplete(true);
    else
    System.out.println("rejecting drop");
    aEvt.rejectDrop();
    aEvt.getDropTargetContext().dropComplete(false);
    catch (Exception exc)
    exc.printStackTrace();
    aEvt.rejectDrop();
    aEvt.getDropTargetContext().dropComplete(false);
    finally
    location=null;
    transferable=null;
    icon=null;
    imgLabel=null;
    public void mousePressed(MouseEvent e)
    x=e.getX();
    y=e.getY();
    public void mouseReleased(MouseEvent e)
    int temp1,temp2;
    temp1=y;
    temp2=x;
    imgLabel.setSize(temp1,temp2);
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseClicked(MouseEvent e) {}
    public void dragEnter(DropTargetDragEvent event)
    System.out.println("dragenter");
    event.acceptDrag(acceptableActions);
    public void dragExit(DropTargetEvent event)
    System.out.println("dragexit");
    public void dragOver(DropTargetDragEvent event)
    System.out.println("dragover");
    event.acceptDrag(acceptableActions);
    public void dropActionChanged(DropTargetDragEvent event)
    System.out.println("dropactionchanged");
    event.acceptDrag(acceptableActions);
    }//class DropContainer

    Hi all,
    I have two classes, say 1st and 2nd.
    I have created an object of the second class in the first class and also i have invoked a method of the second class using it's object from the first class.
    but when i compile the first class i'm getting an error that "cannot access the second class".
    can anyone help me in fixing this problem
    thanks in advance
    murali

  • Drag on a JLabel

    I've build a ImageButton component on top of a JLabel. Normally one would use JButton without borders and stuff, but under Nimbus there are margin (inset) issues and JLabel always works fine. So add a mouse listener and some highlight logic on the icon for mouse-over and he world looks fancy. All is good.
    However, to create a more fancy GUI, I also want to be able to drag images around. Now, images shown in a JList work fine, because JList handles the DnD, but it does not render the way I want. So I want to use pure ImageButtons (with highlight behavior and click handling) in a normal layout (e.g. GridBag). This means I have to bolt on the Dnd myself.
    This mean I could extend my component with " implements DragGestureListener, DragSourceListener" and get that to work, but that is pre 1.4. But I can't seem to figure out how to bolt on DnD in the "1.4+" way using the TransferHandler.
    Does anyone have an example on own to add drag support to a JLabel?

    Hm. So on first glance this seems to make a component "slide" visually (hence your remark about a layout manager ), but that is not what Java's Drag-and-Drop (DnD) is about. DnD basically is a visual cut/copy-paste; after starting a drag a Transferable is created (cut/copy), which represents the data this is copied/moved. The drop is equal to a paste. This whole concept is missing.
    On the other hand, I have to think about that, just moving the component may also work just fine. Thanks for the suggestion at the very least!

  • DnD from Outlook to Java.  Any ideas?

    Naive novice here.
    I would like to drag and drop from Outlook into Java app.
    Can this be done?
    If so how might I go about it?
    Any help/information/pointers is appreciated.
    Mick

    hm, its possible to detect the drop from native apps e.g.
    import javax.swing.*;
    import java.awt.dnd.*;
    import java.awt.datatransfer.*;
    public class MickNBT {
       public static void main(String [] arg) {
          JFrame frame = new JFrame("MickNBT");
          JLabel label = new JLabel("Drag to here");
          new DropTarget(label, new DropTargetAdapter() {
             public void drop(DropTargetDropEvent dtde) {
                Transferable t = dtde.getTransferable();
                System.out.println(dtde+"\n"+t);
          frame.getContentPane().add(label);
          frame.pack();
          frame.show();
    } but i'm not sure how you get the information associated with the drop event. I think it has to be a MIME type for you to have a chance of using it but could be mistaken..
    hopefully someone knows more about this part of the operation :)
    asjf

  • How do I chance the place of JLabel and JButton in JPanel.

    I'm using DefaultLayout and I want to give the user the ability to change the place of JLabel and JButton. I managed the DnD part, but when "dropped" the control returns to it's original position.
    I tried using setX() and setY().

    You need to use a null Layout, also known as [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Absolute Positioning

  • Non-English character not showing up in JLabel correctly

    In my program there is a JLabel that displays Chinese characters in several sizes of fonts, it was displaying all of them correctly until my program grew larger and takes longer to initialize, now it is only displaying some sizes of fonts correctly while displaying others as rectangles. Since my program is too large to be imported here, I am trying to demo the problem in a smaller program, but in this smaller program, all sizes of fonts showed up correctly, here it is :
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Java_Test extends JPanel
      static int Total=9000;
      JComboBox ComboBox_Array[]=new JComboBox[Total];
      Font Times_New_Roman_15_Font=new Font("Times New Roman",0,15);
      int Small_Chinese_Font_Size=3;
      String Software_Info_Chinese_Text="<Html><Table Width=100% Border=0 Cellpadding=2 Cellspacing=3><Tr><Td Align=Center><Font Size=6 Color=#3737FF>[ \u4EA7\u54C1\u7BA1\u7406 ] </Font></Td></Tr>"+
                                               "<Tr><Td Align=Center><Font Size=5 Color=green>\u5E2E\u52A9\u4F60\u7BA1\u7406\u4EA7\u54C1, \u5408\u540C, \u53CA\u5176\u5B83\u4FE1\u606F :</Font></Td></Tr>"+
                                               "<Tr><Td><Font Size="+Small_Chinese_Font_Size+" Color=#2255BB>"+
                                                 "<li>\u8F93\u5165, \u7EF4\u62A4\u548C\u6253\u5370\u8BE6\u7EC6\u4EA7\u54C1\u53CA\u4F9B\u8D27\u5546\u4FE1\u606F<Br>"+
                                                 "<li>\u5730\u5740\u548C\u5907\u6CE8\u4FE1\u606F\u53EF\u7528\u591A\u79CD\u8BED\u8A00\u8F93\u5165<Br>"+
                                               "</Font></Td></Tr>"+
                                               "</Table></Html>";
      Java_Test()
        for (int i=0;i<Total;i++) ComboBox_Array=new JComboBox();
    JLabel A_Non_English_Label=new JLabel(Software_Info_Chinese_Text);
    A_Non_English_Label.setFont(Times_New_Roman_15_Font);
    A_Non_English_Label.setForeground(Color.BLUE);
    add(A_Non_English_Label);
    setPreferredSize(new Dimension(500,200));
    static void Out(String message) { System.out.println(message); }
    public static void main(String[] args)
    final Java_Test demo=new Java_Test();
    Dimension Screen_Size=Toolkit.getDefaultToolkit().getScreenSize();
    final JFrame frame=new JFrame("Java Test");
    frame.add(demo);
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e) { System.exit(0); }
    public void windowDeiconified(WindowEvent e) { demo.repaint(); }
    public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
    public void windowOpening(WindowEvent e) { demo.repaint(); }
    public void windowResized(WindowEvent e) { demo.repaint(); }
    public void windowStateChanged(WindowEvent e) { demo.repaint(); }
    frame.pack();
    frame.setBounds((Screen_Size.width-demo.getWidth())/2,(Screen_Size.height-demo.getHeight())/2-10,demo.getWidth(),demo.getHeight()+38);
    frame.setVisible(true);
    As you can see, in this smaller program I'm trying to create a Total of 9000 objects to simulate lots of memory use, but to no avail. It is still displaying all sizes of fonts correctly.
    In my large program if I change html font from size 3 to size 5, it will display correctly, it seems that for certain sizes it can't display properly when the program gets too large and complicated, not because I don't have the fonts, but because of the complexity of my program. I wonder if anyone else has similar problems, and how to solve it ?
    Frank                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I've just made a breakthrough, the large program will work correctly if I comment out : A_Non_English_Label.setFont(Times_New_Roman_15_Font);
    But then the font doesn't look the way I wanted it to be.
    So I changed it to the following :
    ================================================
    Font Courier_New_15_Font=new Font("Courier New",0,15);
    A_Non_English_Label.setFont(Courier_New_15_Font);
    ================================================
    Now it looks not the same but similar to the way I wanted. Thus my question becomes : why it can't work correctly with "Times_New_Roman", but with "Courier_New" in the large program, they both displayed correctly in my small test program ? Is it because it takes too much resource to load the "Times_New_Roman" font ?
    Frank

  • Can not display ImageIcon in a JLabel where you want in the code ???

    Hello, everybody. I need your help to solve a problem I am on it for 2 days now :
    In the constructor of my class, I have a lot of initializing methods. If I try to display an image (with ImageIcon in a JLabel) within one of these methods, there is no problem and the image is correctely displayed. To try that, I use an image stored on my local disk in "c:\\".
    public class Bedes extends javax.swing.JFrame {
    public Bedes() {
    initComponents();
    -- further initializations
    initConnection();
    public void initConnection() {
    try {
    String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
    Properties systemProperties = System.getProperties();
    systemProperties.put("jdbc.drivers", driverName);
    System.setProperties(systemProperties);
    String dbURL = "jdbc:odbc:Bandes Dessin�es";
    String strUtilisateur = "bedes";
    String strMotDePasse = "cdle";
    connectBedes = DriverManager.getConnection(dbURL,strUtilisateur,strMotDePasse);
    catch (Exception e) {
    System.out.println("Exception in DB Contact " + e);
    // Here, I display an image in my JLabel, and it works :
    couvertureAlbumString = "c:\\myImage.jpg";
    couvertureAlbumsIcon = new ImageIcon(couvertureAlbumString);
    couvertureAlbumsJLabel.setIcon(couvertureAlbumsIcon);
    couvertureAlbumsJLabel.repaint();
    }The problem is that I do not want to display these images there, but in a method that read some data's in a Database (with "try"-"catch" blocks). If there is a name of an image store in the DB, then it must be displayed in the JLabel (located in a JFrame -> JDeskTopPane -> JTabbedPane -> JPanel).
    private void searchDetailsForAlbum(String albumsDetailsToSearch) {
    String nomImageCouverture;
    String couvertureAlbumString;
    ImageIcon couvertureAlbumsIcon;
    try {
    PreparedStatement requeteDetailsAlbums = connectBedes.prepareStatement("SELECT * FROM bandes_dess WHERE bede_nom_tome = ?");
    requeteDetailsAlbums.setString(1, albumsDetailsToSearch);
    ResultSet resultatDetailsAlbums = requeteDetailsAlbums.executeQuery();
    resultatDetailsAlbums.next();
    collectionAlbumsJTextField.setText(resultatDetailsAlbums.getString(6));
    genreAlbumsJTextField.setText(resultatDetailsAlbums.getString(9));
    dessinateurAlbumsJTextField.setText(resultatDetailsAlbums.getString(10));
    scenaristeAlbumsJTextField.setText(resultatDetailsAlbums.getString(11));
    coloristeAlbumsJTextField.setText(resultatDetailsAlbums.getString(12));
    prixAchatAlbumsJTextField.setText(resultatDetailsAlbums.getString(13));
    // Here is the name of the Image to de read
    nomImageCouverture = resultatDetailsAlbums.getString(14);
    catch (Exception e) {
    System.out.println("Exception in searchDetailsForAlbum" + e);
    couvertureAlbumString = "c:\\";
    // Here, I check if there is a name for a picture in the DB
    if (!(nomImageCouverture.equals("No"))) {
    // If Yes, I want to display it
    couvertureAlbumString = couvertureAlbumString + nomImageCouverture;
    couvertureAlbumsIcon = new ImageIcon(couvertureAlbumString);
    couvertureAlbumsJLabel.setIcon(couvertureAlbumsIcon);
    couvertureAlbumsJLabel.repaint();
    }My JLabel is well displayed, but empty, without any image on it. WHY ???
    MLK, you asked me to add some debug code. OK, with pleasure, but what is that "debug code" ???
    Thanks a lot in advance if you could help me.
    Christian.

    DEBUG: couvertureAlbumString: c:\Aldebaran-La-Photo
    OK, the extension of the file was NOT present !!!
    I added it and ..... it works pretty good !!!
    Thank you for your idea of the DEBUG.
    Christian.

  • JLabel components not being displayed on the content Panel in Applet

    Hi everyone!!
    Plz give a solution to the following problem:
    I have an applet in which i have JPanel component and on that component i am adding a lot of JLabel components but the problem is that the JLabel components are not displayed on the applet unless i minimize or maximize the applet.
    kindly give solution to the problem.
    Thanks

    Howdy,
    code would be helpful. Here is a very simple JApplet that displays labels okay here in appletviewer. You talk of applets and JLabels. I assume you are using JApplets.
    import javax.swing.*;
    import java.applet.*;
    import java.awt.*;
    public class AppletPie extends JApplet {
         public void init() {
              Container cp = getContentPane();
              cp.setLayout(new FlowLayout());
              cp.add(new JLabel("Show"));
              cp.add(new JLabel("up"));
              cp.add(new JLabel("you"));
              cp.add(new JLabel("dumb"));
              cp.add(new JLabel("labels"));
    }Perhaps something in this code will help you to solve your problem.
    regards
    sjl

  • Getting values from JLabel[] with JButton[] help!

    Hello everyone!
    My problem is:
    I have created JPanel, i have an array of JButtons and array of JLabels, they are all placed on JPanel depending from record count in *.mdb table - JLabels have its own value selected from Access table.mdb! I need- each time i press some button,say 3rd button i get value showing from 3rd JLabel in some elsewere created textfield, if i have some 60 records and 60 buttons and 60 labels its very annoying to add for each button actionlistener and for each button ask for example jButton[1].addActionListener() ...{ jLabel[1].getText()......} and so on!
    Any suggestion will be appreciated! Thank you!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final int ROWS = 10;
        JPanel[] rows = new JPanel[ROWS];
        final JLabel[] labels = new JLabel[ROWS];
        JButton[] buttons = new JButton[ROWS];
        JPanel p = new JPanel(new GridLayout(ROWS,1));
        final JTextField tf = new JTextField(10);
        ActionListener listener = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setText(labels[Integer.parseInt(((JButton)ae.getSource()).getName())].getText());
        for(int x = 0; x < ROWS; x++)
          labels[x] = new JLabel(""+(int)(Math.random()*10000));
          buttons[x] = new JButton("Button "+x);
          buttons[x].setName(""+x);
          buttons[x].addActionListener(listener);
          rows[x] = new JPanel(new GridLayout(1,2));
          rows[x].add(labels[x]);
          rows[x].add(buttons[x]);
          p.add(rows[x]);
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(tf,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • I've put my phone on silent and when it rings it's silent and doesn't vibrate which is what I want, but when I get a text it makes a beep noise but I want this to be silent too. How can I make it silent? Is there a way to do it without using the DND?

    I want my phone to be completely silent. If I flick it on to wilent it doesn't vobrate when it rings which is great and it doesn't vibrate when a message comes through. However, it does beep when a text comes through which I don't want, plus I don't know why it beeps as that isn't my normal text tone anyway. But I just want it to be silent.  I'm not too keen to use the DND function if I dont have too.

    Options for when an iOS device gets locked because of forgotten passcode:
    Restore (and reset passcode) on your device by connecting it to the last computer to which it was connected:
    iTunes: Backing up, updating, and restoring iOS software - http://support.apple.com/kb/HT1414
    If you cannot connect it to the computer to which the device was last connected (or the device was never connected to a computer) you will have to use recovery mode to completely reset the device, losing all data:
    iOS: Unable to update or restore - http://support.apple.com/kb/HT1808 - recovery mode (e.g., cannot connect to computer last used to sync device, iTunes still asks for a password)
    If recovery does not work there's:
    DFU mode: http://osxdaily.com/2010/12/04/ipad-dfu-mode/
    How to put iPod touch / iPhone into DFU mode - http://geekindisguise.wordpress.com/2009/07/16/how-to-put-ipod-touch-iphone-into -dfu-mode/

  • Problem with HTML in a JLabel

    Is it possible to use styles when using HTML in a JLabel?
    Example:
    <html><hr style="height: 1px; color: black;"></html>Doesn't work correctly as this should give a solid 1px high hr, but doesn't. Instead it gives a black hr with a white shade...
    The JLabel it is used in is not customized in any way.

    I too am interested in getting color on an HR to work. Can you summarize what you have done to date? Sample code?
    Note: An easy way to correct it in a Nonframe instance of html is to subclass HTMLEditor to implement your own ViewFactory and own HRuleView which checks the attribute tag color for the color. I've got this to work, but frames don't work since you can call FrameView (not public) and thus have to use the super class - which then by-passes the ViewFactory from then on.
    So a NON-FRAME Solution to give HR color is... Anybody have a better global solution?
    Here is the one line fix to HRuleView .setProperties. So if you subclass HRuleView specifically to do
    public class MyHTMLEditorKit extends HTMLEditorKit { // StyledEditorKit
        private static final ViewFactory defaultFactory = new MyHTMLFactory();
        public static class MyHTMLFactory extends HTMLFactory {//implements ViewFactory {
             public View create(Element elem) {
             Object o = elem.getAttributes().getAttribute(StyleConstants.NameAttribute);
             if (o instanceof HTML.Tag) {
              HTML.Tag kind = (HTML.Tag) o;
              if (kind == HTML.Tag.HR) {
                  return new MyHRuleView(elem);
           return super.create(elem);
    class MyHRuleView extends View  {
         private Color color = null;
         public void setPropertiesFromAttributes() {
              super.setPropertiesFromAttributes();
              try {color = new Color(Integer.decode((String)attr.getAttribute("color")).intValue());} catch (Exception e) {}
         public void paint(Graphics g, Shape a) {
              if (color != null) g.setColor(color);
              super.paint(g, a);
    }

Maybe you are looking for

  • Calling Web Service from PLSQL. Does anyone do this regularly?

    I grabbed the demo_soap package that is available on both metalink and on the regular oracle site, to try calling a web service from plsql to return the xml. I've had minor success, although I get an ORA600 error , for which I've opened up a TAR. How

  • Adapter and/or converter

    for all apple products that have that big white block (used to charge the product), i know its an adapter, but is it a converter? i read somewhere that someone went to a different country and tried to charge their computer and burned out their logic

  • Regarding change in stock account

    Hi, At the time of Production receipt, we will debit the FG Inventory and credit the Change in Stock A/C and at the time of delivering the  Finished goods to the Customer we will debit to Change in Stock and Credit to FG Inventory A/C ( Simply revers

  • Will the iphone 5 be unlocked?

    Hi everyone, I'm just wondering if the soon-to-come-out Iphone 5 will be unlocked or will it be locked to each other the carriers (such as AT&T,Verizon, and sprint)? Because I have a t-mobile phone number, so i was just wondering if I it individually

  • Global selection modifications problem in LR2

    Hello All, I have discovered a bug in LR 2 (including the past and current version 2.3) which I would like to confirm if others have encountered this issue or know of a fix or workaround. When I select a range of images or all the images and then I w