(MouseMotionListener) mouseDragged question.

I'm implementing an mp3 player. It has multiple jframes displaying things like the playlist, button window, etc. (not unlike WinAMP). I decided that normal windows title bars are huge and ugly, so I decided to set the playlist window to setUndecorated(true);. There's no inherent way to drag this around the screen. So, I decided to stick a JLabel at top and then to move the window around whenever that JLabel calls its MouseMotionListener's mouseDragged() method. Seems fairly simple.
However, it would appear that when I move the window around in order to respond to the mouse dragging, the moving the window itself calls the mouseDragged method, causing the window to jump around the screen as I drag it. I can't seem to keep track of it to "filter" these events out in order to stop this. What should I do?

Check out this posting for an example of dragging a window:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=599181

Similar Messages

  • 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.

  • People, why you won't HELP???

    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 connect action of MouseMotionListener with DnD.
    Here is a part of 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!
    Even if you will not help on subject, answer my question, please - People, why you wan't HELP???.
    DM.

    sorry it is DropTargetDropEvent...
    why dont you get the drop point from DropTargetDropEvent passed through dnd..
    like in drop(DropTargetDropEvent dte)
    add(new DraggablePanel()).setLocation(e.getX(),e.getY());
    }

  • JTable custom selection and mouse drag events

    Hello
    I am currently experiencing a problem when using a JTable and a custom selection. I have made a small example to demonstrate the probem. Selection works for this example by listening for when the user clicks or clicks and drags (button held down) and moves the mouse across cells in the table. For each MouseEvent received in the MouseMotionListener mouseDragged method I store the coordinates of that cell at the point of the mouse and render the cell at those coordinates with a line border allowing a more versatile cell selection. The problem that occurs is when you click+drag and move the mouse fast, it looks MouseEvents are created every x milliseconds so when you move fast there isn't a MouseEvent raised for each cell in the click+drag from A -> B. If you run the following example then click and hold down the mouse button and move fast downwards from the top of the table to the bottom you can see that not all the cells are selected vertically.
    Is there someway of increasing the mouse poll (if this is indeed the problem) during the click+drag or a better solution to this problem that any one knows!?
    I have tried attaching the example but it exceeded the message length for the forum post here is a link to code
    [http://www.oneandonlyluppy.pwp.blueyonder.co.uk/TableTest.java]
    [http://www.oneandonlyluppy.pwp.blueyonder.co.uk/TableTest.zip] <-- Contains the source and compiled classes
    I'll try adding the code again as a separate post
    Thanks
    Edited by: oneandonlyluppy on Jan 8, 2009 2:44 AM
    Edited by: oneandonlyluppy on Jan 8, 2009 2:45 AM

    AFAIK the mouse polling rate is OS dependent (being interrupt driven), and may even be affected by processor load. What you could do is store the mouse location (Point) of the last mouseDragged event, and compute a line to the current location, then use some coordinate geometry to identify any intervening cells which are presently being skipped.
    db

  • Generalized Component Resizing

    Hey people,
    I wrote a "Component Resizer" which takes care of resizing components. Any component as opposed to just a window or a dialog.
    One problem I noticed while resizing dialogs for example was that when I resize the dialog, the internal panes do not get adjust themselves to the new contained size. Now this happens even if I am using say GridBagLayout or GridLayout.
    Another problem I noticed is that then a component inside a container is resized, the new size is retained until the parent container for this component itself is resized. Then it goes back to its original size. I guess this is because of the layout manager but then, this happens even when I use null layout. I have posted the code here (it's really long).
    Any suggestions?
    thanx,
    -vijai.
    Main resize handler:
    * Copyright (c) 2004,
    * Vijayaraghavan Kalyanapasupathy
    * [email protected]
    * See accompanying project license for license terms and agreement.
    * The use of the intellectual property contained herein is subject
    * to the terms of the license agreement. If no license agreement
    * can be found at the locations from where you obtained this
    * sofwtare/file/code fragment contact the author for the license.
    * Contributors: Vijayaraghavan Kalyanapasupathy
    * Created     : 4:03:42 AM, Dec 2, 2004
    * Project     : SwingComponents
    package org.swingcomponents.components;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.JComponent;
    import org.apache.log4j.Logger;
    /**<p>
    * A configurable listener which can resize any component that can generate mouse drag and mouse events.
    * </p>
    * <p>
    * General model for this is that <br/>
    * <ul>
    *  <li> On demand resizing region margin
    *  <li> On demand resizing directions modification
    * </ul>
    * </p>
    * @author Vijayaraghavan Kalyanapasupathy
    public class ComponentResizer extends    MouseAdapter
                                  implements MouseListener,
                                             MouseMotionListener {
         static final int DEFAULT_MARGIN = 8;
          * The sensitivity on the left side within which a mouse drag is interpreted as a resize action.
         static int c_leftmargin   = DEFAULT_MARGIN;
          * The sensitivity on the right side within which a mouse drag is interpreted as a resize action.
         static int c_rightmargin  = DEFAULT_MARGIN;
          * The sensitivity on the top within which a mouse drag is interpreted as a resize action.
         static int c_topmargin    = DEFAULT_MARGIN;
          * The sensitivity on the bottom within which a mouse drag is interpreted as a resize action.
         static int c_bottommargin = DEFAULT_MARGIN;
          * Sets the default margins for all newly generated resizers.
          * @param p_top The new top margin
          * @param p_left The new left side margin
          * @param p_bottom The new bottom margin
          * @param p_right The new right side margin
         public static void setDefaultMargins(int p_top,int p_left,int p_bottom,int p_right) {
              c_logger.debug("Attempting to change application wide margins to: ("+p_top+","+p_left+","+p_bottom+","+p_right+")");
              c_leftmargin   = p_left > 0 ? p_left : c_leftmargin;
              c_rightmargin  = p_right > 0 ? p_right : c_rightmargin;
              c_topmargin    = p_top > 0 ? p_top : c_topmargin;
              c_bottommargin = p_bottom > 0 ? p_bottom : c_bottommargin;
              c_logger.debug("Changed application wide margins to: ("+c_topmargin+","+c_leftmargin+","+c_bottommargin+","+c_rightmargin+")");
          * Retrieves the default application wide left margin used for newly created resizers.
          * @return The default left margin
         public static int getDefaultLeftMargin() {
              return c_leftmargin;
          * Retrieves the default application wide top margin used for newly created resizers.
          * @return The default top margin
         public static int getDefaultTopMargin() {
              return c_topmargin;
          * Retrieves the default application wide right margin used for newly created resizers.
          * @return The default right margin
         public static int getDefaultRightMargin() {
              return c_rightmargin;
          * Retrieves the default application wide bottom margin used for newly created resizers.
          * @return The default bottom margin
         public static int getDefaultBottomMargin() {
              return c_bottommargin;     
          * The standard log4j logger that all instances of this class use
          * to log messages.
         static Logger c_logger = Logger.getLogger(ComponentResizer.class);
         /* The cursors for each direction */
         /** The top resize cursor */
         static final Cursor c_topcursor         = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
         /** The left side resize cursor */
         static final Cursor c_leftcursor        = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
         /** The right side resize cursor */
         static final Cursor c_rightcursor       = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
         /** The bottom resize cursor */
         static final Cursor c_bottomcursor      = Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR);
         /** The topleft resize cursor */
         static final Cursor c_topleftcursor     = Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR);
         /** The topright resize cursor */
         static final Cursor c_toprightcursor    = Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR);
         /** The bottomleft resize cursor */
         static final Cursor c_bottomleftcursor  = Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR);
         /** The bottomright resize cursor */
         static final Cursor c_bottomrightcursor = Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR);
          * Method that performs initialization stuff.
         protected void InitializeResizer() {
              c_logger.debug("Initializing resizer: ");
              m_leftmargin   = c_leftmargin;
              m_rightmargin  = c_rightmargin;
              m_bottommargin = c_bottommargin;
              m_topmargin    = c_topmargin;
              c_logger.debug("Initialized default margins from application wide settings: ("+m_topmargin+","+m_leftmargin+","+m_bottommargin+","+m_rightmargin+")");
              c_logger.debug("Setting default resize options: ");
              m_allowTopLeftResize    = m_allowTopRightResize    = true;
              m_allowBottomLeftResize = m_allowBottomRightResize = true;
              m_allowLeftResize       = m_allowRightResize       = true;
              m_allowTopResize        = m_allowBottomResize      = true;
              c_logger.debug("Getting component default cursor: ");
              m_componentcursor = m_component.getCursor();
         /** The resizer specific left side margin */
         int m_leftmargin;
         /** The resizer specific top margin */
         int m_topmargin;
         /** The resizer specific right side margin */
         int m_rightmargin;
         /** The resizer specific bottom margin */
         int m_bottommargin;
         /** Indicates that top side resizing should be allowed. */
         boolean m_allowTopResize;
         /** Indicates that bottom side resizing should be allowed. */
         boolean m_allowBottomResize;
         /** Indicates that left side resizing should be allowed. */
         boolean m_allowLeftResize;
         /** Indicates that right side resizing should be allowed. */
         boolean m_allowRightResize;
         /** Indicates that top left resizing should be allowed. */
         boolean m_allowTopLeftResize;
         /** Indicates that top right resizing should be allowed. */
         boolean m_allowTopRightResize;
         /** Indicates that bottom left resizing should be allowed. */
         boolean m_allowBottomLeftResize;
         /** Indicates that bottom right resizing should be allowed. */
         boolean m_allowBottomRightResize;
         /** The component that we are focussing on */
         Component m_component = null;
         /** The layout key for the component */
         String m_layoutkey = null;
          * Creates a new component resizer that attaches itself as a mouse listener and
          * as a mouse motion listener to the given component.
          * @param p_component The component to attach the listener to.
          * @param p_layoutkey The key used in the layout manager of the component's parent for this object.
         public ComponentResizer(Component p_component,String p_layoutkey) {
              super();
              m_component = p_component;
              m_layoutkey = p_layoutkey;
              if(m_component != null) {
                   c_logger.debug("Initializing resizer for: "+m_component);
                   InitializeResizer();
                   m_component.getToolkit().setDynamicLayout(true);
                   m_component.addMouseListener(this);
                   m_component.addMouseMotionListener(this);
              }else {
                   c_logger.warn("Component is null: ");
          * Sets the resizer specific bottom margin.
          * @param p_bottommargin The bottommargin to set.
         public void setBottomMargin(int p_bottommargin) {
              c_logger.debug("Attempting to set top margin to: "+p_bottommargin);
              m_bottommargin = p_bottommargin > 0 ? p_bottommargin : m_bottommargin;
              c_logger.debug("Bottom margin set to: "+m_bottommargin);
          * Sets the resizer specific left side margin.
          * @param p_leftmargin The leftmargin to set.
         public void setLeftMargin(int p_leftmargin) {
              c_logger.debug("Attempting to set left margin to: "+p_leftmargin);
              m_leftmargin = p_leftmargin > 0 ? p_leftmargin : m_leftmargin;
              c_logger.debug("Left margin set to: "+m_leftmargin);
          * Sets the resizer specific right side margin.
          * @param p_rightmargin The rightmargin to set.
         public void setRightMargin(int p_rightmargin) {
              c_logger.debug("Attempting to set right margin to: "+p_rightmargin);
              m_rightmargin = p_rightmargin > 0 ? p_rightmargin : m_rightmargin;
              c_logger.debug("Right margin set to: "+m_rightmargin);
          * Sets the resizer specific top margin.
          * @param p_topmargin The topmargin to set.
         public void setTopMargin(int p_topmargin) {
              c_logger.debug("Attempting to set top margin to: "+p_topmargin);
              m_topmargin = p_topmargin > 0 ? p_topmargin : m_topmargin;
              c_logger.debug("Top margin set to: "+m_topmargin);
          * Returns the bottom margin.
          * @return Returns the bottommargin.
         public int getBottomMargin() {
              return m_bottommargin;
          * Returns the left margin.
          * @return Returns the leftmargin.
         public int getLeftMargin() {
              return m_leftmargin;
          * Returns the right margin.
          * @return Returns the rightmargin.
         public int getRightMargin() {
              return m_rightmargin;
          * Returns the top margin.
          * @return Returns the topmargin.
         public int getTopMargin() {
              return m_topmargin;
          * @return Returns the allowBottomLeftResize.
         public boolean isAllowBottomLeftResize() {
              return m_allowBottomLeftResize;
          * @return Returns the allowBottomResize.
         public boolean isAllowBottomResize() {
              return m_allowBottomResize;
          * @return Returns the allowBottomRightResize.
         public boolean isAllowBottomRightResize() {
              return m_allowBottomRightResize;
          * @return Returns the allowLeftResize.
         public boolean isAllowLeftResize() {
              return m_allowLeftResize;
          * @return Returns the allowRightResize.
         public boolean isAllowRightResize() {
              return m_allowRightResize;
          * @return Returns the allowTopLeftResize.
         public boolean isAllowTopLeftResize() {
              return m_allowTopLeftResize;
          * @return Returns the allowTopResize.
         public boolean isAllowTopResize() {
              return m_allowTopResize;
          * @return Returns the allowTopRightResize.
         public boolean isAllowTopRightResize() {
              return m_allowTopRightResize;
          * @param p_allowBottomLeftResize The allowBottomLeftResize to set.
         public void setAllowBottomLeftResize(boolean p_allowBottomLeftResize) {
              c_logger.debug("Setting bottom left resizing to: "+p_allowBottomLeftResize);
              m_allowBottomLeftResize = p_allowBottomLeftResize;
          * @param p_allowBottomResize The allowBottomResize to set.
         public void setAllowBottomResize(boolean p_allowBottomResize) {
              c_logger.debug("Setting bottom resizing to: "+p_allowBottomResize);
              m_allowBottomResize = p_allowBottomResize;
          * @param p_allowBottomRightResize The allowBottomRightResize to set.
         public void setAllowBottomRightResize(boolean p_allowBottomRightResize) {
              c_logger.debug("Setting bottom right resizing to: "+p_allowBottomRightResize);
              m_allowBottomRightResize = p_allowBottomRightResize;
          * @param p_allowLeftResize The allowLeftResize to set.
         public void setAllowLeftResize(boolean p_allowLeftResize) {
              c_logger.debug("Setting left resizing to: "+p_allowLeftResize);
              m_allowLeftResize = p_allowLeftResize;
          * @param p_allowRightResize The allowRightResize to set.
         public void setAllowRightResize(boolean p_allowRightResize) {
              c_logger.debug("Setting right side resizing to: "+p_allowRightResize);
              m_allowRightResize = p_allowRightResize;
          * @param p_allowTopLeftResize The allowTopLeftResize to set.
         public void setAllowTopLeftResize(boolean p_allowTopLeftResize) {
              c_logger.debug("Setting top left resizing to: "+p_allowTopLeftResize);
              m_allowTopLeftResize = p_allowTopLeftResize;
          * @param p_allowTopResize The allowTopResize to set.
         public void setAllowTopResize(boolean p_allowTopResize) {
              c_logger.debug("Setting top side resizing to: "+p_allowTopResize);
              m_allowTopResize = p_allowTopResize;
          * @param p_allowTopRightResize The allowTopRightResize to set.
         public void setAllowTopRightResize(boolean p_allowTopRightResize) {
              c_logger.debug("Setting top right resizing to: "+p_allowTopRightResize);
              m_allowTopRightResize = p_allowTopRightResize;
          * Following are the methods that do all the real stuff.
         /* We define constants that allow us to determine where the cursor is. */
         static final int TOP         = 0x0001;
         static final int BOTTOM      = 0x0002;
         static final int LEFT        = 0x0100;
         static final int RIGHT       = 0x0200;
         static final int TOPLEFT     = 0x0101;
         static final int TOPRIGHT    = 0x0201;
         static final int BOTTOMLEFT  = 0x0102;
         static final int BOTTOMRIGHT = 0x0202;
         static final int UNKNOWN     = 0x0000;
         protected int whereX(int p_x) {
              // check if on left side
              if(p_x >= 0 &&
                 p_x <= m_leftmargin) {
                   c_logger.debug("Cursor is on LEFT");
                   return LEFT;
              // check if on right side
              if(p_x <= m_component.getWidth() &&
                 p_x >= m_component.getWidth()-m_rightmargin) {
                   c_logger.debug("Cursor is on RIGHT");
                   return RIGHT;
              return UNKNOWN;
         protected int whereY(int p_y) {
              // check if on top side
              if(p_y >= 0 &&
                 p_y <= m_topmargin) {
                   c_logger.debug("Cursor is on TOP");
                   return TOP;
              // check if on bottom side
              if(p_y <= m_component.getHeight() &&
                 p_y >= m_component.getHeight()-m_bottommargin) {
                   c_logger.debug("Cursor is on BOTTOM");
                   return BOTTOM;
              return UNKNOWN;
         protected int where(int p_x,int p_y) {
              c_logger.debug("Determining pointer location: ");
              int l_composite = (whereX(p_x) | whereY(p_y));
              switch(l_composite) {
                   case LEFT:
                        c_logger.debug("Left");
                        break;
                   case RIGHT:
                        c_logger.debug("Right");
                        break;
                   case BOTTOM:
                        c_logger.debug("Bottom");
                        break;
                   case TOP:
                        c_logger.debug("Top");
                        break;
                   case TOPLEFT:
                        c_logger.debug("Top left");
                        break;
                   case TOPRIGHT:
                        c_logger.debug("Top right");
                        break;
                   case BOTTOMLEFT:
                        c_logger.debug("Bottom left");
                        break;
                   case BOTTOMRIGHT:
                        c_logger.debug("Bottom right");
                        break;
              return l_composite;
          * The component's default cursor.
         Cursor m_componentcursor;
         boolean m_resizingcursor;
         boolean m_dragready;
         protected void changeCursor(int p_where) {
              c_logger.debug("Changing cursor: ");
              m_resizingcursor = true;
              switch(p_where) {
                   case LEFT:
                        if(m_allowLeftResize) {
                             m_component.setCursor(c_leftcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case RIGHT:
                        if(m_allowRightResize) {
                             m_component.setCursor(c_rightcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case TOP:
                        if(m_allowTopResize) {
                             m_component.setCursor(c_topcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case BOTTOM:
                        if(m_allowBottomResize) {
                             m_component.setCursor(c_bottomcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case TOPLEFT:
                        if(m_allowTopLeftResize) {
                             m_component.setCursor(c_topleftcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case TOPRIGHT:
                        if(m_allowTopRightResize) {
                             m_component.setCursor(c_toprightcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case BOTTOMLEFT:
                        if(m_allowBottomLeftResize) {
                             m_component.setCursor(c_bottomleftcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   case BOTTOMRIGHT:
                        if(m_allowBottomRightResize) {
                             m_component.setCursor(c_bottomrightcursor);
                        }else {
                             m_resizingcursor = false;
                        break;
                   default:
                        c_logger.debug("Reverting to default component cursor: ");
                        m_resizingcursor = false;
                        m_component.setCursor(m_componentcursor);
                        break;
         protected void modifyBounds(int p_newx,int p_newy,int p_newwidth,int p_newheight) {
              m_component.setBounds(p_newx,p_newy,p_newwidth,p_newheight);
              m_component.setSize(p_newwidth,p_newheight);
              /*if(m_component.getParent() != null) {
                   LayoutManager l_manager = m_component.getParent().getLayout();
                   if(l_manager != null) {
                        l_manager.removeLayoutComponent(m_component);
                        l_manager.addLayoutComponent(m_layoutkey,m_component);
              if(m_component instanceof JComponent) {
                   ((JComponent) m_component).setPreferredSize(new Dimension(p_newwidth,p_newheight));
              m_component.repaint();
         protected void resizeLeft(MouseEvent p_e) {
              c_logger.debug("Resizing left side: ");
              if(p_e.getX() <= m_component.getWidth()-m_leftmargin-m_rightmargin-4) {
                   int l_newx = m_component.getX();
                   int l_newwidth = m_component.getWidth();
                   c_logger.debug("Eligible for leftward resize: ");
                   if(p_e.getX() <= 0) {
                        c_logger.debug("Leftward drag: ");
                        l_newx = p_e.getX()+m_component.getX();
                        l_newwidth = m_component.getWidth()-p_e.getX();
                   }else {
                        c_logger.debug("anti-Leftward drag: ");
                        l_newx = m_component.getX()-p_e.getX();
                        l_newwidth = m_component.getWidth()-p_e.getX();
                   c_logger.debug("Component new X: "+l_newx);
                   c_logger.debug("Component new W: "+l_newwidth);
                   modifyBounds(l_newx,m_component.getY(),l_newwidth,m_component.getHeight());
         protected void resizeBottom(MouseEvent p_e) {
              c_logger.debug("Resizing bottom side: ");
              if(p_e.getY() >= m_topmargin+m_bottommargin+4) {
                   c_logger.debug("Eligible for bottom side resize: ");
                   int l_newheight = p_e.getY();
                   c_logger.debug("Component new H: "+l_newheight);
                   modifyBounds(m_component.getX(),m_component.getY(),m_component.getWidth(),l_newheight);
         protected void resizeRight(MouseEvent p_e) {
              c_logger.debug("Resizing right side: ");
              if(p_e.getX() >= m_leftmargin+m_rightmargin+4) {
                   c_logger.debug("Eligible for right side resize: ");
                   int l_newwidth = p_e.getX();
                   c_logger.debug("Component new W: "+l_newwidth);
                   modifyBounds(m_component.getX(),m_component.getY(),l_newwidth,m_component.getHeight());
         protected void resizeTop(MouseEvent p_e) {
              c_logger.debug("Resizing top side: ");
              if(p_e.getY() <= m_component.getHeight()-m_topmargin-m_bottommargin-4) {
                   int l_newy = m_component.getY();
                   int l_newheight = m_component.getHeight();
                   c_logger.debug("Eligible for top side resize: ");
                   if(p_e.getY() <= 0) {
                        c_logger.debug("Topward drag: ");
                        l_newy = m_component.getY()+p_e.getY();
                        l_newheight = m_component.getHeight()-p_e.getY();
                   }else {
                        c_logger.debug("anti-Topward drag: ");
                        l_newy = m_component.getY()+p_e.getY();
                        l_newheight = m_component.getHeight()-p_e.getY();
                   c_logger.debug("Component new Y: "+l_newy);
                   c_logger.debug("Component new H: "+l_newheight);
                   modifyBounds(m_component.getX(),l_newy,m_component.getWidth(),l_newheight);
         protected void resizeBottomLeft(MouseEvent p_e) {
              c_logger.debug("Resizing southwest...");
              resizeBottom(p_e);
              resizeLeft(p_e);
         protected void resizeBottomRight(MouseEvent p_e) {
              c_logger.debug("Resizing southeast...");
              resizeBottom(p_e);
              resizeRight(p_e);
         protected void resizeTopLeft(MouseEvent p_e) {
              c_logger.debug("Resizing northwest...");
              resizeTop(p_e);
              resizeLeft(p_e);
         protected void resizeTopRight(MouseEvent p_e) {
              c_logger.debug("Resizing northeast...");
              resizeTop(p_e);
              resizeRight(p_e);
         /* (non-Javadoc)
          * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
         public void mouseDragged(MouseEvent p_e) {
              c_logger.debug("Dragged at: "+p_e.getX()+","+p_e.getY());
              if(m_resizingcursor) {
                   c_logger.debug("Resizing... ");
                   switch(m_component.getCursor().getType()) {
                        case Cursor.E_RESIZE_CURSOR:
                             resizeRight(p_e);
                             break;
                        case Cursor.SE_RESIZE_CURSOR:
                             resizeBottomRight(p_e);
                             break;
                        case Cursor.N_RESIZE_CURSOR:
                             resizeTop(p_e);
                             break;
                        case Cursor.NE_RESIZE_CURSOR:
                             resizeTopRight(p_e);
                             break;
                        case Cursor.S_RESIZE_CURSOR:
                             resizeBottom(p_e);
                             break;
                        case Cursor.SW_RESIZE_CURSOR:
                             resizeBottomLeft(p_e);
                             break;
                        case Cursor.NW_RESIZE_CURSOR:
                             resizeTopLeft(p_e);
                             break;
                        case Cursor.W_RESIZE_CURSOR:
                             resizeLeft(p_e);
                             break;
         /* (non-Javadoc)
          * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
         public void mouseMoved(MouseEvent p_e) {
              c_logger.debug("Moved at: "+p_e.getX()+","+p_e.getY());
              changeCursor(where(p_e.getX(),p_e.getY()));
         /* (non-Javadoc)
          * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
         public void mouseClicked(MouseEvent p_e) {
              c_logger.debug("Clicked at: "+p_e.getX()+","+p_e.getY());
         /* (non-Javadoc)
          * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
         public void mouseEntered(MouseEvent p_e) {
              c_logger.debug("Entered at: "+p_e.getX()+","+p_e.getY());
         /* (non-Javadoc)
          * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
         public void mouseExited(MouseEvent p_e) {
              c_logger.debug("Exited at: "+p_e.getX()+","+p_e.getY());
              if(!m_dragready) {
                   changeCursor(UNKNOWN);
         /* (non-Javadoc)
          * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
         public void mousePressed(MouseEvent p_e) {
              c_logger.debug("Pressed at: "+p_e.getX()+","+p_e.getY());
              if(m_resizingcursor) {
                   m_dragready = true;
         /* (non-Javadoc)
          * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
         public void mouseReleased(MouseEvent p_e) {
              c_logger.debug("Released at: "+p_e.getX()+","+p_e.getY());
              m_dragready = false;
    }Test file:
    * Copyright (c) 2004,
    * Vijayaraghavan Kalyanapasupathy
    * [email protected]
    * See accompanying project license for license terms and agreement.
    * The use of the intellectual property contained herein is subject
    * to the terms of the license agreement. If no license agreement
    * can be found at the locations from where you obtained this
    * sofwtare/file/code fragment contact the author for the license.
    * Contributors: Vijayaraghavan Kalyanapasupathy
    * Created     : 4:55:08 AM, Dec 2, 2004
    * Project     : SwingComponents
    package org.swingcomponents.tests;
    import java.awt.Color;
    import java.awt.Dimension;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.border.LineBorder;
    import org.netbeans.lib.awtextra.AbsoluteConstraints;
    import org.netbeans.lib.awtextra.AbsoluteLayout;
    import org.swingcomponents.components.ComponentResizer;
    * @author Vijayaraghavan Kalyanapasupathy
    public class TestComponentResizer {
         public static void testUndecoratedDialog() {
              try {
                   JDialog.setDefaultLookAndFeelDecorated(false);
                   JDialog l_dialog = new JDialog(new JFrame());
                   JDialog.setDefaultLookAndFeelDecorated(true);
                   l_dialog.setUndecorated(true);
                   l_dialog.setLocation(400,500);
                   l_dialog.setSize(300,300);
                   l_dialog.setVisible(true);
                   l_dialog.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                   l_dialog.setBackground(Color.BLACK);
                   JPanel l_panel = new JPanel();
                   l_panel.setBorder(LineBorder.createGrayLineBorder());
                   l_dialog.getContentPane().add(l_panel);
                   ComponentResizer l_resizer = new ComponentResizer(l_dialog,null);
                   l_dialog.pack();
                   l_dialog.show();
              }catch (Throwable t) {
                   t.printStackTrace(System.err);
         public static void testJTextArea() {
              try {
                   JFrame l_frame = new JFrame("Test DropDownDialog") {
                        public Dimension getPreferredSize() {
                             return new Dimension(800,600);
                   JTextArea l_area = new JTextArea(10,40);
                   ComponentResizer l_resizer = new ComponentResizer(l_area,null);
                   l_frame.getContentPane().setLayout(new AbsoluteLayout());
                   l_frame.getContentPane().add(l_area, new AbsoluteConstraints(300,400,300,300));
                   l_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   l_frame.pack();
                   l_frame.show();
              }catch(Throwable t) {
                   t.printStackTrace(System.err);
         public static void main(String[] args) {
              testJTextArea();
              //testUndecoratedDialog();
    }

    Apologies,
    I have left out the AbsoluteLayout and AbsoluteConstraints, but the same effect can supposedly be achieved using null layout and absolute positioning. This doesn't work for me, so if you would like those files (from netBeans) I will post them as well.
    thanx,
    -vijai.

  • DnD-NEED HELP!!!

    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 Dimitry,
    I've had that DnD plugin working since Beehive 1.5.x. As Manish says, it may depend on your FF version, also this extension only works when you are drafting your email in a window within the Zimbra frame (keyboard shortcut "c" to create new mail) NOT a floating windows (keyboard shortcut uppercase "C"). In the first case the following will be displayed under the subject field:
    "Совет. Перетащите файлы с рабочего стола для добавления вложений к этому сообщению."
    Hey check that out I got it in Russian ;o), though intrerestingly, none of the aforementioned key board shortcut work, must be my French keyboard...
    Here is an example of the command line we recently used to ensure it was activated:
    beectl add_preference_property set prfs=ZimbraDefaultUserPreferences,enpr=MyCompany name com_zimbra_dnd> type string value TRUE
    hth
    David

  • Is JViewport scrollRectToVisible API Javadoc ambigious or just plain wrong?

    I've been working on a JPanel derived class that demonstrates how to position the JViewport of a JScrollPane using JViewport's scrollRectToVisible method. I've got it working, but only after trial & error regarding the scrollRectToVisible's interpretation of the Rectangle input parameter.
    The issue is that the JDK API javadocs gave me the impression that the Rectangle fields "x" and "y" would specify the (x,y) coordinates of the upper right corner in absolute client area coordinates. The impression resulted from past usage of Rectangles where the "x" and "y" fields were always absolute coordinates. But my trial & error revealed that the "x" and"y" fields in the Rectangle are interpreted by scrollRectToVisible as signed relative deltas within the client area, not absolute client area coordinates.
    Here is the javadoc excerpt fom class JViewport: It does not really say how the Rectangle is interpreted...
    public void scrollRectToVisible(Rectangle contentRect)+
    Scrolls the view so that Rectangle within the view becomes visible.+
    This attempts to validate the view before scrolling if the view is currently not valid - isValid returns false. To avoid excessive validation when the containment hierarchy is being created this will not validate if one of the ancestors does not have a peer, or there is no validate root ancestor, or one of the ancestors is not a Window or Applet.+
    Note that this method will not scroll outside of the valid viewport; for example, if contentRect is larger than the viewport, scrolling will be confined to the viewport's bounds.+
    It says the "*Scrolls the view so that Rectangle within the view becomes visible.*"
    h3. *{color:#ff6600}How would you interpret this? Is this 'wrong by omission' or am I all wet?{color}*
    Here is the relevant chunk of code that operates by creating a Rectangle with deltas, not absolute coordinates. It works. The whole class is too big for this forum post, but I can put the JAR file up for download if requested...
    public class BigPanel extends JPanel implements MouseListener, MouseMotionListener {
         // Data defs and constructor omitted for brevity...
         private void scrollView() {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        //scrollRectToVisible(dxyRect); // WRONG, compiles OK, jumps around but mouse response is all wrong.
                        //scrollPane.scrollRectToVisible(dxyRect);  // WRONG, compiles OK, but does nothing!!!
                        scrollPane.getViewport().scrollRectToVisible(dxyRect);  // RIGHT!!!
         private void setDeltaXY(int mouseX, int mouseY) {
              // Use the base (x,y) coordinate of the view port rectangle
              // when calculating mouse coordinates (mx,my) relative to the
              // visible view port.
              Rectangle viewRect = scrollPane.getViewport().getViewRect();
              int mx = mouseX - viewRect.x;
              int my = mouseY - viewRect.y;
              // Use center of the view port rectangle as the point to subtract
              // from the mouse relative coordinate (mx,my) to calculate the
              // movement delta (dx,dy).
              int dx = mx - viewRect.width / 2;
              int dy = my - viewRect.height / 2;
              // Now create a rectangle with the delta (dx,dy) and the view port
              // (width,height) as the input to scrollRectToVisible.
              // Note that the (x,y) in the rectangle is not an absolute unsigned
              // (x,y) coordinate, but a signed relative delta (dx,dy),
              // which scrollRectToVisible uses to as the relative amount to shift.
              dxyRect = new Rectangle(dx, dy, viewRect.width, viewRect.height);
         private void moveView(MouseEvent e) {
              setDeltaXY(e.getX(), e.getY());
              scrollView();
         @Override
         public void mouseClicked(MouseEvent e) {
              info("mouseClicked");
              moveView(e);
         @Override
         public void mousePressed(final MouseEvent e) {
              info("mousePressed");
              setDeltaXY(e.getX(), e.getY());
              startRepeat();
         @Override
         public void mouseReleased(MouseEvent e) {
              info("mouseReleased");
              cancelRepeat();
         / *(non-Javadoc)*
    @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
         @Override
         public void mouseDragged(MouseEvent e) {
              setDeltaXY(e.getX(), e.getY());
    }

    I'm Barkin up the wrong tree, Huh?I think Darryl is right.
    I tried it as you suggested, on the JScrollpane instance, not the JScrollpane's JViewport. The results were not what I expected of absolute or relative coordinate systems.You got it wrong, try calling scrollRectToVisible on the component being scrolled i.e. viewport view.
    I have written a class which demonstrates working of scrollRectToVisible, that may help you:
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import javax.swing.*;
    * @author talha
    @SuppressWarnings("serial")
    public class ViewportExample extends JFrame {
         private JPanel scrolledPanel = new JPanel() {
              Dimension SIZE = new Dimension(1500, 1000);
              GradientPaint paint = new GradientPaint(0, 0, Color.WHITE, SIZE.width,
                        SIZE.height, Color.BLACK);
              protected void paintComponent(java.awt.Graphics g) {
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setPaint(paint);
                   g2.fillRect(0, 0, getWidth(), getHeight());
                   if (rect != null) {
                        g2.setPaint(new GradientPaint(rect.x, rect.y,
                                            Color.BLACK, rect.x + rect.width, rect.y
                                                      + rect.height, Color.WHITE));
                        g2.fill(rect);
                        g2.setColor(Color.WHITE);
                        g2.setStroke(new BasicStroke(2));
                        g2.draw(rect);
                        g2.drawString("You wanted this rectangle to be visible",
                                  rect.x + 5, rect.y + 20);
                        g2.setColor(Color.BLACK);
                        g2.setStroke(new BasicStroke(1, BasicStroke.CAP_BUTT,
                                  BasicStroke.JOIN_BEVEL, 3, new float[] { 3 }, 1.0f));
                        g2.drawLine(0, rect.y, rect.x, rect.y);
                        g2.drawLine(0, rect.y + rect.height, rect.x, rect.y
                                  + rect.height);
                        g2.drawLine(rect.x, 0, rect.x, rect.y);
                        g2.drawLine(rect.x + rect.width, 0, rect.x + rect.width,
                                            rect.y);
              public Dimension getPreferredSize() {
                   return SIZE;
         private Rectangle rect;
         private JComponent verticalRule = new JComponent() {
              protected void paintComponent(java.awt.Graphics g) {
                   Rectangle clip = g.getClipBounds();
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setColor(Color.BLACK);
                   g2.fill(clip);
                   int start = clip.y / 100 * 100;
                   int end = ((clip.y + clip.height) / 100 + 1) * 100;
                   g2.setColor(Color.WHITE);
                   for (int i = start; i < end; i += 100) {
                        g2.drawLine(20, i, 30, i);
                        g2.drawString(Integer.toString(i), 2, i + 15);
            private JComponent horizontalRule = new JComponent() {
              protected void paintComponent(java.awt.Graphics g) {
                   Rectangle clip = g.getClipBounds();
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                             RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setColor(Color.BLACK);
                   g2.fill(clip);
                   int start = clip.x / 100 * 100;
                   int end = ((clip.x + clip.width) / 100 + 1) * 100;
                   g2.setColor(Color.WHITE);
                   for (int i = start; i < end; i += 100) {
                        g2.drawLine(i, 20, i, 30);
                        g2.drawString(Integer.toString(i), i + 2, 25);
         public ViewportExample() {
              super("Viewport Example");
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JScrollPane pane = new JScrollPane(scrolledPanel);
              verticalRule.setPreferredSize(new Dimension(30, 1000));
              pane.setRowHeaderView(verticalRule);
              horizontalRule.setPreferredSize(new Dimension(1500, 30));
              pane.setColumnHeaderView(horizontalRule);
              pane.setBackground(Color.DARK_GRAY);
              add(pane, BorderLayout.CENTER);
              add(getSouthPanel(), BorderLayout.SOUTH);
              setSize(700, 600);
              // setExtendedState(MAXIMIZED_BOTH);
              setLocationRelativeTo(null);
         private JPanel getSouthPanel() {
              JPanel panel = new JPanel();
              final JTextField field = new JTextField(30);
              field.addActionListener(new ActionListener() {
                   Pattern pattern = Pattern
                             .compile("\\s*((?:-)?\\d+)\\s+((?:-)?\\d+)\\s+(\\d+)\\s+(\\d+)\\s*");
                   @Override
                   public void actionPerformed(ActionEvent e) {
                        Matcher matcher = pattern.matcher(field.getText());
                        if (matcher.matches()) {
                             rect = new Rectangle(Integer.parseInt(matcher.group(1)),
                                       Integer.parseInt(matcher.group(2)), Integer
                                                 .parseInt(matcher.group(3)), Integer
                                                 .parseInt(matcher.group(4)));
                             //-- mark this --
                             scrolledPanel.scrollRectToVisible(rect);
                             scrolledPanel.repaint();
                        } else {
                             Toolkit.getDefaultToolkit().beep();
              panel.add(new JLabel("Rectangle: (Formatted as : x y width height) "));
              panel.add(field);
              return panel;
         public static void main(String... args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new ViewportExample().setVisible(true);
    } This code has many irrelevant things but I added them just to learn new things, but they help in making overall application more usable. Have fun :)
    Try typing "300 400 400 300" in the text field, hit Enter and see the result. Try out other values...
    Thanks!

  • Capturing events help

    Im building a visual component where the user can drag node(s) from a palette to a main panel. These nodes can be connected to one another with links that one can create by gliding over the node and dragging it to the node that it needs to be connected to. My problem now is how do I determine which way the arrow is going i.e. what if the user is dragging to the left or right ot top or bottom of the node how can I capture this?
    Thank you all for your time

    My problem now is how do I determine which way the arrow
    is going i.e. what if the user is dragging to the
    left or right ot top or bottom of the node how can I
    capture this? You'll need to have custom DnD code to handle mouse drag events (see MouseMotionListener.mouseDragged) when dragging within the main panel. You'll need to detect collisions with other nodes in your mouseDragged method. Collision detection is sometimes difficult to do depending on the shape of your nodes. Simplest way is to get the bounds of each node and use the Rectangle methods to calculate collision points with the dragged node as you're dragging. When you detect a mouse released event, you'll use the last known direction as an indicator on which way to point the arrow.

  • StylePad demo - scaling it

    Hi, I'm trying to modify the Stylepad demo (located in $JAVA_HOME/demo/jfc/Stylepad) so that it works 100% with a scaled instance of Graphics2D.
    I've seen a bit of discussion around this (scaling/zooming a JTextPane/JTextComponent) - but I have yet to see a solution.
    Just overriding JTextPane's paintComponen() method and serving it a scaled Graphics2D instance opened up a box of problems :) - to which I would appreciate solution suggestions to.
    I've modified StylePad.java's createEditor() method. Here it is:
        protected JTextComponent createEditor() {
               StyleContext sc = new StyleContext();
               final DefaultStyledDocument doc = new DefaultStyledDocument();
                  initDocument(doc, sc);
              final JTextPane p = new JTextPane(doc){
                  public void paintComponent(Graphics g) {
                            Graphics2D g2d = (Graphics2D)g;
                         g2d.scale(0.5,0.5);
                         super.paintComponent(g2d);
                    p.setCaret(new ScaledCaret()); // my custom caret
                    p.addCaretListener(new CaretListener() {
                            public void caretUpdate(CaretEvent e) {
                                p.repaint();
                 MouseInputAdapter mh = new MouseInputAdapter() {
                            public void mousePressed(MouseEvent e) {
                                    p.repaint();
                           public void mouseDragged(MouseEvent e) {
                                    p.repaint();
                    p.addMouseListener(mh);
                    p.addMouseMotionListener(mh);
                    p.setDragEnabled(true);
         /* My own BasicTextPaneUI implementation, commented out for now
            ScaledTextUI sTextUI = new ScaledTextUI();
            p.setUI(sTextUI);
            return p;
        }The first problem I encountered was that the Caret position was all wrong. So, I created my own caret implementation that extends DefaultCaret. Remember that this is just test code to get it working with the scale 0.5,0.5 which I use in StylePad ..
    import javax.swing.text.DefaultCaret;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    public class ScaledCaret extends DefaultCaret {
         * Moves the caret position
         * according to the mouse pointer's current
         * location.  This effectively extends the
         * selection.  By default, this is only done
         * for mouse button 1.
         * @param e the mouse event
         * @see MouseMotionListener#mouseDragged
        public void mouseDragged(MouseEvent e) {
            MouseEvent p = new MouseEvent((Component)e.getSource(),e.getID(),e.getWhen(),e.getModifiers(),(int)Math.round(e.getX()*2), (int)Math.round(e.getY()*2),e.getClickCount(),e.isPopupTrigger());
            super.mouseDragged(p);
         * Tries to set the position of the caret from
         * the coordinates of a mouse event, using viewToModel().
         * @param e the mouse event
        protected void positionCaret(MouseEvent e) {
            MouseEvent p = new MouseEvent((Component)e.getSource(),e.getID(),e.getWhen(),e.getModifiers(),(int)Math.round(e.getX()*2), (int)Math.round(e.getY()*2),e.getClickCount(),e.isPopupTrigger());
            super.positionCaret(p);
    }That fixed the Caret positioning problems - but it still does not blink (once scaled the caret stops blinking).
    The problem I am working with now is the size of the component.
    If you run the StylePad demo with the above code you will experience problems with the painting of the JTextPane .. the ScrollPane obviously thinks its bigger than what it is, and around the JTextPane a lot of "rubbish" is painted.
    My next step was creating a class extending BasicTextPaneUI. I did this, overriding getMaximumSize(), getPeferredSize() and getMinimumSize() to always return a specific dimension. It did not fix the problems I described above..
    Hope someone takes an interest in this problem :)

    Hi again,
    I found out that the scaled painting should be done in the JTextPane's paintComponent method (this will affect all children). Doing them in the view's messed up things ..
    I do however still have problems. Trying to implement your code everything looks pretty messed up.. Here's my EditorKit and ViewFactory if you would be kind enough to take a look at it:
        static class MyEditorKit extends StyledEditorKit implements ViewFactory {
          * Fetches a factory that is suitable for producing
          * views of any models that are produced by this
          * kit.  The default is to have the UI produce the
          * factory, so this method has no implementation.
          * @return the view factory
            public ViewFactory getViewFactory() {
             return this;
             * Creates an uninitialized text storage model (PlainDocument)
             * that is appropriate for this type of editor.
             * @return the model
            public Document createDefaultDocument() {
                return new DefaultStyledDocument();
          * THIS IS COPIED FROM StyledEditorKit
          * Creates a view from the given structural element of a
          * document.
          * @param elem  the piece of the document to build a view of
          * @return the view
          * @see View
          public View create(Element elem) {
             String kind = elem.getName();
             if (kind != null) {
              if (kind.equals(AbstractDocument.ContentElementName)) {
                        return new MyLabelView(elem);
              } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
                  return new MyParagraphView(elem);
              } else if (kind.equals(AbstractDocument.SectionElementName)) {
                  return new MyBoxView(elem, View.Y_AXIS);
              } else if (kind.equals(StyleConstants.ComponentElementName)) {
                  return new MyComponentView(elem);
              } else if (kind.equals(StyleConstants.IconElementName)) {
                  return new IconView(elem);
             // default to text display
                return new LabelView(elem);
         }Here's an example of one of the view's (MyParagraphView since that is the one that is used frequently (always?):
            static class MyParagraphView extends javax.swing.text.ParagraphView {
                public MyParagraphView(Element elem) {
                    super(elem);
                    System.out.println("new MyParagraphView()");
                 * Determines the minimum span for this view along an
                 * axis.  This is implemented to provide the superclass
                 * behavior after first making sure that the current font
                 * metrics are cached (for the nested lines which use
                 * the metrics to determine the height of the potentially
                 * wrapped lines).
                 * @param axis may be either View.X_AXIS or View.Y_AXIS
                 * @return  the span the view would like to be rendered into.
                 *           Typically the view is told to render into the span
                 *           that is returned, although there is no guarantee.
                 *           The parent may choose to resize or break the view.
                 * @see View#getMinimumSpan
                public float getMinimumSpan(int axis) {
                    float f = super.getMinimumSpan(axis);
                    System.out.print("getMinimumSpan() from super ="+f+" .. ");
                    if(axis == View.X_AXIS) {
                        f *= StylePadConstants.X_SCALE_FACTOR;
                    } else {
                        f *= StylePadConstants.Y_SCALE_FACTOR;
                    System.out.println("new ="+f);
                    return f;
                 * Determines the maximum span for this view along an
                 * axis.  This is implemented to provide the superclass
                 * behavior after first making sure that the current font
                 * metrics are cached (for the nested lines which use
                 * the metrics to determine the height of the potentially
                 * wrapped lines).
                 * @param axis may be either View.X_AXIS or View.Y_AXIS
                 * @return  the span the view would like to be rendered into.
                 *           Typically the view is told to render into the span
                 *           that is returned, although there is no guarantee.
                 *           The parent may choose to resize or break the view.
                 * @see View#getMaximumSpan
                public float getMaximumSpan(int axis) {
                    float f = super.getMaximumSpan(axis);
                    if(axis == View.X_AXIS) {
                        f *= StylePadConstants.X_SCALE_FACTOR;
                    } else {
                        f *= StylePadConstants.Y_SCALE_FACTOR;
                    return f;
                 * Determines the preferred span for this view along an
                 * axis.  This is implemented to provide the superclass
                 * behavior after first making sure that the current font
                 * metrics are cached (for the nested lines which use
                 * the metrics to determine the height of the potentially
                 * wrapped lines).
                 * @param axis may be either View.X_AXIS or View.Y_AXIS
                 * @return  the span the view would like to be rendered into.
                 *           Typically the view is told to render into the span
                 *           that is returned, although there is no guarantee.
                 *           The parent may choose to resize or break the view.
                 * @see View#getPreferredSpan
                public float getPreferredSpan(int axis) {
                    float f = super.getPreferredSpan(axis);
                    System.out.print("getPreferredSpan() - from super="+f+"  .. ");
                    if(axis == View.X_AXIS) {
                        f *= StylePadConstants.X_SCALE_FACTOR;
                    } else {
                        f *= StylePadConstants.Y_SCALE_FACTOR;
                    System.out.println("new="+f);
                    return f;
                 * Provides a mapping from the document model coordinate space
                 * to the coordinate space of the view mapped to it.  This makes
                 * sure the allocation is valid before calling the superclass.
                 * @param pos the position to convert >= 0
                 * @param a the allocated region to render into
                 * @return the bounding box of the given position
                 * @exception BadLocationException  if the given position does
                 *  not represent a valid location in the associated document
                 * @see View#modelToView
                public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
                    Rectangle r = (Rectangle)super.modelToView(pos, a, b);
                    r.x *= StylePadConstants.X_SCALE_FACTOR;
                    r.y *= StylePadConstants.Y_SCALE_FACTOR;
                    r.width *= StylePadConstants.X_SCALE_FACTOR;
                    r.height *= StylePadConstants.Y_SCALE_FACTOR;
                    return r;
                 * Provides a mapping from the view coordinate space to the logical
                 * coordinate space of the model.
                 * @param x   x coordinate of the view location to convert >= 0
                 * @param y   y coordinate of the view location to convert >= 0
                 * @param a the allocated region to render into
                 * @return the location within the model that best represents the
                 *  given point in the view >= 0
                 * @see View#viewToModel
                public int viewToModel(float x, float y, Shape a, Position.Bias[] bias) {
                    float newx = (float)(x*StylePadConstants.X_SCALE_FACTOR);
                    float newy = (float)(y*StylePadConstants.Y_SCALE_FACTOR);
                    Rectangle r = a.getBounds();
                    r.x *= StylePadConstants.X_SCALE_FACTOR;
                    r.y *= StylePadConstants.Y_SCALE_FACTOR;
                    r.width *= StylePadConstants.X_SCALE_FACTOR;
                    r.height *= StylePadConstants.Y_SCALE_FACTOR;
                    int i = super.viewToModel(newx, newy, r, bias);
                    return i;
            }What happens is that text elements are displayed on top of other text elements etc.
    All the other views (MyBoxView etc.) contains the same code as the one above. I copied the create() method from StyledEditorKit's ViewFactory.
    StylePadConstants merely contains the x/y scale factor.
    Best regards,
    Bjorn

  • Force tootip to display?

    hi,
    i wanted to know is there any way to force a tooltip to display, whether or not the user wants it? i wanted to have a small tool tip next to my mouse at all times displaying the x and y coordinates. is this possible?

    ok i used the popup menu and got it to work, the gui is still ugly, but i just wanted to know how to do it, thanks again.
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.event.*;
    * Created on Jul 16, 2003
    * To change this generated comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    * @author soni29
    * To change this generated comment go to
    * Window>Preferences>Java>Code Generation>Code and Comments
    public class MouseTip extends JFrame{
         JPanel panel;
         JTextField field;
         JButton button;
         JLabel label;
         JLabel mouseToolTip = new JLabel();
         JPopupMenu menu = new JPopupMenu();
         JMenuItem item = new JMenuItem();
         public static void main(String[] args) {
              MouseTip obj = new MouseTip();
              obj.init();
         public void init() {
              panel = new JPanel();
              field = new JTextField();
              button = new JButton("button");
              label = new JLabel("hi");
              mouseToolTip.setBackground(Color.red);
              menu.add(item);
         //     panel.setLayout(new GridLayout(4,1));
              panel.add(button);
              panel.add(label);
              panel.add(field);
              panel.add(mouseToolTip);
              getContentPane().add(panel);
              setSize(400,400);
              panel.addMouseMotionListener(new ToolTiper());
              field.addMouseMotionListener(new ToolTiper());
              button.addMouseMotionListener(new ToolTiper());
              this.addWindowListener(new Windower());
              setVisible(true);
         class Windower extends WindowAdapter {
              public void windowClosed(WindowEvent e) {
                   System.exit(0);
         class ToolTiper implements MouseMotionListener {
              /* (non-Javadoc)
               * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
              public void mouseDragged(MouseEvent e) {
                   // do nothing
              /* (non-Javadoc)
               * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
              public void mouseMoved(MouseEvent e) {
                   field.setText(e.getX() + "," + e.getY());     
                   mouseToolTip.setText(e.getX() + "," + e.getY());
                   mouseToolTip.setLocation(e.getX(), e.getY());
                   item.setText(e.getX() + "," + e.getY());
                   menu.setLocation(e.getX(), e.getY());
                   menu.setVisible(true);
    }

  • MouseMotionListener question

    Hi,
    I have discovered an interesting problem with the MouseMotionListener class.
    I have a window, say, a frame and in that I have a MouseMotionListener added to it. Now, in the MouseMoving method, I just print out the X and Y on the frame. Simple.
    However, when I say, press the mouse one button and then move my mouse, suddenly, the MouseMoving method isn't being called. When I let loff with the button and resume moving the mouse, it starts to print out the locations again.
    Does anyone know how get around this?
    Thanks.

    Your mouseDragged method will be notified

  • Problem w/ MouseMotionListener on JTable cell

    Hey everyone,
    I am using a MouseMotionListener on a JTable, and in most cases it works fine. The case where it does NOT work as I would expect is when you are editing a cell. In that case, events do not register when the mouse is moving over the cell being edited. I'm assuming that for some reason the cell editor maybe is receiving the events... but I'm not sure that is the case, and if it is, not sure how to deal with it. Here's a very basic example:
    ***************** begin code example ************************************
    public class Main extends JFrame {
    /** Creates a new instance of Main */
    public Main() {
    this.setLayout(new BorderLayout());
    JPanel panel = new JPanel();
    JTable theTable = new JTable(1,1);
    theTable.addMouseMotionListener(new MouseMotionListener() {
                   public void mouseDragged(MouseEvent e) {
                        // TODO Auto-generated method stub
                   public void mouseMoved(MouseEvent e) {
                        System.out.println("Mouse Moved");
    panel.add(theTable);
    this.add(panel,BorderLayout.NORTH);
    this.setSize(100,100);
    setVisible(true);
    * @param args the command line arguments
    public static void main(String[] args) {
    Main main = new Main();
    ***************** end code example **************************************
    Now, what I want to do is be able to have a listener not only on the table, but also on the cells (even when they are being edited). It is worth noting that the listener still functions around the borders of the cell... just not when mousing over the cell itself. What is going on with this? What is the best way for me to achieve my desired results?
    Thanks in advance,
    Jared

    Thanks for the tip on code formatting tags camickr. I'm (obviously) new to the forums.
    I am using "balloon tool tips" (can be seen here: https://balloontip.dev.java.net) to display information about the columns. The way I am currently doing it is that I have a MouseMotionListener on the entire JTable, and I attach the balloon tool tip to the header directly above the center of the column that the mouse is over. The way I am able to always know where to attach the balloon tool tip at the top is by using the events from the MouseMotionListener, as well as the X coordinate provided by the event. It works wonderfully... until one of the cells is being edited. At that point it works wonderfully on every part of the JTable except that one cell.
    Does that answer your question?
    Thanks again,
    Jared

  • How can a class extending MouseAdapter override mouseDragged method?

    I've found this code from somewhere, don't remember where
    private class DragLimiter extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
    pressedX = e.getX();
    pressedY = e.getY();
    @Override
    public void mouseDragged(MouseEvent e) {
    label.setLocation(
    Math.min(
    Math.max(label.getX() + e.getX() - pressedX, BORDER),
    panel.getWidth() - label.getWidth() - BORDER),
    Math.min(
    Math.max(label.getY() + e.getY() - pressedY, BORDER),
    panel.getHeight() - label.getHeight() - BORDER));
    }The question is how can a class extending MouseAdapter override mousedragged()?
    I found that MouseAdapter implements MouseListener whose subinterface is MouseMotionListener, I think this has something to do with the question.
    But I've always thought you can only override methods of the super classes or interfaces not vice versa.
    I believe I have some kind of fundamental misunderstanding of this and would like to have some help in understanding this.
    Thanks

    This is more a Java question than a Swing question.
    I found that MouseAdapter implements MouseListener whose subinterface is MouseMotionListenerThat's not correct: if you look at MouseAdapter Javadoc, you'll find that it implements both MouseListener and MouseMotionListener (and MouseMotionListener is not a subinterface of MouseListener).
    Regardless, if you look at the javadoc, you see that MouseAdapter declares a method public void mouseDragged(MouseEvent). It doesn't matter whether this is also declared by an interface, a subclass can override it all the same.

  • OO question

    Hi . Sorry, newbie question, but still, I'm stuck:
    I have a program X.
    In public class X, in main, I have something like
    myFrame frame=new myFrame();....
    In class myFrame extends JFrame, in the constructor "public myFrame()", I have
    //Add panel to frame:
    myPanel panel=new myPanel();
    add(panel);
    //Add a window events listener
    addWindowListener(new WindowEventsListener());
    In class myPanel I implemented the isDirty property and an accessor,
    getDirtyState. In WindowEventsListener, upon closing, I'd like to check the isDirty property of myPanel.
    My problem is that in WindowEventsListener I cannot say
    public void windowClosing(WindowEvent e)
    JOptionPane pane = new JOptionPane();
    Toolkit.getDefaultToolkit().beep();
    if (getDirtyState()==true)
    if (pane.showConfirmDialog(e.getComponent(),"Save drawing before quitting
    ?", "Sketch", JOptionPane.YES_NO_OPTION)==0)
    //The user chose YES
    pane.showMessageDialog(e.getComponent(), "Save here !", "Program X",
    JOptionPane.OK_OPTION);
    System.exit(0);
    else
    System.exit(0);
    because getDirtyState refers to myPanel, and I don't see myPanel from there.
    Which is the proper OO way of passing this value all the way to my
    WindowEventsListener, please ? The isDirty belongs in myPanel, not in
    myFrame, and, either way, how would I pass that value to class
    WindowEventsListener which extends WindowAdapter ?
    Thank you, Alex.

    First, thank you very much for your answer...
    Sorry, I have tried to use your suggestion, but I think that I'm missing something - I would have to use a constructor of class WindowEventsListener which would take a parameter of that type. Somehow, it doesn't work - I'll try again tomorrow.
    While waiting for an answer, I "solved" the problem with the following (gauche, I'm sure) code (this is the complete code):
    package raducu;
    import javax.swing.*;
    public class Blackboard {
         public static void main(String[] args)
              SketchFrame frame=new SketchFrame();
              frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
              frame.setVisible(true);
    }//End class Blackboard
    package raducu;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    class SketchFrame extends JFrame
         public SketchPanel panel;
         public SketchFrame()
              Toolkit kit=Toolkit.getDefaultToolkit();          
              Dimension screenSize=kit.getScreenSize();
              int screenWidth=screenSize.width;
              int screenHeight=screenSize.height;                    
              setSize(screenWidth/2, screenHeight/2);
              setLocation(screenWidth/4,screenHeight/4);
              //setExtendedState(MAXIMIZED_BOTH);
              setIconImage(kit.getImage("red-ball.gif"));          
              setTitle("Blackboard");
              //Add panel to frame:
              this.panel=new SketchPanel();
              add(this.panel);          
              //Add a window events listener
              addWindowListener(new WindowEventsListener());
    }//End class SketchFrame
    package raducu;
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    public class SketchPanel extends JPanel
         private Point2D previousEnd;
         private ArrayList<Line2D> lines;     
         private static final double RADIUS=2.5;
         private boolean isDirty;
         private boolean isClicked;
         //Constructor
         public SketchPanel()
              this.previousEnd=new Point2D.Double(0,0);
              this.lines= new ArrayList<Line2D>();
              this.isDirty=false;
              setForeground(Color.YELLOW);
              MouseMotionListener mouseMotionListener = new MouseMotionHandler();          
              this.addMouseMotionListener(mouseMotionListener);
              MouseListener mouseListener=new MouseClickHandler();
              this.addMouseListener(mouseListener);
              //Define actions
              Action yellowAction=new ColorAction("Yellow",new ImageIcon("yellow-ball.gif"), Color.YELLOW);
              Action blueAction=new ColorAction("Blue",new ImageIcon("blue-ball.gif"), Color.blue);
              Action redAction=new ColorAction("Red",new ImageIcon("red-ball.gif"), Color.red);
              //Add buttons for these actions:
              add(new JButton(yellowAction));
              add(new JButton(blueAction));
              add(new JButton(redAction));
              //Associate the Y, B and R keys with names
              InputMap imap=getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
              imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
              imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
              //Associate the names with actions
              ActionMap amap=getActionMap();
              amap.put("panel.yellow", yellowAction);
              amap.put("panel.red", redAction);
              amap.put("panel.blue", blueAction);
         //Adds to "lines" array
         private void addLine(int dx, int dy)
              //compute new end point
              Point2D newEnd=new Point2D.Double(dx, dy);
              //add line segment
              Line2D line=new Line2D.Double(this.previousEnd, newEnd);          
              this.lines.add(line);          
              //remember new end point
              this.previousEnd=newEnd;
              this.isDirty=true;
         //resets the Point tracking, so that when the mouse is dragged, no line is added and the end point is updated
         private void resetLine(int dx, int dy)
              //remember new end point
              this.previousEnd=new Point2D.Double(dx, dy);          
         private boolean getClicked()
              return this.isClicked;
         private void setClicked(boolean isClicked)
              this.isClicked=isClicked;
         public boolean getDirtyState()
              return this.isDirty;
         //overrides the paintComponent method of object Component.
         public void paintComponent(Graphics g)     
              super.paintComponent(g);
              setBackground(Color.BLACK);          
              Graphics2D g2=(Graphics2D) g;
              //draw all lines:          
              for (Line2D l : this.lines)
                   g2.draw(l);
         //inner class MouseMotionHandler
         class MouseMotionHandler extends MouseMotionAdapter
              public void mouseDragged(MouseEvent event)
                   if (SketchPanel.this.isClicked==true)
                        SketchPanel.this.addLine(event.getX(), event.getY());                    
                        repaint();
         }//end inner class MouseMotionHandler
         //inner class MouseClickHandler
         class MouseClickHandler extends MouseAdapter
              public void mousePressed(MouseEvent event)
                   if ((event.getModifiersEx() & InputEvent.BUTTON1_DOWN_MASK)!=0)
                        SketchPanel.this.isClicked=true;
                        resetLine(event.getX(), event.getY());
              public void mouseReleased(MouseEvent event)
                   SketchPanel.this.isClicked=false;               
         }//end inner class MouseClickHandler
         //inner class for ActionListener. AbstractAction is a class implementing the Action interface...
         class ColorAction extends AbstractAction
              //Constructs a "color" action object
              public ColorAction(String name, Icon icon, Color c)
                   putValue(Action.NAME, name);
                   putValue(Action.SMALL_ICON, icon);
                   putValue(Action.SHORT_DESCRIPTION, "Sets panel to " + name.toLowerCase());
                   putValue("color", c);
              public void actionPerformed(ActionEvent event)
                   Color c=(Color) getValue("color");
                   setForeground(c);               
         }//end inner class ColorAction
    }//End class SketchPanel
    package raducu;
    import java.awt.Toolkit;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JOptionPane;
    class WindowEventsListener extends WindowAdapter
         public void windowStateChanged(WindowEvent e)
              System.out.println(e.toString());
         public void windowClosing(WindowEvent e)
              JOptionPane pane = new JOptionPane();          
              SketchFrame x;
              x=(SketchFrame) e.getSource();
              if (x.panel.getDirtyState()==true)          
                   Toolkit.getDefaultToolkit().beep();
                   if (pane.showConfirmDialog(e.getComponent(),"Save drawing before quitting ?", "Blackboard", JOptionPane.YES_NO_OPTION)==0)
                        //The user chose YES                    
                        pane.showMessageDialog(e.getComponent(), "Save here !", "Blackboard", JOptionPane.OK_OPTION);
                        System.exit(0);
                   else
                        System.exit(0);
              else
                   System.exit(0);
    }As you can see, in windowClosing I take a reference to the source, which happens to be my Frame object, which contains a public "panel" object. It's not clean, I know... I'll try your suggestion.
    Thank you very much....

  • Background picture to famous "ImageTest" applet - Is it supid Question?

    I would like to see what Pholser will say about this. :)
    Is this a dumest question or what ?
    Thanks in advance
    basisdba
    ------------------ Repeated----------------------------------------
    Hi to all,
    I am not sure if you could help on this one or not, but
    will be happy to see any responding on this :))
    This is the example that I have worked on:
    http://java.sun.com/applets/other/ImageTest/index.html
    I am trying to add a sold background to this, is this possible?
    Thanks in advance
    Regards,

    Hi Sam and all of you,
    Sorry for the delay I am very bussy daily as SAP adminstrator,
    if you know what I mean :)
    You both are right but with some minor corrections.
    You guys are all great after all...
    I attached ImageTest.java demo sample with this modification to the
    background only...I am trying to add extra code into it to allow
    NOT only BLUE/RED swap color but also some more colors, how can I do
    that? How can I add black, green, yellow and so on...(stupid nah :) )
    Why in the hell "Java Tech.." make the color defining so hard? :)
    Or it would be nice to have a 16 color table to choose from...
    Thanks again to all of you and I also rewarded your points based
    on the most recent "white house" logic! :)))))
    Regards,
    ------------------------------- Start of the code
    /*Modified only ImageTest.java Demo
    import java.lang.Math.*; // for Spray
    import java.awt.*; // note to self - imports CURSOR class
    import javax.swing.*; // for ui
    import java.awt.image.*; // for images
    import java.applet.*; // for sounds
    import java.awt.event.*; // for events
    import java.net.*; // URL
    import java.net.URL;
    import java.util.Vector;
    import java.awt.geom.*; // for Line2D
    import java.util.*; // used for the Vector in the flood fill method
    import java.util.StringTokenizer;
    public class ImageTest extends Applet {
    //Init
    public void init()
    // Image bg0 = applet.getImage(applet.getDocumentBase(),"images/bg0.gif");
    setLayout(new BorderLayout());
    add("Center", new ImagePanel(this));
    add("North", new ImageHelp());
    setVisible(true);
    public String getAppletInfo()
    return "A simple image manipulation tool.";
    class ImageHelp extends Panel {
    public ImageHelp() {
    setLayout(new GridLayout(6, 1)); //Grid 5 Row and 1 column
    //m
    // add(new Button("Move"));
    //m
    add(new Label("test",
    Label.CENTER));
    add(new Label("Image Move: < > ^ v, or with [L]eft/[R]ight/p/[D]own",
    Label.CENTER));
    add(new Label("Image Resize: +/-",
    Label.CENTER));
    add(new Label("Color Filter: T key",
    Label.CENTER));
    add(new Label("Change Alpha: (Shift)+/-",
    Label.CENTER));
    add(new Label("Rotate Image: (Shift)<> or (Shift)[L]eft/[R]ight",
    Label.CENTER));
    System.out.println("");
    class ImagePanel extends Panel
    Applet applet;
    public ImagePanel(Applet app) {
    applet = app;
    setLayout(new BorderLayout());
    Panel grid = new Panel();
    grid.setLayout(new GridLayout(1, 1)); //first(row), second (column)
    add("Center", grid);
         Image bg0 = applet.getImage(applet.getDocumentBase(),"images/bg0.gif");
         Image fg0 = applet.getImage(applet.getDocumentBase(),"images/ff001.gif");
         grid.add(new ImageCanvas(applet, fg0, bg0, 1.0));
         setBounds(0, 0, 20, 20);
    class ImageCanvas
    extends Canvas
    implements ImageObserver, KeyListener, MouseListener,
    MouseMotionListener, FocusListener {
    double hmult = 0;
    int xadd = 0;
    int yadd = 0;
    int xprev = 0;
    int yprev = 0;
    int imgw = -1;
    int imgh = -1;
    int xoff = 0;
    int yoff = 0;
    int scalew = -1;
    int scaleh = -1;
    boolean focus = false;
    boolean usefilter = false;
    static final int numalphas = 9;
    int alpha = numalphas - 1;
    static final int numrotations = 8;
    int rotation = 0;
    ImageFilter colorfilter;
    ImageFilter alphafilters[] = new ImageFilter[numalphas];
    RotateFilter rotfilters[] = new RotateFilter[numrotations];
    Image origimage;
    Image curimage, backimage;
    Applet applet;
         public BufferedImage currentImage, oldImage, tempImage, storedImage;
    Image bg0, bg1, bg2, bgImage;
         public URL URL_STRING;
    private int picNo = 0;
    public void init()
    try {
         bg0 = new ImageIcon(new URL(URL_STRING +"images/bg0.gif")).getImage();
         bg1 = new ImageIcon(new URL(URL_STRING +"images/bg1.gif")).getImage();
         catch (Exception exc)
         {//imgLoad = "Image failed to load";
    public ImageCanvas(Applet app, Image img,Image bg0,double mult) {
    applet = app;
    origimage = img;
    backimage = bg0;
    hmult = mult;
    pickImage();
    setBounds(0, 0, 100, 100);
    addMouseListener(this);
    addMouseMotionListener(this);
    addKeyListener(this);
    addFocusListener(this);
    //1.1 event handling
    public void focusGained(FocusEvent e) {
    focus = true;
    repaint();
    public void focusLost(FocusEvent e) {
    focus = false;
    repaint();
    public void keyPressed(KeyEvent e) {
    public void keyTyped(KeyEvent e) {
    char key = e.getKeyChar();
    switch(key)
    case 't':
    case 'T':
    usefilter = !usefilter;
    pickImage();
    repaint();
    e.consume();
    break;
    case '^':
    case '6':
    case 'u':
    case 'U':
    yadd -= 5;
    repaint();
    e.consume();
    break;
    case 'v':
    case 'V':
    case 'd':
    case 'D':
    yadd += 5;
    repaint();
    e.consume();
    break;
    case '>':
    case 'R':
    rotation--;
    if (rotation < 0) {
    rotation = numrotations - 1;
    pickImage();
    scalew = scaleh = -1;
    repaint();
    e.consume();
    break;
    case '.':
    case 'r':
    xadd += 5;
    repaint();
    e.consume();
    break;
    case '<':
    case 'L':
    rotation++;
    if (rotation >= numrotations) {
    rotation = 0;
    pickImage();
    scalew = scaleh = -1;
    repaint();
    e.consume();
    break;
    case ',':
    case 'l':
    xadd -= 5;
    repaint();
    e.consume();
    break;
    case '+':
    if (++alpha > numalphas - 1) {
    alpha = numalphas - 1;
    pickImage();
    repaint();
    e.consume();
    break;
    case '=':
    hmult *= 1.2;
    scalew = scaleh = -1;
    repaint();
    e.consume();
    break;
    case '-':
    hmult /= 1.2;
    scalew = scaleh = -1;
    repaint();
    e.consume();
    break;
    case '_':
    if (--alpha < 0) {
    alpha = 0;
    pickImage();
    repaint();
    e.consume();
    break;
    public void keyReleased(KeyEvent e) {
    public void mouseClicked(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    xprev = e.getX();
    yprev = e.getY();
    e.consume();
    public void mouseReleased(MouseEvent e) {
    e.consume();
    public void mouseEntered(MouseEvent e) {
    requestFocus();
    e.consume();
    public void mouseExited(MouseEvent e) {
    public void mouseDragged(MouseEvent e) {
    int x = e.getX();
    int y = e.getY();
    xadd += x - xprev;
    yadd += y - yprev;
    xprev = x;
    yprev = y;
    repaint();
    e.consume();
    public void mouseMoved(MouseEvent e) {
         //method selects a random image for the child to draw on or colour in
         public void backGroundImage(){
    public void paint(Graphics g) {
    g.drawImage(backimage, 0, 0, this);
    Rectangle r = getBounds();
    int hlines = r.height / 10;
    int vlines = r.width / 10;
    if (imgw < 0) {
    imgw = curimage.getWidth(this);
    imgh = curimage.getHeight(this);
    if (imgw < 0 || imgh < 0) {
    return;
    if (scalew < 0) {
    if (rotation == 0) {
    scalew = imgw;
    scaleh = imgh;
    } else {
    Rectangle rect = new Rectangle(0, 0, imgw, imgh);
    rotfilters[rotation].transformBBox(rect);
    xoff = rect.x;
    yoff = rect.y;
    scalew = rect.width;
    scaleh = rect.height;
    scalew = (int) (scalew * hmult);
    scaleh = (int) (scaleh * hmult);
    xoff = (imgw - scalew) / 2;
    yoff = (imgh - scaleh) / 2;
    if (imgw != scalew || imgh != scaleh) {
    g.drawImage(curimage, xadd + xoff, yadd + yoff,
    scalew, scaleh, this);
    } else {
    g.drawImage(curimage, xadd + xoff, yadd + yoff, this);
    static final long updateRate = 100;
    public synchronized boolean imageUpdate(Image img, Image bg0,int infoflags,
    int x, int y, int w, int h) {
    if (img != curimage) {
    return false;
    boolean ret = true;
    boolean dopaint = false;
    long updatetime = 0;
    if ((infoflags & WIDTH) != 0) {
    imgw = w;
    dopaint = true;
    if ((infoflags & HEIGHT) != 0) {
    imgh = h;
    dopaint = true;
    if ((infoflags & (FRAMEBITS | ALLBITS)) != 0) {
    dopaint = true;
    ret = false;
    } else if ((infoflags & SOMEBITS) != 0) {
    dopaint = true;
    updatetime = updateRate;
    if ((infoflags & ERROR) != 0) {
    ret = false;
    if (dopaint) {
    repaint(updatetime);
    return ret;
    public synchronized Image pickImage() {
    ImageProducer src = origimage.getSource();
    if (alpha != numalphas - 1) {
    ImageFilter imgf = alphafilters[alpha];
    if (imgf == null) {
    int alphaval = (alpha * 255) / (numalphas - 1);
    imgf = new AlphaFilter(alphaval);
    alphafilters[alpha] = imgf;
    src = new FilteredImageSource(src, imgf);
    if (rotation != 0) {
    RotateFilter imgf = rotfilters[rotation];
    if (imgf == null) {
    double angle = (2 * Math.PI * rotation) / numrotations;
    imgf = new RotateFilter(angle);
    rotfilters[rotation] = imgf;
    src = new FilteredImageSource(src, imgf);
    if (usefilter) {
    if (colorfilter == null) {
    colorfilter = new RedBlueSwapFilter();
    src = new FilteredImageSource(src, colorfilter);
    Image choice;
    if (src == origimage.getSource()) {
    choice = origimage;
    } else {
    choice = applet.createImage(src);
    if (curimage != choice) {
    if (curimage != null && curimage != origimage) {
    curimage.flush();
    curimage = choice;
    return choice;
    class RedBlueSwapFilter extends RGBImageFilter {
    public RedBlueSwapFilter() {
    canFilterIndexColorModel = true;
    public void setColorModel(ColorModel model) {
    if (model instanceof DirectColorModel) {
    DirectColorModel dcm = (DirectColorModel) model;
    int rm = dcm.getRedMask();
    int gm = dcm.getGreenMask();
    int bm = dcm.getBlueMask();
    int am = dcm.getAlphaMask();
    int bits = dcm.getPixelSize();
    dcm = new DirectColorModel(bits, bm, gm, rm, am);
    substituteColorModel(model, dcm);
    consumer.setColorModel(dcm);
    } else {
    super.setColorModel(model);
    public int filterRGB(int x, int y, int rgb)
    return ((rgb & 0xFF000000)) | ((rgb & 0xff00ff00)|((rgb & 0xff0000) >> 16)| ((rgb & 0xff) << 16)); //
    //return ((rgb & 0xff00ff00)|((rgb & 0xff0000) >> 16)| ((rgb & 0xff) << 16)); //
    class AlphaFilter extends RGBImageFilter {
    ColorModel origmodel;
    ColorModel newmodel;
    int alphaval;
    public AlphaFilter(int alpha) {
    alphaval = alpha;
    canFilterIndexColorModel = true;
    public int filterRGB(int x, int y, int rgb) {
    int alpha = (rgb >> 24) & 0xff;
    alpha = alpha * alphaval / 255;
    return ((rgb & 0x00ffffff) | (alpha << 24));
    //------------------------------- End of the code

Maybe you are looking for

  • My ID is from China but I want to use in America because I'm living there

    Please I want to use in america because I have to buy many movies in there but in China  there is no movies or TV shows. so please baging you... (I'm from Korea move to China and move to america) If you say OK I will send you my ID.

  • Installed Yosemite - audio line out no longer working

    After installing Yosemite, sound will only play from my Mac Pro's internal speakers. Opening Preferences > Sound and selecting Line Out has no effect. Why does the Line Out no longer work with Yosemite?

  • Hp pro 8600 error Paper detected does not match paper size or type selected .

    hp pro 8600 error "Paper detected does not match paper size or type selected" for Copies from tray one .  There has been no change in the paper always used in tray one.  Prints documents with no problem from Tray One with same paper.  Copies from Tra

  • Editing the properties of the closed captioning area.

    Is there a way to edit the properties of the closed captioning (CC) area.  I mean besides the number of lines and font type and size. For instance in a responsive design project the closed captioning runs under the X to close the CC window in the pho

  • Email configuration on n73

    hi, i was trying to configure e mail on my n73, but no success. i was using airtel network with mobile office. pls some one give the details for gmail, yahoo& rediff how to configure thanksin advance