Do I use DnD or MouseMotionListener ?

I am wondering about the pros and cons of using dnd api vs. MouseListener/MouseMotionListener.
I am experimenting with drag-and-drop using a simple app that allows components to be rearranged by dragging.
Here is a description of desired test program behavior:
For instance, if 5 rectangular panel components [A,B,C,D,E] are in a vertical row, and B is dragged onto D, then it is meant that B should be moved to before D, so the components will jump to new order [A,C,B,D,E]. (This is a simple test app for my learning, so I am ignoring that nothing can be moved to after E.)
There is a visual indicator during the drag operation. In the above example where B, the dragsource, is dragged to D:
- When drag begins, dragsource is on B, so indicator is a little notch arrow between A and B.
- When drag moves onto C, notch arrow jumps to between B and C.
- When drag moves onto D, notch arrow jumps to between C and D.
- When drag released on D, components jump to rearrage themselves as user would expect from indicator arrow position.
If drag goes outside the 5 components, the indicator arrow will stay where it was (i.e. it only updates at enter not exit)
If mouse released outside the 5 components (or outside app window), the drag/move operation is aborted: the indicator goes away and no components move.
The dragged-into component listener calls to parent panel to update the indicator arrow.
The dropped-onto component listener calls to parent panel to reorder children.
This description is pretty sound and simple in theory, but I am new to MouseMotionListener and java.awt.dnd. Which is better for this purpose?
DND:
- Can use listener to tell me about the enter, drop, and dragEnded events.
- Since my app is not truly performing datatransfer, I would need to fool it with adding new action or dataflavor type (so not to mix up with other types of dragsources and targets).
- I don't know how to discover the dragged component from a DropTargetDragEvent
MouseMotion:
- Would probably simplify everything and shorten my code.
- Can use listener to tell me about the drag, enter, and release events.
- Don't know how I would detect/handle the cases where mouse moved/released outside the application or outside the listening components.
/Mel
I will post the so-far-source if anyone is actually interested to see it.

Hi,
I know it kinda very late as its been a while since you posted your question, but i realized that is exavtly what i am trying to achieve in my project. Move labels within a panel among themselves. I was wondering if you might still have to code and if so, can you please send it to me?? my email id is [email protected]
or if ou dont, and you do read this email, I would really appreciate it if you can let me know how?
thanks very mucg,
Sri.

