How to outline selected cells during drag and drop in the jtable

Hi,
I have spent a lot of time to find out how to outline selected cells during drag in the jtable, but I did not find the answer.
Can anybody give me a tip, where to read more about this problem or even better, give an example...
I have the following situation:
1.Table has 10 rows and 10 columns
2.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION) and setCellSelectionEnabled(true)
3.user select 5 cells in 4th row (for example cell45,cell46,cell47,cell48 and cell49)
4.user starts dragging. During dragging an outline should be drawn. Outline should be a rectangular with width of 5 cells and height of one cell. Outline should move according to the mouse position.
5.rectangular disappears when dropped
Regards,
Primoz

In "createTransferable" you can create a drag image
which you can paint in "dragOver" and clear in "drop" method of DropTarget :
package dnd;
* DragDropJTableCellContents.java
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class DragDropJTableCellContents extends JFrame {
    public DragDropJTableCellContents() {
        setTitle("Drag and Drop JTable");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().add(createTable("JTable"), BorderLayout.CENTER);
        setSize(400, 300);
        setLocationRelativeTo(null);
    private JPanel createTable(String tableId) {
        DefaultTableModel model = new DefaultTableModel();
        for (int i = 0; i < 10; i++) {
            model.addColumn("Column "+i);
        for (int i = 0; i < 10; i++) {
            String[] rowData = new String[10];
            for (int j = 0; j < 10; j++) {
                rowData[j] = tableId + " " + i + j;
            model.addRow(rowData);
        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        table.setCellSelectionEnabled(true);
        JScrollPane scrollPane = new JScrollPane(table);
        table.setDragEnabled(true);
        TableTransferHandler th = new TableTransferHandler();
        table.setTransferHandler(th);
        table.setDropTarget(new TableDropTarget(th));
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(scrollPane);
        panel.setBorder(BorderFactory.createTitledBorder(tableId));
        return panel;
    public static void main(String[] args) {
        new DragDropJTableCellContents().setVisible(true);
    abstract class StringTransferHandler extends TransferHandler {
        public int dropAction;
        protected abstract String exportString(JComponent c);
        protected abstract void importString(JComponent c, String str);
        @Override
        protected Transferable createTransferable(JComponent c) {
            return new StringSelection(exportString(c));
        @Override
        public int getSourceActions(JComponent c) {
            return COPY;
        @Override
        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;
        @Override
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            for (int ndx = 0; ndx < flavors.length; ndx++) {
                if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                    return true;
            return false;
    class TableTransferHandler extends StringTransferHandler {
        private int dragRow;
        private int[] dragColumns;
        private BufferedImage[] image;
        private int row;
        private int[] columns;
        public JTable target;
        @Override
        protected Transferable createTransferable(JComponent c) {
            JTable table = (JTable) c;
            dragRow = table.getSelectedRow();
            dragColumns = table.getSelectedColumns();
            createDragImage(table);
            return new StringSelection(exportString(c));
        protected String exportString(JComponent c) {
            JTable table = (JTable) c;
            row = table.getSelectedRow();
            columns = table.getSelectedColumns();
            StringBuffer buff = new StringBuffer();
            for (int j = 0; j < columns.length; j++) {
                Object val = table.getValueAt(row, columns[j]);
                buff.append(val == null ? "" : val.toString());
                if (j != columns.length - 1) {
                    buff.append(",");
            return buff.toString();
        protected void importString(JComponent c, String str) {
            target = (JTable) c;
            DefaultTableModel model = (DefaultTableModel) target.getModel();
            String[] values = str.split("\n");
            int colCount = target.getSelectedColumn();
            int max = target.getColumnCount();
            for (int ndx = 0; ndx < values.length; ndx++) {
                String[] data = values[ndx].split(",");
                for (int i = 0; i < data.length; i++) {
                    String string = data;
if(colCount < max){
model.setValueAt(string, target.getSelectedRow(), colCount);
colCount++;
public BufferedImage[] getDragImage() {
return image;
private void createDragImage(JTable table) {
if (dragColumns != null) {
try {
image = new BufferedImage[dragColumns.length];
for (int i = 0; i < dragColumns.length; i++) {
Rectangle cellBounds = table.getCellRect(dragRow, i, true);
TableCellRenderer r = table.getCellRenderer(dragRow, i);
DefaultTableModel m = (DefaultTableModel) table.getModel();
JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
lbl.setBounds(cellBounds);
BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
Graphics2D graphics = img.createGraphics();
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
lbl.paint(graphics);
graphics.dispose();
image[i] = img;
} catch (RuntimeException re) {
class TableDropTarget extends DropTarget {
private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
private Rectangle rect2D = new Rectangle();
private TableTransferHandler handler;
public TableDropTarget(TableTransferHandler h) {
super();
this.handler = h;
@Override
public void dragOver(DropTargetDragEvent dtde) {
handler.dropAction = dtde.getDropAction();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
Point location = dtde.getLocation();
int row = table.rowAtPoint(location);
int column = table.columnAtPoint(location);
table.changeSelection(row, column, false, false);
paintImage(table, location);
autoscroll(table, location);
super.dragOver(dtde);
public void dragExit(DropTargetDragEvent dtde) {
clearImage((JTable) dtde.getDropTargetContext().getComponent());
super.dragExit(dtde);
@Override
public void drop(DropTargetDropEvent dtde) {
Transferable data = dtde.getTransferable();
JTable table = (JTable) dtde.getDropTargetContext().getComponent();
clearImage(table);
handler.importData(table, data);
super.drop(dtde);
private final void paintImage(JTable table, Point location) {
Point pt = new Point(location);
BufferedImage[] image = handler.getDragImage();
if (image != null) {
table.paintImmediately(rect2D.getBounds());
rect2D.setLocation(pt.x - 15, pt.y - 15);
int wRect2D = 0;
int hRect2D = 0;
for (int i = 0; i < image.length; i++) {
table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
pt.x += image[i].getWidth();
if (hRect2D < image[i].getHeight()) {
hRect2D = image[i].getHeight();
wRect2D += image[i].getWidth();
rect2D.setSize(wRect2D, hRect2D);
private final void clearImage(JTable table) {
table.paintImmediately(rect2D.getBounds());
private Insets getAutoscrollInsets() {
return autoscrollInsets;
private void autoscroll(JTable table, Point cursorLocation) {
Insets insets = getAutoscrollInsets();
Rectangle outer = table.getVisibleRect();
Rectangle inner = new Rectangle(outer.x + insets.left,
outer.y + insets.top,
outer.width - (insets.left + insets.right),
outer.height - (insets.top + insets.bottom));
if (!inner.contains(cursorLocation)) {
Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
cursorLocation.y - insets.top,
insets.left + insets.right,
insets.top + insets.bottom);
table.scrollRectToVisible(scrollRect);
Edited by: Andre_Uhres on Nov 18, 2007 10:03 PM

Similar Messages

  • How to change mouse cursor during drag and drop

    Hi Guys,
    Iam performing a Drag and drop from Table1(on top of the figure) to Table2(down in the figure).
    see attached figure
    http://www.upload-images.net/imagen/e80060d9d3.jpg
    Have implemented the Drag and drop functionality using "Transferable" and "TransferHandler"using the java tutorial
    http://java.sun.com/docs/books/tutorial/uiswing/examples/dnd/index.html#ExtendedDndDemo
    Now My problem is that ,I want to make the 1st column in Table2(ie: Column2-0) not to accept any drops so that the cursor appears like a "No-Drop" cursor but with selection on the column cell during a drop action.
    Also when I move my cursor between "column2-0" and "column2-1",want to to have the "No-Drop" and "Drop" cursor to appear depending on the column.
    How can I achieve it using the TransferHandle class.Dont want to go the AWT way of implementing all the source and target listeners on my own.
    Have overridded the "CanImort" as follows:
    public boolean canImport(JComponent c, DataFlavor[] flavors) {
         JTable table = (JTable)c;      
    Point p = table.getMousePosition();
    /* if(p==null)
         return false;
    int selColIndex = table.columnAtPoint(p);
    if(selColIndex==0)
         return false;*/
    If I execute the above commented code,The "No-Drop" Icon appears in "column2-0",but no cell selection.Also If I move to "column2-1",which is the 1st column,Still get the "No-Drop" Icon there,also with no cell selection.
    for (int i = 0; i < flavors.length; i++) {
    if ((DataFlavor.stringFlavor.equals(flavors))) {
    return true;
    return false;
    Thanks in advance.....
    Edited by: Kohinoor on Jan 18, 2008 3:47 PM

    If you found the selection column based on the mouse pointer, then based on the column, you can set the cursor pointer as any one as below :
    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    setCursor(new Cursor(Cursor.HAND_CURSOR));

  • How do I set up my drag and drop questionaire to export to a XML file?

    How do I set up my drag and drop questionaire to export to a
    XML file?
    I have a 70 seperate SWF files that pose a question and
    contain a drag and drop rank order response of 1,2,3,4.How do I set
    up a XML file that receives the responses.I don't understand how to
    do the Actionscript
    and get my responses to connect to the XML.Please
    Help!Thanks!
    Here's an example of my XML.
    <assessment>
    <sessionid>ffae926ea290ee93c3f26669c6c04a92</sessionid>
    <request>save_progress</request>
    <question>
    <number>1</number>
    <slot_a>2</slot_a>
    <slot_b>1</slot_b>
    <slot_c>4</slot_c>
    <slot_d>3</slot_d>
    </question>
    <question>
    <number>2</number>
    <slot_a>4</slot_a>
    <slot_b>3</slot_b>
    <slot_c>2</slot_c>
    <slot_d>1</slot_d>
    </question>
    <question>
    <number>3</number>
    <slot_a>1</slot_a>
    <slot_b>2</slot_b>
    <slot_c>3</slot_c>
    <slot_d>4</slot_d>
    </question>
    </assessment>

    Use XML.sendAndLoad.
    http://livedocs.macromedia.com/flash/8/main/00002879.html
    You will need a server script to receive the XML structure
    and it depends on
    the server scripting language how you obtain that data. Then
    you can either
    populate a database or write to a static file or even email
    the XML data
    received from Flash.
    For a basic example, I have two links I use for students in
    my Flash
    courses:
    http://www.hosfordusa.com/ClickSystems/courses/flash/examples/XMLASP/Ex01/XMLASPEchoEx01_D oc.php
    http://www.hosfordusa.com/ClickSystems/courses/flash/examples/XMLPHP/EX01/XMLPHPEchoEx01_D oc.php
    Lon Hosford
    www.lonhosford.com
    May many happy bits flow your way!
    "kenpoian" <[email protected]> wrote in
    message
    news:e5i9hp$cs6$[email protected]..
    How do I set up my drag and drop questionaire to export to a
    XML file?
    I have a 70 seperate SWF files that pose a question and
    contain a drag and
    drop rank order response of 1,2,3,4.How do I set up a XML
    file that receives
    the responses.I don't understand how to do the Actionscript
    and get my responses to connect to the XML.Please
    Help!Thanks!
    Here's an example of my XML.
    <assessment>
    <sessionid>ffae926ea290ee93c3f26669c6c04a92</sessionid>
    <request>save_progress</request>
    <question>
    <number>1</number>
    <slot_a>2</slot_a>
    <slot_b>1</slot_b>
    <slot_c>4</slot_c>
    <slot_d>3</slot_d>
    </question>
    <question>
    <number>2</number>
    <slot_a>4</slot_a>
    <slot_b>3</slot_b>
    <slot_c>2</slot_c>
    <slot_d>1</slot_d>
    </question>
    <question>
    <number>3</number>
    <slot_a>1</slot_a>
    <slot_b>2</slot_b>
    <slot_c>3</slot_c>
    <slot_d>4</slot_d>
    </question>
    </assessment>

  • Issue during drag and drop in vb

    Hi Uwe,
    I want an urgent help on the following scenario.
    When i do a drag and drop anywhere on vb other than a link or spot.The screen freezes and when i try to do at lead selection on any of the FPM objects at the same time I get an assert condition violated dump.After my analysis I think its still possess the drop event when i try to do any other action on fpm at same time.This issue is happening for me in ie11 but for ie10 its working fine.
    Please suggest some remedy!
    Thanks
    Siju

    Hello Siju,
    I am aware of multiple issues with drag and drop in the context of VB embedded in FPM/WD. In order to sort this out correctly and get the right solution I suggest to open a support ticket on BC-WD-CMP-FPM.
    Best regards,
    Uwe

  • How come in Pages, i cannot drag and drop images?

    how come in Pages, i cannot drag and drop images?

    Yes you can in all versions.
    It helps if you actually describe what you are doing.
    Where are you dragging it from and where are you dragging it to?
    In what version of Pages?
    I suspect you are trying to drag an image into a Table, Header or Footer in Pages 5, which is no longer possible. Feature removed by Apple.
    Peter

  • How can we restrict the type of components that can be dragged and dropped from the sidekick CQ

    how can we restrict the type of components that can be dragged and dropped from the sidekick CQ

    Generally drop the components at parasys. The components allowed on the parsys is control via the design mode of the page.So restrict components at the design of the parsys. http://dev.day.com/docs/en/cq/current/wcm/working_with_cq_wcm/using_edit_designandpreviewm odes.html#Design%20Mode

  • File can not be moved by drag and drop in the finder when not open Finder windows

    With the operating system OSX Snow Leopard, it was possible, for example, a file from the desktop to pull drag and drop on the Finder icon, the page opened after a short and you could put the file in a folder.
    At this stage I must first open the Finder to drag a file into the destination folder.
    Is it a setting or is there anything wrong with my Mountain Lion properly?
    It is often the case that several windows of other applications are open or in Fullscreen are, then I would, as I also already knew and am accustomed, for example a file regardless of the location from which drag drag and drop in the Finder without leaving the / program / ​​site to open the Finder, before returning to the file then select I wanted to move.
    Note: For all other programs it works.
    Finder not only in where it makes the most sense.
       Picture 1: Finder window opens when you drag a file to the Finder icon
       Picture 2: Finder icon flashes but the Finder window does not open. Finder windows have previously by clicking on the icon in the Dock will be open to pull a      file into it.
       Thanks in advance for your help :-)

    Yes, all I can tell you is that Finder does not have that function in ML. Your system is "working as expected".
    You can file feedback here.

  • Drag and drop from/to JTable

    Hi,
    I am trying to implement drag and drop between two JTables. I have two questions about this and I hope you can help me.
    1. I would like to prevent the user from droping an Object in the same JTable as the object came from in the first place. How can I do that?
    2. How can I drop an Object in a JTable if there isn�t any rows in the table?
    I am using jdk 1.4.
    Thanks!!!
    :-)Lisa

    I think you just use setDragEnabled(true) on both tables.
    If not, then maybe this link will help:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/dnd.html

  • An mp3 file on my computer will not import to itunes by either the drag-and-drop or the Add File to Library method.  Can't figure out what I'm doing wrong.  My OS is Windows 7.

    I purchased an mp3 from a private website on my laptop.  The itunes library i sync ipod to is on my desktop, so i copied the mp3 onto a flash drive and then into my desktop in the Downloads folder and Desktop folder as well as the itunes music folder, 3 places.  I opened itunes on the desktop and read the instructions for importing music that's already in my computer.  Neither the drag-and-drop or the Add File to Library method works.  I've tried both ways over and over.  Cannot figure out what the problem is.  I do note that the name of the mp3 file doesn't show the .mp3 extension, it appears as simply it's title, Eating Healthy, without any extension at all.  Could the filename be the problem, or do you have any other idea what I'm doing wrong?  My OS is Windows 7, using IE9.  Thanks.
    ADDENDUM AFTER READING ANOTHER DISCUSSION HERE:  I have now tried right clicking the song in Windows Explorer and choosing Open With, clicking itunes.  The mp3 plays in itunes but does not add to the library.

    I don't have a Recently Added playlist.  However, I discovered that the file I had named Eating Healthy was given the name You Can Enjoy Eating Healthy when it copied to iTunes.  I'm guessing iTunes pulled the full name of the piece from the internet.  Upshot--the mp3 did transfer to iTunes on all 3 tries, but I was looking in my alphabetized list under E, not Y, so I didn't see it there.  Thanks for your help. 

  • [SOLVED] Thunar 1.6 doesn't drag-and-drop with the right mouse button

    Hallo all.
    It might be something I've done (though I did delete my ~/.config/Thunar directory before upgrading), but Thunar doesn't let me drag-and-drop with the right mouse button, thus stopping me from copying something instead of moving it, etc. Has anyone else had that too?
    Last edited by GordonGR (2012-12-28 14:34:20)

    Joel wrote:
    anonymous_user wrote:Is it supposed to be with the right-mouse button? I always thought drag and drop was done with the left button?
    Could be right-hand user
    Come on! Read what GordonGR wrote!
    Microsoft Windows, Nautilus, the Haiku Tracker, and probably many other file managers have a feature where, when you right-click or middle-click and drag an icon to a new location, a pop-up menu appears and asks what you'd like to do (Move, Copy, Link). I thought I used to use this feature in Thunar too but it seems to have stopped working in recent versions. Has anyone else had any experience with it?
    EDIT: Here's random blogger talking about the feature in an older version of Thunar: http://jeromeg.blog.free.fr/index.php?p … and-tricks So that's good, I wasn't just imagining the feature.
    Last edited by drcouzelis (2012-12-12 03:45:05)

  • Drag and Drop between two JTables

    I tried to implement drag and drop between two JTables using data transfer, but i did not get it to work, that dnd works in both directions. i have my own transferhandler, but if is use setTransferHandler(handler), i'm no longer able to start a drag from that table. i also tried to use a mouse listener to call exportAsDrag, but i only works in one direction. any ideas or examples?

    That is a rather large request, and indicates that you have likely not spent much time researching the subject before posting. Read up on Swing drag & drop here (http://java.sun.com/docs/books/tutorial/dnd/), then ask specific questions about something you don't understand, problems with your implementation, etc.
    Mike

  • Drag and Drop Image into JTable

    I was wondering if anyone can tell me if it is possible to have an image dragged and dropped into a JTable where the single image snaps to multiple columns and rows?
    Thank you.

    Can anyone point me in the right direction for doing the following:
    Drag and drop an image into a JTable where the single image snaps to multiple columns and rows.
    Thanks.

  • Hello, does anyone know why when i drag and drop from the internet,why my images never show up?

    hello, does anyone know why when i drag and drop from the internet,why my images never show up?

    I'm wanting to drag images from the internet into a folder on my desktop or hard drive. I am used to being able to drag just about any image from any website off the web and into a folder on my old mac, but since I got my laptop, I've noticed I cannot do that. Is it a preference?

  • [svn:fx-trunk] 11067: Drag and Drop - tweak the positioning of the drop indicator, allow 1 pixel overlap with the container border

    Revision: 11067
    Author:   [email protected]
    Date:     2009-10-21 16:32:39 -0700 (Wed, 21 Oct 2009)
    Log Message:
    Drag and Drop - tweak the positioning of the drop indicator, allow 1 pixel overlap with the container border
    QE notes: None
    Doc notes: None
    Bugs: None
    Reviewer: None
    Tests run: checkintests
    Is noteworthy for integration: No
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/layouts/HorizontalLayout.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/layouts/TileLayout.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/layouts/VerticalLayout.as

    Revision: 11067
    Author:   [email protected]
    Date:     2009-10-21 16:32:39 -0700 (Wed, 21 Oct 2009)
    Log Message:
    Drag and Drop - tweak the positioning of the drop indicator, allow 1 pixel overlap with the container border
    QE notes: None
    Doc notes: None
    Bugs: None
    Reviewer: None
    Tests run: checkintests
    Is noteworthy for integration: No
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/layouts/HorizontalLayout.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/layouts/TileLayout.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/layouts/VerticalLayout.as

  • I deleted i photo from search folder, reloaded the software and now I can not drag and drop to the desktop. Help

    I deleted i photo from search folder, reloaded the software and now I can not drag and drop to the desktop. Help

    Look in the Applications folder to see if iPhoto is still there. If it is drag it back to the Finder Sidebar. If it is no longer in the Applications folder post back, you can also look in the Trash it might still be there.

Maybe you are looking for

  • Looking For App to Sync Calendar

    Good evening. This is my first go round with a blackberry so I am new to all this.  I am tired of having a desktop calendar, paper calendar, and the calendar that is on my 8300.  I am looking to find a program that I can plug all my events, meetings,

  • How do I change my iCloud settings from Uk to USA?

    Hi All, I have set my icloud account in the UK but I live now in California and I cannot download american apps as the system tells me I need to change my settings. Any idea how to do that? Thanks a lot!

  • IP Blacklisting

    Dear Team, We are mail service providers. The client send the mails by using our IP. Client get delivery failure mails with following reason.  Failed Recipient: X  Reason: Remote host said: 550 5.7.1 Service unavailable; Client host   [180.179.114.23

  • Shared variable engine memory problem

    Hello, I have a lot of problems with DSC 8. The server that worked very well in DSC 7, in DSC 8 is creating a lot of problems starting with memory leaks in tagsrv process. I have over 5000 shared variables and when I publish them the tagsrv is around

  • Smartform errors encountered in Citrix

    We are running into an issue when we want to start Smartforms editor Microsoft Word in SAP clients while working via Citrix. The error message from MS Word: " the macro cannot be found or has been dsiabled because of your Macro security settings" any