Similar Messages

  • HT5463 Is it possible to use DND  on a single number and will this apply to messages as well?

    Can you use DND on a single phone number?

    What do you mean by "use DND"? Do you mean you want to block a single user? Or let only a single user through. The latter would be fairly simple. Just make that person the only "Favorite" and set DND to allow only favorites through.  Blocking only one person can be simply accomplished by assigning them customer ring and text tones of silence.

  • DnD and MouseMotionListener

    Hi,
    I am trying to move one panel(1) inside another one -
    panel(2) with DnD. I think that everything works good, but only one problem. Can't change positioning (x,y) of panel(1) inside the panel(2). I am trying to use MouseMotionListener-mouseDragged(), but no help.
    May be I am doing something wrong. How to coonect action of MouseMotionListener with DnD.
    Here is my code.
    class DNDPanel extends JPanel implements
    DropTargetListener, MouseMotionListener {
    int x;
    int y;
    public DNDPanel() {
    super();
    setBackground(Color.black);
    setLayout(null);
    add(new DraggablePanel()).setLocation(x, y);
    addMouseMotionListener(this);
    DropTarget dt = new DropTarget(this, this);
    public void mouseDragged(MouseEvent e) {
    x = e.getX();
    y = e.getY(); // I think that problem hides somewhere here.
    public void drop(DropTargetDropEvent dtde) {
    if(isValidDragDrop(dtde.getDropAction(), dtde.getCurrentDataFlavors())) {
    dtde.acceptDrop(dtde.getDropAction());
    try {
    Transferable xfer = dtde.getTransferable();
    Object obj = xfer.getTransferData(MyFlavors.draggablePanelFlavor);
    if(obj instanceof JComponent) {
    add(new DraggablePanel()).setLocation(x, y);
    // or here???
    revalidate();
    catch(Exception exc) {
    System.err.println(exc);
    exc.printStackTrace();
    dtde.dropComplete(false);
    else {dtde.rejectDrop();}
    class DraggablePanel extends JPanel implements DragSourceListener,
    DragGestureListener,
    Transferable {
    public DraggablePanel() {
    super();
    setBackground(Color.red);
    setPreferredSize(new Dimension(100,100));
    setBounds(0,0,100,100);
    JButton button = new JButton("Beep");
    button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    Toolkit.getDefaultToolkit().beep();
    add(button);
    DragSource ds = DragSource.getDefaultDragSource();
    DragGestureRecognizer dgr = ds.createDefaultDragGestureRecognizer(
    this, DnDConstants.ACTION_COPY_OR_MOVE, this);
    Thank you. I really need HELP!
    DM.

    hi,
    I dont completely understand your question, but if you are trying to get the coordinates of the component with respect to the parent panel, try methods from SwingUtilities, like converPoint,.....
    Am not sure if that completely answers your question, but I had a similiar problem, ad then used this. Hope this helps!
    Sri.

  • How can I use Drap and Drop in Linux system?

    I try to use DnD in a item from "explorer" in Linux into my application, but it does atually not work. The same version is work well on Windows. Below is code (3 separated files):
    * FileAndTextTransferHandler.java is used by the 1.4
    * DragFileDemo.java example.
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    class FileAndTextTransferHandler extends TransferHandler {
        private DataFlavor fileFlavor, stringFlavor;
        private TabbedPaneController tpc;
        private JTextArea source;
        private boolean shouldRemove;
        protected String newline = "\n";
        //Start and end position in the source text.
        //We need this information when performing a MOVE
        //in order to remove the dragged text from the source.
        Position p0 = null, p1 = null;
        FileAndTextTransferHandler(TabbedPaneController t) {
           tpc = t;
           fileFlavor = DataFlavor.javaFileListFlavor;
           stringFlavor = DataFlavor.stringFlavor;
        public boolean importData(JComponent c, Transferable t) {
            JTextArea tc;
            if (!canImport(c, t.getTransferDataFlavors())) {
                return false;
            //A real application would load the file in another
            //thread in order to not block the UI.  This step
            //was omitted here to simplify the code.
            try {
                if (hasFileFlavor(t.getTransferDataFlavors())) {
                    String str = null;
                    java.util.List files =
                         (java.util.List)t.getTransferData(fileFlavor);
                    for (int i = 0; i < files.size(); i++) {
                        File file = (File)files.get(i);
                        //Tell the tabbedpane controller to add
                        //a new tab with the name of this file
                        //on the tab.  The text area that will
                        //display the contents of the file is returned.
                        tc = tpc.addTab(file.toString());
                        BufferedReader in = null;
                        try {
                            in = new BufferedReader(new FileReader(file));
                            while ((str = in.readLine()) != null) {
                                tc.append(str + newline);
                        } catch (IOException ioe) {
                            System.out.println(
                              "importData: Unable to read from file " +
                               file.toString());
                        } finally {
                            if (in != null) {
                                try {
                                    in.close();
                                } catch (IOException ioe) {
                                     System.out.println(
                                      "importData: Unable to close file " +
                                       file.toString());
                    return true;
                } else if (hasStringFlavor(t.getTransferDataFlavors())) {
                    tc = (JTextArea)c;
                    if (tc.equals(source) && (tc.getCaretPosition() >= p0.getOffset()) &&
                                             (tc.getCaretPosition() <= p1.getOffset())) {
                        shouldRemove = false;
                        return true;
                    String str = (String)t.getTransferData(stringFlavor);
                    tc.replaceSelection(str);
                    return true;
            } catch (UnsupportedFlavorException ufe) {
                System.out.println("importData: unsupported data flavor");
            } catch (IOException ieo) {
                System.out.println("importData: I/O exception");
            return false;
        protected Transferable createTransferable(JComponent c) {
            source = (JTextArea)c;
            int start = source.getSelectionStart();
            int end = source.getSelectionEnd();
            Document doc = source.getDocument();
            if (start == end) {
                return null;
            try {
                p0 = doc.createPosition(start);
                p1 = doc.createPosition(end);
            } catch (BadLocationException e) {
                System.out.println(
                  "Can't create position - unable to remove text from source.");
            shouldRemove = true;
            String data = source.getSelectedText();
            return new StringSelection(data);
        public int getSourceActions(JComponent c) {
            return COPY_OR_MOVE;
        //Remove the old text if the action is a MOVE.
        //However, we do not allow dropping on top of the selected text,
        //so in that case do nothing.
        protected void exportDone(JComponent c, Transferable data, int action) {
            if (shouldRemove && (action == MOVE)) {
                if ((p0 != null) && (p1 != null) &&
                    (p0.getOffset() != p1.getOffset())) {
                    try {
                        JTextComponent tc = (JTextComponent)c;
                        tc.getDocument().remove(
                           p0.getOffset(), p1.getOffset() - p0.getOffset());
                    } catch (BadLocationException e) {
                        System.out.println("Can't remove text from source.");
            source = null;
        public boolean canImport(JComponent c, DataFlavor[] flavors) {
            if (hasFileFlavor(flavors))   { return true; }
            if (hasStringFlavor(flavors)) { return true; }
            return false;
        private boolean hasFileFlavor(DataFlavor[] flavors) {
            for (int i = 0; i < flavors.length; i++) {
                if (fileFlavor.equals(flavors)) {
    return true;
    return false;
    private boolean hasStringFlavor(DataFlavor[] flavors) {
    for (int i = 0; i < flavors.length; i++) {
    if (stringFlavor.equals(flavors[i])) {
    return true;
    return false;
    * TabbedPaneController.java is used by the 1.4
    * DragFileDemo.java example.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    * Class that manages area where the contents of
    * files are displayed.  When no files are present,
    * there is a simple JTextArea instructing users
    * to drop a file.  As soon as a file is dropped,
    * a JTabbedPane is placed into the window and
    * each file is displayed under its own tab.
    * When all the files are removed, the JTabbedPane
    * is removed from the window and the simple
    * JTextArea is again displayed.
    public class TabbedPaneController {
        JPanel tabbedPanel = null;
        JTabbedPane tabbedPane;
        JPanel emptyFilePanel = null;
        JTextArea emptyFileArea = null;
        FileAndTextTransferHandler transferHandler;
        boolean noFiles = true;
        String fileSeparator;
        public TabbedPaneController(JTabbedPane tb, JPanel tp) {
            tabbedPane = tb;
            tabbedPanel = tp;
            transferHandler = new FileAndTextTransferHandler(this);
            fileSeparator = System.getProperty("file.separator");
            //The split method in the String class uses
            //regular expressions to define the text used for
            //the split.  The forward slash "\" is a special
            //character and must be escaped.  Some look and feels,
            //such as Microsoft Windows, use the forward slash to
            //delimit the path.
            if ("\\".equals(fileSeparator)) {
                fileSeparator = "\\\\";
            init();
        public JTextArea addTab(String filename) {
            if (noFiles) {
                tabbedPanel.remove(emptyFilePanel);
                tabbedPanel.add(tabbedPane, BorderLayout.CENTER);
                noFiles = false;
            String[] str = filename.split(fileSeparator);
            return makeTextPanel(str[str.length-1], filename);
        //Remove all tabs and their components, then put the default
        //file area back.
        public void clearAll() {
            if (noFiles == false) {
                tabbedPane.removeAll();
                tabbedPanel.remove(tabbedPane);
            init();
        private void init() {
            String defaultText =
                "Select one or more files from the file chooser and drop here...";
            noFiles = true;
            if (emptyFilePanel == null) {
                emptyFileArea = new JTextArea(20,15);
                emptyFileArea.setEditable(false);
                emptyFileArea.setDragEnabled(true);
                emptyFileArea.setTransferHandler(transferHandler);
                emptyFileArea.setMargin(new Insets(5,5,5,5));
                JScrollPane fileScrollPane = new JScrollPane(emptyFileArea);
                emptyFilePanel = new JPanel(new BorderLayout(), false);
                emptyFilePanel.add(fileScrollPane, BorderLayout.CENTER);
            tabbedPanel.add(emptyFilePanel, BorderLayout.CENTER);
            tabbedPanel.repaint();
            emptyFileArea.setText(defaultText);
        protected JTextArea makeTextPanel(String name, String toolTip) {
            JTextArea fileArea = new JTextArea(20,15);
            fileArea.setDragEnabled(true);
            fileArea.setTransferHandler(transferHandler);
            fileArea.setMargin(new Insets(5,5,5,5));
            JScrollPane fileScrollPane = new JScrollPane(fileArea);
            tabbedPane.addTab(name, null, (Component)fileScrollPane, toolTip);
            tabbedPane.setSelectedComponent((Component)fileScrollPane);
            return fileArea;
    * DragFileDemo.java is a 1.4 example that
    * requires the following file:
    *    FileAndTextTransferHandler.java
    *    TabbedPaneController.java
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class DragFileDemo extends JPanel
                              implements ActionListener {
        JTextArea fileArea;
        JFileChooser fc;
        JButton clear;
        TabbedPaneController tpc;
        public DragFileDemo() {
            super(new BorderLayout());
            fc = new JFileChooser();;
            fc.setMultiSelectionEnabled(true);
            fc.setDragEnabled(true);
            fc.setControlButtonsAreShown(false);
            JPanel fcPanel = new JPanel(new BorderLayout());
            fcPanel.add(fc, BorderLayout.CENTER);
            clear = new JButton("Clear All");
            clear.addActionListener(this);
            JPanel buttonPanel = new JPanel(new BorderLayout());
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            buttonPanel.add(clear, BorderLayout.LINE_END);
            JPanel upperPanel = new JPanel(new BorderLayout());
            upperPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            upperPanel.add(fcPanel, BorderLayout.CENTER);
            upperPanel.add(buttonPanel, BorderLayout.PAGE_END);
            //The TabbedPaneController manages the panel that
            //contains the tabbed pane.  When there are no files
            //the panel contains a plain text area.  Then, as
            //files are dropped onto the area, the tabbed panel
            //replaces the file area.
            JTabbedPane tabbedPane = new JTabbedPane();
            JPanel tabPanel = new JPanel(new BorderLayout());
            tabPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            tpc = new TabbedPaneController(tabbedPane, tabPanel);
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                upperPanel, tabPanel);
            splitPane.setDividerLocation(400);
            splitPane.setPreferredSize(new Dimension(530, 650));
            add(splitPane, BorderLayout.CENTER);
        public void setDefaultButton() {
            getRootPane().setDefaultButton(clear);
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == clear) {
                tpc.clearAll();
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("DragFileDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the menu bar and content pane.
            DragFileDemo demo = new DragFileDemo();
            demo.setOpaque(true); //content panes must be opaque
            frame.setContentPane(demo);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
            demo.setDefaultButton();
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();

    I'm currently using Linux Fedora system.
    Doesn't matter. There's no standard way for D&D on Linux, no single API.
    Every application has its own mechanism which may or may not be compatible with any other.
    Gnome and KDE groups are doing some work to provide a common standard but as you know the Linux zealots are completely opposed to anyone telling them what to do (such as creating standards) and won't in general follow them.

  • Custom Cursor and Drag Image in 1.4 DnD

    What is the proper way to provide a custom cursor and drag image in 1.4 DnD? Say we initiate the drag on a component that supports data transfer (such as a JTree).

    Well, this is strange. My app was locking up (100% CPU) when using DND from windows Explorer.
    I noticed that another part of the same appliction was working perfictly. The difference: JFrame .vs. JDialog. I switched the offending JDialog to a JFrame and all works perfictly now!
    java version "1.4.0"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)
    Java HotSpot(TM) Client VM (build 1.4.0-b92, mixed mode)
    I would like to switch back at some point, but my g.setXORMode() problem is a much bigger issue for us. (That is, once you enter the XOR mode, you can not go back!)

  • How to use JViewPort.scrollRectToVisible()?

    Hi there,
    I have a JTable in a JScrollPane. The Drag and Drop for this JTable is done with MouseListener and MouseMotionListener. I do not implement DragSource, DropTarget, etc.
    When dragging over the edge of the visible area, the JTable should automatically scroll. I tried that with the following:
    public void mouseDragged(MouseEvent e) {
      if (!jTable1.getVisibleRect().contains(e.getPoint())){
        jScrollPane1.getViewport().scrollRectToVisible(new Rectangle(e.getPoint()));
    }That works fine when scrolling to the right or down. But scrolling left or upwards, doesn't.
    I have the used values printed out and they should work fine:
    e.getPoint():             x=715,y=56  
    jTable1.getVisibleRect(): x=254,y=149,width=1155,height=411So, I say the JTable has to be scrolled, so that Point (715, 56) becomes visible. This value is obviously above Point y=149 of the currently visible area. So why is it not scrolled?
    It seems that the scrolling only begins, when I move the Mouse Pointer above the whole Table. That means also moving it above the visible area.
    What am I doing wrong?

    No, I do not (and cannot) use TransferHandler and such. The Drag and Drop is done manually by using MouseListener and MouseMotionListener.
    And also, my problem is not the drag and drop functionality. The problem is only the scrolling.

  • What is an 'appropriate state' in DnD

    When I use dnd, I get the exception
    java.awt.dnd.InvalidDnDOperationException: The operation requested cannot be performed by the DnD system since it is not in the appropriate state
         at sun.awt.motif.MDragSourceContextPeer.startDrag(MDragSourceContextPeer.java:72)
         at java.awt.dnd.DragSource.startDrag(DragSource.java:279)
         at java.awt.dnd.DragSource.startDrag(DragSource.java:372)
    ...A number of people have asked about this,but no one's posted an explanation.
    In particular, I'd like to know what an 'appropriate state' is for the DnD
    system. I haven't been able to find an explanation of this in the api or
    the tutorial website links.
    Despite this exception, my DnD code does (usually work).
    FYI my code is copied from the example on the DnD tutorial website. I'm running
    IBM's 1.3.1 JDK under Linux (although I don't think this matters; people have
    encountered this problem on other platforms).
    Thanks,
    bw

    One possibility that comes to mind is that the DropTargetDropEvent.dropComplete(boolean success) method was not called on the last drop.
    In my experience (Windows), failure to call this method at the end of a drop, regardless of success results in much worse problems than you are describing, but it does seem to fit the description of "appropriate state" i.e. you can't start a new drag before the last one has finished.
    Just a thought.

  • DnD + Applet + Mozilla doesn't work on Linux

    hello!
    I have a Java Applet which use DnD.
    When i run it in Internet Explorer it runs fine....
    But when i try it in Mozilla (Linux), the DnD refuse to work... :(
    Help anyone???

    more info:
    OS: RedHat LInux ver. 9.0
    WM: Gnome 2.2.0
    Mozilla: 1.7.2
    java version 1.4.1 blackdown-linux
    the exception we (sometimes) get when trying to drag is "InvalidDnDOperationException: Drag and Drop in progress" (once again, the same code works perfectly in windows).

  • How to disable DND on Cisco IP Phone 303

    Hi there!
    I want that none of the user to use DND?
    Can i do this from WEB-ADMINISTRATION page of IP PHone?
    let me know?
    Regards!

    Yes, DND activation can be disabled from phone's WWW UI.

  • IOS nice feature to have - allow notifications from specific apps even on DND

    When I sleep at night, I enable "Do Not Disturb".  DND has a nice feature that allows calls from specific persons to go thru even while in DND.  I'm hoping that Apple would extend this allow specific apps to notify me even on DND.  I have a "SmartThings" app, and this app notifies me when unwanted movement, or when my doors/windows are opened by "intruders".  I would want SmartThings to notify me, even when I'm in DND.
    Thanks.

    As long as the app is running, it should.
    I use DND on a schedule as well as a third party alarm app and my alarm still sounds every morning before DND is disabled.

  • Must click then click and drag for JTable Drag and Drop

    Hi All,
    I've been using Java 1.4 to drag and drop data between two tables in our application. Basically I need to drag the data from individual rows of the source table and insert it into one of the cells in the new table. This works absolutely fine and has made a huge improvement to this portion of our app. I've included example source code below that does a similar thing by transferring data from one table and inserting it into another (it's quite big and also not as well done as the example in our real app but unfortunately I can't send the source for that).
    The thing I've noticed though is that in order to start dragging data I need to click to select it and then press and hold the mouse button to start dragging, whereas under W**dows and just about every other OS you can just press and hold and start dragging straight away. If you try this with a JTable though it just changes the rows you have selected so the drag and drop works but feels a bit clunky and amateurish. I'd like to do something about this such that it works like Windows Explorer (or similar) where you can just press the mouse button and start dragging.
    Any help would be greatly appreciated - and if anybody finds the code useful you're more than welcome to it. Note that the business end of this is CustomTransferHandler.java - this will show you how to insert data at a specific position in a JTable, it's a bit of a faff but not too bad once you've got it sussed.
    Thanks,
    Bart Read
    ===============================================================
    TestFrame.java
    * TestFrame.java
    * Created on October 21, 2002, 4:59 PM
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.event.*;
    import java.util.TooManyListenersException;
    import javax.swing.*;
    * @author  readb
    public class TestFrame extends javax.swing.JFrame
         private static final String [] NAMES     = {
              "John", "Geoff", "Madeleine", "Maria", "Flanders",
              "Homer", "Marge", "Bart", "Lisa", "Weird Baby" };
         private JTable source;
         private JTable dest;
         private MyTableModel     sourceModel;
         private MyTableModel     destModel;
         private Clipboard          clipboard;
         /** Creates a new instance of TestFrame */
         public TestFrame()
              clipboard = getToolkit().getSystemClipboard();
              Container c = getContentPane();
              c.setLayout( new BorderLayout( 40, 40 ) );
              source = new MyJTable();
              sourceModel = new MyTableModel();
              source.setModel( sourceModel );
              source.setDragEnabled( true );
              CustomTransferHandler handler = new CustomTransferHandler( "Source handler" );
              source.setTransferHandler( handler );
              try
                   source.getDropTarget().addDropTargetListener( handler );
              catch ( TooManyListenersException tmle )
                   tmle.printStackTrace();
              dest = new MyJTable();
              destModel = new MyTableModel();
              dest.setModel( destModel );
              dest.setDragEnabled( true );
              handler = new CustomTransferHandler( "Dest handler" );
              dest.setTransferHandler( handler );
              try
                   dest.getDropTarget().addDropTargetListener( handler );
              catch ( TooManyListenersException tmle )
                   tmle.printStackTrace();
              c.add( new JScrollPane( source ), BorderLayout.WEST );
              c.add( new JScrollPane( dest ), BorderLayout.EAST );
              populate();
         private void populate( MyTableModel model )
              for ( int index = 0; index < NAMES.length; ++index )
                   model.setRow( index, new DataRow( index + 1, NAMES[ index ] ) );
         private void populate()
              populate( sourceModel );
              populate( destModel );
         public static void main( String [] args )
              TestFrame app = new TestFrame();
              app.addWindowListener(
                   new WindowAdapter() {
                        public void windowClosing( WindowEvent we )
                             System.exit( 0 );
              app.pack();
              app.setSize( 1000, 600 );
              app.show();
         private class MyJTable extends JTable
              public boolean getScrollableTracksViewportHeight()
                   Component parent = getParent();
                   if (parent instanceof JViewport)
                        return parent.getHeight() > getPreferredSize().height;
                   return false;
    }=====================================================================
    MyTableModel.java
    * MyTableModel.java
    * Created on October 21, 2002, 4:43 PM
    import java.util.ArrayList;
    * @author  readb
    public class MyTableModel extends javax.swing.table.AbstractTableModel
         private static final int          NUMBER               = 0;
         private static final int          NAME               = 1;
         private static final String []     COLUMN_HEADINGS     = { "Number", "Name" };
         private ArrayList data;
         /** Creates a new instance of MyTableModel */
         public MyTableModel()
              super();
              data = new ArrayList();
         public int getColumnCount()
              return COLUMN_HEADINGS.length;
         public String getColumnName( int index )
              return COLUMN_HEADINGS[ index ];
         public Class getColumnClass( int index )
              switch ( index )
                   case NUMBER:
                        return Integer.class;
                   case NAME:
                        return String.class;
                   default:
                        throw new IllegalArgumentException( "Illegal column index: " + index );
         public int getRowCount()
              return ( null == data ? 0 : data.size() );
         public Object getValueAt( int row, int column )
              DataRow dataRow = ( DataRow ) data.get( row );
              switch ( column )
                   case NUMBER:
                        return new Integer( dataRow.getNumber() );
                   case NAME:
                        return dataRow.getName();
                   default:
                        throw new IllegalArgumentException( "Illegal column index: " + column );
         public void addRow( DataRow row )
              int rowIndex = data.size();
              data.add( row );
              fireTableRowsInserted( rowIndex, rowIndex );
         public void addRows( DataRow [] rows )
              int firstRow = data.size();
              for ( int index = 0; index < rows.length; ++index )
                   data.add( rows[ index ] );
              fireTableRowsInserted( firstRow, data.size() - 1 );
         public void setRow( int index, DataRow row )
              if ( index == data.size() )
                   data.add( row );
              else
                   data.set( index, row );
              fireTableRowsUpdated( index, index );
         public void insertRows( int index, DataRow [] rows )
              for ( int rowIndex = rows.length - 1; rowIndex >= 0; --rowIndex )
                   data.add( index, rows[ rowIndex ] );
              fireTableRowsInserted( index, index + rows.length - 1 );
         public DataRow getRow( int index )
              return ( DataRow ) data.get( index );
         public DataRow removeRow( int index )
              DataRow retVal = ( DataRow ) data.remove( index );
              fireTableRowsDeleted( index, index );
              return retVal;
         public boolean removeRow( DataRow row )
              int index = data.indexOf( row );
              boolean retVal = data.remove( row );
              fireTableRowsDeleted( index, index );
              return retVal;
         public void removeRows( DataRow [] rows )
              for ( int index = 0; index < rows.length; ++index )
                   data.remove( rows[ index ] );
              fireTableDataChanged();
    }=====================================================================
    DataRow.java
    * DataRow.java
    * Created on October 21, 2002, 4:41 PM
    import java.io.Serializable;
    * @author  readb
    public class DataRow implements Serializable
         private int          number;
         private String     name;
         /** Creates a new instance of DataRow */
         public DataRow( int number, String name )
              this.number = number;
              this.name = name;
         public int getNumber()
              return number;
         public String getName()
              return name;
         public String toString()
              return String.valueOf( number ) + ": " + name;
    }======================================================================
    CustomTransferHandler.java
    * CustomTransferHandler.java
    * Created on October 22, 2002, 8:36 AM
    import java.awt.*;
    import java.awt.datatransfer.Clipboard;
    import java.awt.datatransfer.ClipboardOwner;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.dnd.*;
    import java.awt.event.InputEvent;
    import java.io.IOException;
    import java.util.Arrays;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
    import javax.swing.JTable;
    import javax.swing.TransferHandler;
    * @author  readb
    public class CustomTransferHandler
                   extends TransferHandler
                   implements Transferable, ClipboardOwner, DropTargetListener
         public static final DataFlavor     ROW_ARRAY_FLAVOR     = new DataFlavor( DataRow[].class, "Multiple rows of data" );
         private String               name;
         private ImageIcon          myIcon;
         private     DataRow []          data;
         private boolean               clipboardOwner                    = false;
         private int                    rowIndex                         = -1;
         /** Creates a new instance of CustomTransferHandler */
         public CustomTransferHandler( String name )
              this.name = name;
         public boolean canImport( JComponent comp, DataFlavor [] transferFlavors )
              System.err.println( "CustomTransferHandler::canImport" );
              if ( comp instanceof JTable && ( ( JTable ) comp ).getModel() instanceof MyTableModel )
                   for ( int index = 0; index < transferFlavors.length; ++index )
                        if ( ! transferFlavors[ index ].equals( ROW_ARRAY_FLAVOR ) )
                             return false;
                   return true;
              else
                   return false;
         protected Transferable createTransferable( JComponent c )
              System.err.println( "CustomTransferHandler::createTransferable" );
              if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
                   return null;
              this.data = null;
              JTable               table     = ( JTable ) c;
              MyTableModel     model     = ( MyTableModel ) table.getModel();
              Clipboard          cb          = table.getToolkit().getSystemClipboard();
              cb.setContents( this, this );
              clipboardOwner = true;
              int [] selectedRows = table.getSelectedRows();
              Arrays.sort( selectedRows );
              data = new DataRow[ selectedRows.length ];
              for ( int index = 0; index < data.length; ++index )
                   data[ index ] = model.getRow( selectedRows[ index ] );
              return this;
         public void exportAsDrag( JComponent comp, InputEvent e, int action )
              super.exportAsDrag( comp, e, action );
              Clipboard          cb          = comp.getToolkit().getSystemClipboard();
              cb.setContents( this, this );
         protected void exportDone( JComponent source, Transferable data, int action )
              System.err.println( "CustomTransferHandler::exportDone" );
              if ( TransferHandler.MOVE == action && source instanceof JTable && ( ( JTable ) source ).getModel() instanceof MyTableModel )
                   JTable table = ( JTable ) source;
                   MyTableModel model = ( MyTableModel ) table.getModel();
                   int [] selected = table.getSelectedRows();
                   for ( int index = selected.length - 1; index >= 0; --index )
                        model.removeRow( selected[ index ] );
         public void exportToClipboard( JComponent comp, Clipboard clip, int action )
              System.err.println( "CustomTransferHandler::exportToClipboard" );
         public int getSourceActions( JComponent c )
              System.err.println( "CustomTransferHandler::getSourceActions" );
              if ( ( c instanceof JTable ) && ( ( JTable ) c ).getModel() instanceof MyTableModel )
                   return MOVE;
              else
                   return NONE;
          *     I've commented this out because it doesn't appear to work in any case.
          *     The image isn't null but as far as I can tell this method is never
          *     invoked.
    //     public Icon getVisualRepresentation( Transferable t )
    //          System.err.println( "CustomTransferHandler::getVisualRepresentation" );
    //          if ( t instanceof CustomTransferHandler )
    //               if ( null == myIcon )
    //                    try
    //                         myIcon = new ImageIcon( getClass().getClassLoader().getResource( "dragimage.gif" ) );
    //                    catch ( Exception e )
    //                         System.err.println( "CustomTransferHandler::getVisualRepresentation: exception loading image" );
    //                         e.printStackTrace();
    //                    if ( null == myIcon )
    //                         System.err.println( "CustomTransferHandler::getVisualRepresentation: myIcon is still NULL" );
    //               return myIcon;
    //          else
    //               return null;
         public boolean importData( JComponent comp, Transferable t )
              System.err.println( "CustomTransferHandler::importData" );
              super.importData( comp, t );
              if ( ! ( comp instanceof JTable ) )
                   return false;
              if ( ! ( ( ( JTable ) comp ).getModel() instanceof MyTableModel ) )
                   return false;
              if ( clipboardOwner )
                   return false;
              if ( !t.isDataFlavorSupported( ROW_ARRAY_FLAVOR ) )
                   return false;
              try
                   data = ( DataRow [] ) t.getTransferData( ROW_ARRAY_FLAVOR );
                   return true;
              catch ( IOException ioe )
                   data = null;
                   return false;
              catch ( UnsupportedFlavorException ufe )
                   data = null;
                   return false;
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
              System.err.println( "MyTransferable::getTransferData" );
              if ( flavor.equals( ROW_ARRAY_FLAVOR ) )
                   return data;
              else
                   throw new UnsupportedFlavorException( flavor );
         public DataFlavor[] getTransferDataFlavors()
              System.err.println( "MyTransferable::getTransferDataFlavors" );
              DataFlavor [] flavors = new DataFlavor[ 1 ];
              flavors[ 0 ] = ROW_ARRAY_FLAVOR;
              return flavors;
         public boolean isDataFlavorSupported( DataFlavor flavor )
              System.err.println( "MyTransferable::isDataFlavorSupported" );
              return flavor.equals( ROW_ARRAY_FLAVOR );
         public void lostOwnership( Clipboard clipboard, Transferable transferable )
              clipboardOwner = false;
         /** Called while a drag operation is ongoing, when the mouse pointer enters
          * the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dragEnter(DropTargetDragEvent dtde)
         /** Called while a drag operation is ongoing, when the mouse pointer has
          * exited the operable part of the drop site for the
          * <code>DropTarget</code> registered with this listener.
          * @param dte the <code>DropTargetEvent</code>
         public void dragExit(DropTargetEvent dte)
         /** Called when a drag operation is ongoing, while the mouse pointer is still
          * over the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dragOver(DropTargetDragEvent dtde)
         /** Called when the drag operation has terminated with a drop on
          * the operable part of the drop site for the <code>DropTarget</code>
          * registered with this listener.
          * <p>
          * This method is responsible for undertaking
          * the transfer of the data associated with the
          * gesture. The <code>DropTargetDropEvent</code>
          * provides a means to obtain a <code>Transferable</code>
          * object that represents the data object(s) to
          * be transfered.<P>
          * From this method, the <code>DropTargetListener</code>
          * shall accept or reject the drop via the
          * acceptDrop(int dropAction) or rejectDrop() methods of the
          * <code>DropTargetDropEvent</code> parameter.
          * <P>
          * Subsequent to acceptDrop(), but not before,
          * <code>DropTargetDropEvent</code>'s getTransferable()
          * method may be invoked, and data transfer may be
          * performed via the returned <code>Transferable</code>'s
          * getTransferData() method.
          * <P>
          * At the completion of a drop, an implementation
          * of this method is required to signal the success/failure
          * of the drop by passing an appropriate
          * <code>boolean</code> to the <code>DropTargetDropEvent</code>'s
          * dropComplete(boolean success) method.
          * <P>
          * Note: The data transfer should be completed before the call  to the
          * <code>DropTargetDropEvent</code>'s dropComplete(boolean success) method.
          * After that, a call to the getTransferData() method of the
          * <code>Transferable</code> returned by
          * <code>DropTargetDropEvent.getTransferable()</code> is guaranteed to
          * succeed only if the data transfer is local; that is, only if
          * <code>DropTargetDropEvent.isLocalTransfer()</code> returns
          * <code>true</code>. Otherwise, the behavior of the call is
          * implementation-dependent.
          * <P>
          * @param dtde the <code>DropTargetDropEvent</code>
         public void drop(DropTargetDropEvent dtde)
              System.err.println( "CustomTransferHandler::drop" );
              Component c = dtde.getDropTargetContext().getDropTarget().getComponent();
              if ( ! ( c instanceof JComponent ) )
                   dtde.rejectDrop();
                   return;
              JComponent comp = ( JComponent ) c;
              if ( ! ( c instanceof JTable ) || ! ( ( ( JTable ) c ).getModel() instanceof MyTableModel ) )
                   dtde.rejectDrop();
                   return;
              dtde.acceptDrop( TransferHandler.MOVE );
              //     THIS is such a mess -- you can't do the following because
              //     getTransferable() throws an (undocumented) exception - what's that
              //     all about.
    //          Transferable t = dtde.getTransferable();
    //               if ( !t.isDataFlavourSupported( ROW_ARRAY_FLAVOR ) )
    //                    dtde.rejectDrop();
    //                    return false;
    //          TransferHandler handler = comp.getTransferHandler();
    //          if ( null == handler || ! handler.importData( comp, t ) )
    //               dtde.rejectDrop();
    //               return;
              Point p = dtde.getLocation();
              JTable table = ( JTable ) comp;
              rowIndex = table.rowAtPoint( p );
              //     So you have to do this instead and use the data that's been
              //     stored in the data member via import data.  Total mess.
              if ( null == data )
                   dtde.rejectDrop();
                   return;
              MyTableModel model = ( MyTableModel ) table.getModel();
              if ( rowIndex == -1 )
                   model.addRows( data );
              else
                   model.insertRows( rowIndex, data );
              dtde.acceptDrop( TransferHandler.MOVE );
         /** Called if the user has modified
          * the current drop gesture.
          * <P>
          * @param dtde the <code>DropTargetDragEvent</code>
         public void dropActionChanged(DropTargetDragEvent dtde)
    }

    Hi again,
    Well I've tried using the MouseListener / MouseMotionListener approach but it doesn't quite seem to work, although it does get the events correctly. I think the reason is that it doesn't interact correctly with the Java DnD machinery which is something that V.V hinted at. It's something that I may need to look into if / when I have more time available.
    I have to say though that I haven't had any problems with scrollbars - we're making fairly heavy use of large tables and if you drag over a table with a scroll bar and move to the top or bottom then it scrolls as you would expect and allows you to drop the data where you like. For this situation I've used pretty much the same approach as for the toy example above except that I've implemented separate source and destination TransferHandlers (the source table is read-only, and it really doesn't make sense to allow people to drag from the destination table so I've essentially split the functionality of the example handler down the middle).
    I'm not actually particularly in favour of messing too much with the mechanics of DnD, more because of lack of time than anything else. Guess I'll just have to put up with this for the moment. Doesn't help that DnD is so poorly documented by Sun.
    Thanks for all your help.
    Bart

  • New JNDI name created for each drag and drop of database table into table

    Hi All,
    I'm using Netbeans 5.5 with Visual Web Pack with Mysql as backend. Whenever I drag and drop a database table into table component it creates new JNDI (data source) name for each table. I want to use single JNDI name for all tables. If I change the JNDI name to default name then the design disappears and shows error . Is there any option to set the JNDI name unique for all tables?
    Thanks in advance.

    Hi again,
    Well I've tried using the MouseListener / MouseMotionListener approach but it doesn't quite seem to work, although it does get the events correctly. I think the reason is that it doesn't interact correctly with the Java DnD machinery which is something that V.V hinted at. It's something that I may need to look into if / when I have more time available.
    I have to say though that I haven't had any problems with scrollbars - we're making fairly heavy use of large tables and if you drag over a table with a scroll bar and move to the top or bottom then it scrolls as you would expect and allows you to drop the data where you like. For this situation I've used pretty much the same approach as for the toy example above except that I've implemented separate source and destination TransferHandlers (the source table is read-only, and it really doesn't make sense to allow people to drag from the destination table so I've essentially split the functionality of the example handler down the middle).
    I'm not actually particularly in favour of messing too much with the mechanics of DnD, more because of lack of time than anything else. Guess I'll just have to put up with this for the moment. Doesn't help that DnD is so poorly documented by Sun.
    Thanks for all your help.
    Bart

  • How to reach a method of an object from within another class

    I am stuck in a situation with my program. The current situation is as follows:
    1- There is a class in which I draw images. This class is an extension of JPanel
    2- And there is a main class (the one that has main method) which is an extension of JFrame
    3- In the main class a create an instance(object) of StatusBar class and add it to the main class
    4- I also add to the main class an instance of image drawing class I mentioned in item 1 above.
    5- In the image drawing class i define mousemove method and as the mouse
    moves over the image, i want to display some info on the status bar
    6- How can do it?
    7- Thanks!

    It would make sense that the panel not be forced to understand its context (in this case a JFrame, but perhaps an applet or something else later on) but offer a means of tracking.
    class DrawingPanel extends JPanel {
      HashSet listeners = new HashSet();
      public void addDrawingListener(DrawingListener l) {
         listeners.add(l);
      protected void fireMouseMove(MouseEvent me) {
         Iterator i = listeners.iterator();
         while (i.hasNext()) {
            ((DrawingListener) i.next()).mouseMoved(me.getX(),me.getY());
    class Main implements DrawingListener {
      JFrame frame;
      JLabel status;
      DrawingPanel panel;
      private void init() {
         panel.addDrawingListener(this);
      public void mouseMoved(int x,int y) {
         status.setText("x : " + x + " y: " + y);
    public interface DrawingListener {
      void mouseMoved(int x,int y);
    }Of course you could always just have the Main class add a MouseMotionListener to the DrawingPanel, but if the DrawingPanel has a scale or gets embedded in a scroll pane and there is some virtual coordinate transformation (not using screen coordinates) then the Main class would have to know about how to do the transformation. This way, the DrawingPanel can encapsulate that knowledge and the Main class simply provides a means to listen to the DrawingPanel. By using a DrawingListener, you could add other methods as well (versus using only a MouseMotionListener).
    Obviously, lots of code is missing above. In general, its not a good idea to extend JFrame unless you really are changing the JFrames behavior by overrding methods, etc. Extending JPanel is okay, as you are presumably modifiying the drawing code, but you'd be better off extending JComponent.

  • URGENT! Need help with scrolling on a JPanel!

    Hello Guys! I guess there has been many postings about this subject in the forum, but the postings I found there.... still couldn't solve my problem...
    So, straight to the problem:
    I am drawing some primitive graphic on a JPanel. This JPanel is then placed in a JScrollPane. When running the code, the scrollbars are showing and the graphic is painted nicely. But when I try to scroll to see the parts of the graphics not visible in the current scrollbarview, nothing else than some flickering is happening... No movement what so ever...
    What on earth must I do to activate the scroll functionality on my JPanel??? Please Help!
    And yes, I have tried implementing the 'Scrollable' interface... But it did not make any difference...
    Code snippets:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class FilterComp extends JPanel {//implements Scrollable {
      protected DefaultMutableTreeNode root;
      protected Image buffer;
      protected int lastW = 0;
      protected int origoX = 0;
      protected final StringBuffer sb = new StringBuffer();
    //  protected int maxUnitIncrement = 1;
      protected JScrollPane scrollpane = new JScrollPane();
       *  Constructor for the FilterComp object
       *@param  scrollpane  Description of the Parameter
      public FilterComp(JScrollPane scrollpane) {
        super();
    //    setPreferredSize(new Dimension(1000, 500));
        this.setBackground(Color.magenta);
    //    setOpaque(false);
        setLayout(
          new BorderLayout() {
            public Dimension preferredLayoutSize(Container cont) {
              return new Dimension(1000, 600);
        this.scrollpane = scrollpane;
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollpane.setPreferredSize( new Dimension( 500, 500 ) );
        scrollpane.getViewport().add( this, null );
    //    scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        repaint();
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = getSize().width;
        if (w != lastW) {
          buffer = null;
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (root != null) {
          int h = getHeight(root);
          if (buffer == null) {
            buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g3 = (Graphics2D) buffer.getGraphics();
            g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g3.setColor(Color.black);
            g3.setStroke(new BasicStroke(2));
            paint(g3, (w / 2) + origoX, 10, w / 2, root); 
          lastW = w;
          AffineTransform old = g2.getTransform();
          AffineTransform trans = new AffineTransform();
          trans.translate((w / 2) + origoX, (getHeight() - (h * 40)) / 2);
          g2.setTransform(trans);
          g2.drawImage(buffer, (-w / 2) + origoX, 0, null);
          g2.setTransform(old);
        updateUI();
       *  Description of the Method
       *@param  g  Description of the Parameter
      public void update(Graphics g) {
        // Call paint to reduce flickering
        paint(g);
       *  Description of the Method
       *@param  g2    Description of the Parameter
       *@param  x     Description of the Parameter
       *@param  y     Description of the Parameter
       *@param  w     Description of the Parameter
       *@param  node  Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, int w, DefaultMutableTreeNode node) {
        if (node.getChildCount() == 2) {
          DefaultMutableTreeNode c1 = (DefaultMutableTreeNode) node.getChildAt(0);
          DefaultMutableTreeNode c2 = (DefaultMutableTreeNode) node.getChildAt(1);
          if (c1.getChildCount() == 0 && c2.getChildCount() == 0) {
            String s = c1.getUserObject().toString() + " " + node.getUserObject() + " " + c2.getUserObject();
            paint(g2, x, y, s);
          } else {
            g2.drawLine(x - (w / 2), y, x + (w / 2), y);
            Font f = g2.getFont();
            g2.setFont(new Font(f.getName(), Font.BOLD | Font.ITALIC, f.getSize() + 2));
            paint(g2, x, y, node.getUserObject().toString());
            g2.setFont(f);
            g2.drawLine(x - (w / 2), y, x - (w / 2), y + 40);
            g2.drawLine(x + (w / 2), y, x + (w / 2), y + 40);
            paint(g2, x - (w / 2), y + 40, w / 2, c1);
            paint(g2, x + (w / 2), y + 40, w / 2, c2);
        } else if (node.getChildCount() == 0) {
          paint(g2, x, y, node.getUserObject().toString());
       *  Description of the Method
       *@param  g2  Description of the Parameter
       *@param  x   Description of the Parameter
       *@param  y   Description of the Parameter
       *@param  s   Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, String s) {
        y += 10;
        StringTokenizer st = new StringTokenizer(s, "\\", false);
        if (s.indexOf("'") != -1 && st.countTokens() > 1) {
          int sh = g2.getFontMetrics().getHeight();
          while (st.hasMoreTokens()) {
            String t = st.nextToken();
            if (st.hasMoreTokens()) {
              t += "/";
            int sw = g2.getFontMetrics().stringWidth(t);
            g2.drawString(t, x - (sw / 2), y);
            y += sh;
        } else {
          int sw = g2.getFontMetrics().stringWidth(s);
          g2.drawString(s, x - (sw / 2), y);
       *  Sets the root attribute of the FilterComp object
       *@param  root  The new root value
      public void setRoot(DefaultMutableTreeNode root) {
        this.root = root;
        buffer = null;
       *  Gets the root attribute of the FilterComp object
       *@return    The root value
      public DefaultMutableTreeNode getRoot() {
        return root;
       *  Gets the height attribute of the FilterComp object
       *@param  t  Description of the Parameter
       *@return    The height value
      private int getHeight(TreeNode t) {
        int h = 1;
        int c = t.getChildCount();
        if (c > 0) {
          if (c > 1) {
            h += Math.max(getHeight(t.getChildAt(0)), getHeight(t.getChildAt(1)));
          } else {
            h += getHeight(t.getChildAt(0));
        return h;
       *  Sets the x attribute of the FilterComp object
       *@param  x  The new x value
      public void setX(int x) {
        origoX = x;
       *  Gets the x attribute of the FilterComp object
       *@return    The x value
      public int getX() {
        return origoX;
       *  Gets the preferredScrollableViewportSize attribute of the FilterComp
       *  object
       *@return    The preferredScrollableViewportSize value
    //  public Dimension getPreferredScrollableViewportSize() {
    //    return getPreferredSize();
       *  Gets the scrollableBlockIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableBlockIncrement value
    //  public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
       *  Gets the scrollableTracksViewportHeight attribute of the FilterComp object
       *@return    The scrollableTracksViewportHeight value
    //  public boolean getScrollableTracksViewportHeight() {
    //    return false;
       *  Gets the scrollableTracksViewportWidth attribute of the FilterComp object
       *@return    The scrollableTracksViewportWidth value
    //  public boolean getScrollableTracksViewportWidth() {
    //    return false;
       *  Gets the scrollableUnitIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableUnitIncrement value
    //  public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
    }

    The Scrollable interface should be implemented by a JPanel set as the JScrollPane's viewport or scrolling may not function. Although it is said to be only necessary for tables, lists, and trees, without it I have never had success with images. Even the Java Swing Tutorial on scrolling images with JScrollPane uses the Scrollable interface.
    I donot know what you are doing wrong here, but I use JScrollPane with a JPanel implementing Scrollable interface and it works very well scrolling images drawn into the JPanel.
    You can scroll using other components, such as the JScrollBar or even by using a MouseListener/MouseMotionListener combination, but this is all done behind the scenes with the use of JScrollPane/Scrollable combination.
    You could try this approach using an ImageIcon within a JLabel:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test extends JFrame {
         BufferedImage bi;
         Graphics2D g_bi;
         public Test() {
              super("Scroll Test");
              makeImage();
              Container contentPane = getContentPane();
              MyView view = new MyView(new ImageIcon(bi));
              JScrollPane sp = new JScrollPane(view);
              contentPane.add(sp);
              setSize(200, 200);
              setVisible(true);
         private void makeImage() {
              bi = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
              g_bi = bi.createGraphics();
              g_bi.setColor(Color.white);
              g_bi.fillRect(0,0,320,240);
              g_bi.setColor(Color.black);
              g_bi.drawLine(0,0,320,240);
         public static void main(String args[]) {
              Test test = new Test();
    class MyView extends JLabel {
         ImageIcon icon;
         public MyView(ImageIcon ii) {
              super(ii);
              icon = ii;
         public void paintComponent(Graphics g) {
              g.drawImage(icon.getImage(),0,0,this);
    }Robert Templeton

  • Drag and Drop in JPanel having GridBagLayout

    Hi,
    I have a JPanel (longitudinal) which has labels with imageicons (actually they are created using javax.media package and other JAI packages, but for simplicity sake labels are good). These labels are arranged longitudinally one below the other.
    I have to implement drag and drop for these labels. I should be able to change the order etc. of the labels using DnD. I have been able to do that successfully. From the mouse coordinattes when the mouse is released, i calculated the grid on the layout, and then add the component to the panel in the grid.
    All is well, but it doesnt end well :-(
    The problem I am having is that when i releaase the mouse button, the component gets added on top of the component that is already there in that grid.
    Is there a way that they can adjust positions, and the other labels move one grid down when another one is added in the same grid??
    I would really appreciate any help. I did a lot of work to come to this level, and now i have just run out of ideas.
    Thanks a lot in advance!!
    Sri.

    Hi,
    I have a JPanel (longitudinal) which has labels with imageicons (actually they are created using javax.media package and other JAI packages, but for simplicity sake labels are good). These labels are arranged longitudinally one below the other.
    I have to implement drag and drop for these labels. I should be able to change the order etc. of the labels using DnD. I have been able to do that successfully. From the mouse coordinattes when the mouse is released, i calculated the grid on the layout, and then add the component to the panel in the grid.
    All is well, but it doesnt end well :-(
    The problem I am having is that when i releaase the mouse button, the component gets added on top of the component that is already there in that grid.
    Is there a way that they can adjust positions, and the other labels move one grid down when another one is added in the same grid??
    I would really appreciate any help. I did a lot of work to come to this level, and now i have just run out of ideas.
    Thanks a lot in advance!!
    Sri.

Maybe you are looking for

  • How to output new /new other than new/

    I use dom to parse a document to xml String.if a xml node doesn't have node value ,it will output <new/> but not <new></new>.we use this format (<new></new>) to transfer with remote mechine,so how to output this format. following is my sample code:  

  • How to open a standby database for use?

    First, let me state that I am not a DBA nor am I a systems guy; I'm a software developer. At work, we recently built a new virtualized db server by cloning our disaster recovery (DR) database server. The DR database was kept in 'standby' mode (I thin

  • Extended classic to Classic

    Hi, When would a switch from ECS to Classic be justifiable? Thanks.

  • Is partial replication possible?

    Would i have the control to replicate some records but not all? While inserting a new record could I decide if the record was replication worthy and then either keep it local or replicate it? Would I be able to replicate to a subset of the network si

  • NSAffineTransform and rotating images (Not iPhone)

    I have a subclass of NSView, and in that I'm viewing an NSImage. I have a rotate button that causes the drawRectangle method to create an NSAffineTransform that should rotate the image. I'm also drawing the image locked to the upper left corner, by d