MouseMoved - problem

Hi,
i've got a little problem concerning mouse handling:
Nothing happens when I check whether the mouse moves in a GlCanvas. Here the code:
@Override
    public void mouseEntered(MouseEvent e)
        super.mouseEntered(e);
        System.out.println("MOUSE ENTERED");
    @Override
    public void mouseMoved(MouseEvent e)
        super.mouseMoved(e);
        System.out.println("MOUSE MOVED");
...When I enter in the GLCanvas with my mouse cursor, it runs fine: "MOUSE ENTERED " is shown
but when i move the mouse in the GLCanvas, nothing happens. I think that's very strange^^
Do You have a solution?
thanks
christoph
Edited by: Fachmann on Feb 23, 2010 9:31 AM

public class Listener  implements GLEventListener, MouseMotionListener, MouseListenerIt's MouseListener and MouseMotionListener

Similar Messages

  • Robot mouseMove problem with other browser than IE

    Hi i'm using this code:
    Point mouseP = MouseInfo.getPointerInfo().getLocation();
    Robot robot = new Robot();
    robot.mouseMove(mouseP.x, mouseP.y - 200);in my applet. The security is ok and it work very well under internet explorer. My problem is because it very slow under Mozilla and don't seems to work under Firefox. I use the same java runtime with the sam applet version on the same computer. It seems to be the mouseMove function that act differently.
    Somebody have an answer?
    thx

    Hmm.... well, both those other browsers require the Java plug-in to run the applet anyway. So the browser shouldn't be an issue at all in whether it works or not. The plug-in's security manager settings, sure, but if you are sure that's not the problem... then I don't know.

  • MouseMove problem in JPanel

    Hello I am writing an applet and I am calling a class which extends JPanel.
    In the JPanel I am trying to create a rectangle (fillRect) which than I will be able to move using the method mouseMove().
    I have been able to draw the rectangle on the panel which is in the applet but i havent succeded in moving the rectangle with mouseMove().
    Could somebody please show me to implement the mouseMove correctly .

    Here's a sloppy sort of example for you. It could be vastly improved, but it shows you one example of using a MouseMotionAdapter to change the state of your JPanel subclass.
    Basically, you maintain a model - in this case, the location of your rectangle. When you get input from the mouse, you change the model appropriately. Then you need your view to be redrawn to show your new model. In this case, we just call repaint() and let Swing handle it. In other programs, you might have a loop continuously redrawing the view for you (but that's another story).
    Cheers,
    John
    package moop;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionAdapter;
    import javax.swing.JPanel;
    public class MyPanel extends JPanel  {
         /** the last known location of the corner of our rectangle  */
         private Point cornerPoint = new Point(0,0);
          * Constructor, giving us a chance to add a mouse motion listener.
         public MyPanel() {
              addMouseMotionListener(new MouseMotionAdapter() {
                    * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
                   public void mouseMoved(MouseEvent e) {
                        cornerPoint.x = e.getX() - 10;
                        cornerPoint.y = e.getY() - 10;
                        repaint();
          * Override the default method to draw a rectangle.
         public void paintComponent(Graphics g) {
              // let the superclass do it's stuff first
              super.paintComponent(g);          
              // draw a red rectangle
              g.setColor(Color.red);
              g.fillRect(cornerPoint.x, cornerPoint.y, 20, 20);
    }

  • Problems with detection of mousemovements

    Hello,
    I tried to use the mousemotionlistener in my japplet. I just copied it from a working JApplet, but no nothing works. On this moment i'm starting to thing that Java isn't that easy to program, as being said.
    Could someone please give me a working exameple were the event "MouseMoved" from the MouseMotionListener is triggered.
    Greetings Koen

    my code was:
    public class MoveObject extends JApplet
    implements ActionListener,MouseMotionListener
    public MoveObject()
    getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
    public void init()
    codeWin = new CodeWindow();
    commWindow = new CommentWindow();
    sList = new ShapeList(codeWin, commWindow);
    addBackButton = new JButton("Add Node to End");
    addBackButton.addActionListener(this);
    addBackButton.setToolTipText("To add a node to the end of the linked list");
    addFrontButton = new JButton("Add Node");
    addFrontButton.addActionListener(this);
    addFrontButton.setToolTipText("To add a node to the start of the linked list");
    insertButton = new JButton("Insert Node");
    insertButton.addActionListener(this);
    insertButton.setToolTipText("Select an arrow, then click this button to insert a node");
    removeSelectedButton = new JButton("Remove Selected Node");
    removeSelectedButton.addActionListener(this);
    removeSelectedButton.setToolTipText("Select a node, then click this button to remove it");
    clearTextArea = new JButton("Clear comments");
    clearTextArea.addActionListener(this);
    clearTextArea.setToolTipText("Clears the comment pane");
    resetButton = new JButton("Reset");
    resetButton.addActionListener(this);
    resetButton.setToolTipText("Clears the list");
    tidyButton = new JButton("Tidy Nodes");
    tidyButton.addActionListener(this);
    tidyButton.setToolTipText("Puts the nodes in a straight line");
    sList.addMouseListener(this);
    sList.addMouseMotionListener(this);
    JScrollPane jscrollpane = new JScrollPane(sList);
    jscrollpane.getVerticalScrollBar().setUnitIncrement(30);
    jscrollpane.getVerticalScrollBar().setBlockIncrement(30);
    jscrollpane.getHorizontalScrollBar().setUnitIncrement(30);
    jscrollpane.getHorizontalScrollBar().setBlockIncrement(30);
    sList.setPreferredSize(new Dimension(10000, 1000));
    jscrollpane.addMouseListener(this);
    jscrollpane.addMouseMotionListener(this);
    scrollCodePane = new JScrollPane(codeWin, 22, 32);
    scrollCodePane.getVerticalScrollBar().setUnitIncrement(20);
    scrollCodePane.getVerticalScrollBar().setBlockIncrement(20);
    codeWin.setScrollPane(scrollCodePane);
    scrollCommentPane = new JScrollPane(commWindow, 22, 31);
    scrollCommentPane.getVerticalScrollBar().setUnitIncrement(20);
    scrollCommentPane.getVerticalScrollBar().setBlockIncrement(20);
    commWindow.setScrollPane(scrollCommentPane);
    JSplitPane jsplitpane = new JSplitPane(1, scrollCodePane, scrollCommentPane);
    jsplitpane.setDividerLocation(670);
    JSplitPane jsplitpane1 = new JSplitPane(0, jscrollpane, jsplitpane);
    jsplitpane1.setDividerLocation(350);
    getContentPane().add(jsplitpane1, "Center");
    mainBar = new JToolBar();
    mainBar.setFloatable(false);
    mainBar.add(addFrontButton);
    mainBar.add(addBackButton);
    mainBar.add(insertButton);
    mainBar.add(removeSelectedButton);
    mainBar.add(tidyButton);
    mainBar.addSeparator();
    mainBar.add(clearTextArea);
    mainBar.add(resetButton);
    mainBar.addSeparator();
    getContentPane().add(mainBar, "North");
    public void actionPerformed(ActionEvent actionevent)
    if(!sList.threadsActive())
    if(actionevent.getSource() == addFrontButton)
    sList.addFrontNode();
    if(actionevent.getSource() == addBackButton)
    sList.animateAddNode();
    if(actionevent.getSource() == insertButton)
    sList.animateInsertNode();
    if(actionevent.getSource() == removeSelectedButton)
    sList.animateStartRemove();
    if(actionevent.getSource() == tidyButton)
    sList.tidyNodes();
    if(actionevent.getSource() == clearTextArea)
    commWindow.clear();
    if(actionevent.getSource() == resetButton)
    sList.resetList();
    repaint();
    public void mouseReleased(MouseEvent mouseevent)
    int i = mouseevent.getX();
    int j = mouseevent.getY();
    if(!sList.arrayEmpty() && !sList.threadsActive())
    sList.findObject(i, j);
    public void mousePressed(MouseEvent mouseevent)
    public void mouseDragged(MouseEvent mouseevent)
    public void mouseClicked(MouseEvent mouseevent)
    public void mouseEntered(MouseEvent mouseevent)
    public void mouseExited(MouseEvent mouseevent)
    public void mouseMoved(MouseEvent mouseevent)
    public JButton addBackButton;
    public JButton addFrontButton;
    public JButton insertButton;
    public JButton removeSelectedButton;
    public JButton clearTextArea;
    public JButton resetButton;
    public JButton tidyButton;
    public JToolBar mainBar;
    public JFrame frame;
    public JScrollPane scrollCodePane;
    public JScrollPane scrollCommentPane;
    public CodeWindow codeWin;
    public CommentWindow commWindow;
    public ShapeList sList;
    private int mdX;
    private int mdY;
    }

  • Problem with socket and object writing

    Hi,
    I programm this client/server app, the client has a point (graphic ) , the server has a point and when the mouse is moving it moves the point and the new position is send via the socket.
    The probleme is that i don't receive the good thing.
    When i display the coord of the point before sending it's good , but when receiving from the socket the coords are always the same ...
    i don't understand .
    Well , try and tell me ...
    Thx.

    oups, the program can be usefull ...
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class server_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    server s;
    public server_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p2=new point(50,50,new Color(0,0,255));
    p1=new point(200,200,new Color(255,0,0));
    s = new server(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    s.write_point(p1);
    repaint();
    public static void main(String args[])
         server_JFrame sjf = new server_JFrame();
    sjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         sjf.setTitle("server");
    sjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class server {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public server(point p,Container c)
    p_=p;
    c_=c;
    try
    ServerSocket server = new java.net.ServerSocket(80);
    System.out.println("attente d'un client");
    java.net.Socket client = server.accept();
    System.out.println("client accept�");
    Istream_ = new ObjectInputStream(client.getInputStream());
    Ostream_ = new ObjectOutputStream(client.getOutputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) { exception.printStackTrace(); }
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.applet.*;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    public class client_JFrame extends javax.swing.JFrame implements MouseListener,MouseMotionListener{
    point p1,p2;
    client c;
    public client_JFrame()
    this.setSize(600,400);
    addMouseListener(this);
    addMouseMotionListener(this);
    p1=new point(50,50,new Color(0,0,255));
    p2=new point(200,200,new Color(255,0,0));
    c = new client(p2,this);
    public void paint(Graphics g)
    super.paint(g);
    g.setColor(p1.get_color());
    g.fillOval(p1.get_x(), p1.get_y(),10,10);
    g.setColor(p2.get_color());
    g.fillOval(p2.get_x(), p2.get_y(),10,10);
    public void mouseClicked(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e)
    p1.set_x(e.getX());
    p1.set_y(e.getY());
    c.write_point(p1);
    repaint();
    public static void main(String args[])
         client_JFrame cjf = new client_JFrame();
    cjf.setDefaultCloseOperation(EXIT_ON_CLOSE);
         cjf.setTitle("client");
    cjf.show();
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.awt.*;
    public class client {
    point p_;
    Container c_;
    ObjectInputStream Istream_;
    ObjectOutputStream Ostream_;
    public client(point p,Container c)
    p_=p;
    c_=c;
    try
    ipJDialog ipjd = new ipJDialog();
    String ip = ipjd.getvalue();
    Socket socket = new Socket(ip,80);
    System.out.println("connection avec serveur reussi");
    Ostream_ = new ObjectOutputStream(socket.getOutputStream());
    Istream_ = new ObjectInputStream(socket.getInputStream());
    ThreadRead tr = new ThreadRead(Istream_,p_,c_);
    catch (Exception exception) {*exception.printStackTrace();*/System.out.println("connection avec serveur echou�");}
    public void write_point(point p)
    try
    System.out.print("x="+p.get_x());
    System.out.println(" y="+p.get_y());
    Ostream_.flush();
    Ostream_.writeObject(p);
    Ostream_.flush();
    catch (Exception exception) {exception.printStackTrace();}
    import java.io.Serializable;
    import java.awt.*;
    public class point implements Serializable{
    private int x_;
    private int y_;
    private Color c_;
    public point(int x, int y, Color c) {
    x_=x;
    y_=y;
    c_=c;
    public int get_x() { return x_ ; }
    public int get_y() { return y_ ; }
    public void set_x(int x) { x_=x ; }
    public void set_y(int y) { y_=y ; }
    public Color get_color() { return c_ ; }
    }

  • Problem with line clipping.

    Hi,
    In my applications there are various shapes and there is a Line Handle
    associated with every shape. That line handle's initial point is center of
    the shape and the end point is outside the shape.
    I am using g2d.clip() method to clip the line inside the shape so that
    Line shouldn't be visible from the center but from surface of the shape.
    My problem is that the line sometimes isn't visible ,specially if center point's x or y is same as line end points x or y.
    This is because of are clipping .
    Can anybody tell me how to negate this problem?
    I am posting small program to demonstrate the issue;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.Area;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class EllipseDraw
    extends JPanel
    implements MouseMotionListener
         Line2D line = new Line2D.Double(new Point2D.Double(75, 75), new Point2D.Double(150, 60));
         Ellipse2D ellipse = new Ellipse2D.Double(50, 50, 50, 50);
         EllipseDraw()
              this.addMouseMotionListener(this);
         public static void main(String[] args)
              EllipseDraw ellipseDraw = new EllipseDraw();
              ellipseDraw.setBorder(BorderFactory.createRaisedBevelBorder());
              JFrame frame = new JFrame();
              frame.getContentPane().add(ellipseDraw);
              frame.setSize(300, 300);
              frame.setVisible(true);
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              g2d.setStroke(new BasicStroke(2));
              Map renderHints = new HashMap();
              renderHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              renderHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
              g2d.setRenderingHints(renderHints);
              g2d.setPaint(Color.red);
              Area area = null;
              g2d.draw(ellipse);
              Shape currentClip = g2d.getClip();
              if (!ellipse.contains(line.getP2()))
                   area = new Area(line.getBounds2D());
                   area.subtract(new Area(ellipse));
                   g2d.clip(area);
                   g2d.draw(line);
                   g2d.setClip(currentClip);
              if (area != null)
                   g2d.draw(area);
         public void mouseDragged(MouseEvent e)
         public void mouseMoved(MouseEvent e)
              line.setLine(line.getP1(), e.getPoint());
              this.invalidate();
              this.repaint();
    }

    I solved the problem by growing the area .
    if (!ellipse.contains(line.getP2()))
                   Rectangle rect = line.getBounds();
                   rect.grow(10, 10);
                   area = new Area(rect);
                   area.subtract(new Area(ellipse));
                   g2d.clip(area);
                   g2d.draw(line);
                   g2d.setClip(currentClip);
              }

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java™ Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Is there any problems in IE if using RMI.?

    Hello buddies,
    this is my 3rd attempt to get answer. before it i tried 2 times but didn't get answered.
    actually i m making a chat application. in that there is a canvas on which we can draw something and send it to all users. i make an applet and from within the applet i m calling a frame. all this awt components like canvas and buttons etc. displays in the frame. applet is just a platform do call the frame. i m using RMI to do the chat. i tried to run it first in appletviewer and it works fine. but when i tried to run in IE from <applet> tag no frame is displays. i am trying to solve it from last 20 days but still unsolved. here is the code if anybody wishes to try it.
    // clinet frame...
    import java.rmi.*;
    import java.rmi.server.*;
    import canvas.Drawer;
    import java.awt.*;
    import java.applet.*;
    import java.applet.Applet;
    import java.awt.event.*;
    import java.util.*;
    import ru.zhuk.graphics.*;
    /*<applet code="ChatClient" width=600 height=300>
    </applet>
    public class ChatClient extends Frame implements IChatClient,ActionListener,MouseListener,MouseMotionListener
         // GLOBAL VARIABLES USED IN THE PROGRAMME...
         boolean flag=false;
         int n;
         String str="";
         String Coord=null;
         IChatService service=null;
         FrameApplet fa=null;
         TextField servername,serverport,username;
         Button connect,disconnect;
         TextField message;
         Button send,sendText;
         TextArea fromserver;
         int i=0,j=0;
         int x[] = new int[1000];
         int y[] = new int[1000];
         Drawer canvas;
         boolean connected=false;
         String title,user="";
         // Class Members //
         public ChatClient()
         public ChatClient(String str)
              super(str);
              setBounds(50,20,600,450);
              setLayout(new FlowLayout(FlowLayout.CENTER,45,10));
              title=str;
              setStatus();
              // Create controls //
              add(new Label("Chat Server Name : "));
              servername=new TextField(20);
              add(servername);
              servername.setText("localhost");
              add(new Label("Chat Server Port : "));
              serverport=new TextField(20);
              add(serverport);
              serverport.setText("900");
              add(new Label("Your User Name : "));
              username=new TextField(20);
              add(username);
              username.setText("Umesh");
              connect=new Button("Connect");
              connect.addActionListener(this);
              add(connect);
              disconnect=new Button("Disconnect");
              disconnect.addActionListener(this);
              add(disconnect);
              message=new TextField(30);
              add(message);
              sendText=new Button("Send Text");
              sendText.addActionListener(this);
              add(sendText);
              fromserver=new TextArea(10,50);
              add(fromserver);
              fromserver.setEditable(false);
    canvas = new Drawer();
              canvas.setSize(250,250);
              canvas.setBackground(Color.cyan);
              add(canvas);
              canvas.addMouseListener(this);
              canvas.addMouseMotionListener(this);
              send=new Button("Send");
              send.addActionListener(this);
              add(send);
              try
                   UnicastRemoteObject.exportObject(this);
              catch(Exception e)
              setVisible(true);
              for(j=0;j<1000;j++)
                   x[j]=0;
                   y[j]=0;
              Coord = new String();
              Coord = "";
    //          fa=new FrameApplet();
         public void mousePressed(MouseEvent me){}
         public void mouseReleased(MouseEvent me)
              Coord = Coord + "r";
         public void mouseClicked(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public void mouseDragged(MouseEvent me)
              if (Coord == "")
                   Coord = me.getX() + "," + me.getY();
              else
                   Coord = Coord + " " + me.getX() + "," + me.getY();
         public void mouseMoved(MouseEvent me){}
         // RMI connection //
         private void connect()
              try
                   service = (IChatService)Naming.lookup("rmi://pcname/ChatService");
                   service.addClient(this);
                   connected=true;
                   setStatus();
                   user=username.getText();
                   Coord = "";
              catch(Exception e)
                   fromserver.append("Error Connecting ...\n" + e);
                   System.out.println(e);
                   connected=false;
                   setStatus();
                   service=null;
         private void disconnect()
              try
                   if(service==null)
                        return;
                   service.removeClient(this);
                   service=null;
              catch(Exception e)
                   fromserver.append("Error Connecting ...\n");
              finally
                   connected=false;
                   setStatus();
         private void setStatus()
              if(connected)
                   setTitle(title+" : Connected");
              else
                   setTitle(title+" : Not Connected");
         // IChatClient methods //
         public String getName()
              return user;
         public void sendMessage(String msg)
              fromserver.append(msg+"\n");
         public void SendCanvasObject(String str)
              this.str = str;
              fromserver.append(str + "\n");
              Graphics g = canvas.getGraphics();
              paint(g);
         // Actionlistener //
         public void actionPerformed(ActionEvent e)
              if(e.getSource()==connect)
                   connect();
                   if(connected)
                        servername.setEnabled(false);
                        serverport.setEnabled(false);
                        username.setEnabled(false);
                        connect.setEnabled(false);
                        Coord = "";
              else
              if(e.getSource()==disconnect)
                   disconnect();
                   servername.setEnabled(true);
                   serverport.setEnabled(true);
                   username.setEnabled(true);
                   connect.setEnabled(true);
              else
              if(e.getSource()==send)
                   flag = true;
                   if(service==null)
                        return;
                   try
                        fromserver.append("Sending an image...\n");
                        service.SendCanvasObject(this,Coord);
                        i=0;
                        for(j=0;j<1000;j++)
                             x[j]=0;
                             y[j]=0;
                        Coord = "";
                        fromserver.append("\n" + "Image Sent...");
                   catch(RemoteException re)
                        fromserver.append("Error Sending Message ...\n" + re);
                   catch(Exception ee)
                        fromserver.append("Error Sending Message ...\n" + ee);
              else
              if(e.getSource()==sendText)
                   if(service==null)
                        return;
                   try
                        service.sendMessage(this,message.getText());
                        message.setText("");
                   catch(RemoteException exp)
                        fromserver.append("Remote Error Sending Message ...\n" + exp);
                   catch(Exception ee)
                        fromserver.append("Error Sending Message ...\n" + ee);
         public void paint(Graphics g)
              if(flag==true)
                   i=0;
                   StringTokenizer stoken = new StringTokenizer(str,"r");
                   String strin = "";
                   while(stoken.hasMoreTokens())
                        strin = stoken.nextToken();
                        fromserver.append("\n" + strin + "\n");
                        StringTokenizer stoken1 = new StringTokenizer(strin," ");
                        String strin1 = "";
                        j=0;
                        while(stoken1.hasMoreTokens())
                             strin1 = stoken1.nextToken();
                             fromserver.append("\n" + strin1 + "\n");
                             x[j]=Integer.parseInt(strin1.substring(0,strin1.indexOf(",")));
                             y[j]=Integer.parseInt(strin1.substring(strin1.indexOf(",")+1,strin1.length()));
                             j++;
                        for(int k=0;k<j-1;k++)
                             g.drawLine(x[k],y[k],x[k+1],y[k+1]);     
                   i++;
    import java.rmi.*;
    import java.rmi.server.*;
    import canvas.Drawer;
    import java.util.*;
    import ru.zhuk.graphics.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    public class FrameApplet extends Applet implements ActionListener
         ChatClient f;
         public void init()
              Button b = new Button("Start Chat");
              b.addActionListener(this);
              add(b);
         public void actionPerformed(ActionEvent ae)
              f=new ChatClient("Chat");
              f.show();
              f.setSize(400,400);
    here is html file which i calls from IE
    <html>
    <title>Micky Chat</title>
    <body>
    <br>
    <br>
    <center>
    <applet code="FrameApplet.class" width=200 height=200>
    </applet>
    </center>
    </body>
    </html>
    and at last a shocking thing is it is runs in Netscape displaying frames but not calling paint method.
    pls. help me
    thanks a lot
    umesh

    Hi Umesh!
    Sorry that I cannot be too concrete about that since it has to be centuries ago when I fell over this problem.
    As far as I can remember, the JDK provided by MS has no RMI built-in. These was probably one of the main reasons why Sun sued Microsoft concering its handling of Java.
    Afterwards MS released a path for its Java Runtime that included RMI support, but AFAIK they never included it in the standard package. So much luck when searching for the ZIP! (-;
    A little bit of googling might help, e.g.:
    http://groups.google.com/groups?hl=de&lr=&ie=UTF-8&oe=UTF-8&threadm=37f8ddf6.4532124%40news.online.no&rnum=17&prev=/groups%3Fq%3Dmicrosoft%2Bjvm%2Brmi%2Bsupport%26start%3D10%26hl%3Dde%26lr%3D%26ie%3DUTF-8%26oe%3DUTF-8%26selm%3D37f8ddf6.4532124%2540news.online.no%26rnum%3D17
    cheers,
    kdi

  • Having a problem saving the graphics on a canvas.

    I'm having a problem saving graphics on a canvas. It draws on the canvas but when another window comes up the graphics disappear. I put in a method to take the graphics on the canvas and repaint it with the graphics. But this comes up blank. So I don't know why this is happening. It is probably the paint method but I don't know why. If anyone has any ideas could you please respond because I have had this problem for ages now and it's driving me mad and I have to get this finished or I'm going to be a lot of trouble. I'll show you the code for the class I am concerned with. It is long but most of it can be disregarded. The only parts which are relevent are the paint method and where the drawline e.t.c are called which is in the mouse release
    package com.project.CSSE4;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.ImageFilter;
    import java.awt.image.CropImageFilter;
    import java.awt.image.FilteredImageSource;
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import java.sql.*;
    public class CanvasOnly extends JPanel
           implements MouseListener, MouseMotionListener
       public static final int line = 1;
       public static final int freehand = 2;
       public static final int text = 3;
       public static final int mode_paint = 0;
       public static final int mode_xor = 1;
       public Color drawColor;
       public int drawThickness = 1;
       public int drawType = 0;
       public boolean fill = false;
       private boolean dragging = false;
       public int oldx = 0;
       public int oldy = 0;
       private int rectangleWidth;
       private int rectangleHeight;
       private tempLine draftLine;
       private tempText draftText;
       public Canvas pad;
       public static final Font defaultFont =
         new Font("Helvetica", Font.BOLD, 14);
       protected boolean floatingText = false;
       boolean showingPicture;
       protected Image offScreen;
       public JTextArea coor;
       public JButton writeIn;
       Connection connection;
       String codeLine;
       int x = 0;
       int y = 0;
       public CanvasOnly()
           try
                Class.forName("com.mysql.jdbc.Driver").newInstance();
           }catch( Exception e)
                 System.err.println("Unable to find and load driver");
                 System.exit(1);
            pad = new Canvas();
            pad.setBackground(Color.white);
            pad.setVisible(true);
            pad.setSize(400, 400);
           coor = new JTextArea(15, 15);
           writeIn = new JButton("load TExt");
           writeIn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent event1)
                     try
                   Statement statement = connection.createStatement();
                   ResultSet rs = statement.executeQuery("SELECT * FROM submit WHERE file_name = 'cmd.java'");
                   rs.next();
                   String one1 = rs.getString("student_id");
                   //System.out.println("one1 :" + one1);
                   String two1 = rs.getString("file_name");
                   //System.out.println("two1 : " + two1);
                    InputStream textStream = rs.getAsciiStream("file");
                    BufferedReader textReader = new BufferedReader(
                                     new InputStreamReader(textStream));
                    codeLine = textReader.readLine();
                    x = 0;
                    y = -12;
                    while(codeLine != null)
                        y = y + 12;
                        //fileText.append( line + "\n");
                        //canvasPad.drawTheString(line, x, y);
                        drawText(Color.black, x, y, codeLine, mode_paint);
                        codeLine = textReader.readLine();
                     textReader.close();
                    pad.setSize(400, y);
                    Timestamp three1 = rs.getTimestamp("ts");
                    //System.out.println(three1);
                    textReader.close();
                    rs.close();
              }catch (SQLException e)
                System.err.println(e);
              catch(IOException ioX)
                System.err.println(ioX);
            //setSize(300,300);
            drawColor = Color.black;
            pad.addMouseListener(this);
         pad.addMouseMotionListener(this);
         offScreen = null;
       public Image getContents()
         // Returns the contents of the canvas as an Image.  Only returns
         // the portion which is actually showing on the screen
         // If the thing showing on the canvas is a picture, just send back
         // the picture
         if (showingPicture)
             return (offScreen);
         ImageFilter filter =
             new CropImageFilter(0, 0, getWidth(), getHeight());
         Image newImage =
             createImage(new FilteredImageSource(offScreen.getSource(),
                                  filter));
         return(newImage);
        public void setImage(Image theImage)
         // Fit it to the canvas
         offScreen = theImage;
         repaint();
         showingPicture = true;
        synchronized public void paint(Graphics g)
         int width = 0;
         int height = 0;
         //The images are stored on an off screen buffer.
            //offScreen is the image declared at top
         if (offScreen != null)
                  //intislise the widt and heigth depending on if showingpicture is true
              if (!showingPicture)
                       width = offScreen.getWidth(this);
                       height = offScreen.getHeight(this);
                   //width = getWidth(this);
                   //height = getHeight(this);  //offScreen
              else
                   //width = pad.getSize().width;
                   //height = getSize().height;
                   width = pad.getWidth();
                   //width = getSize().width;
                   height = pad.getHeight();
                   //height = getSize().height;
                    //Draws as much of the specified image as has already
                    //been scaled to fit inside the specified rectangle
                    //The "this" is An asynchronous update interface for receiving
                    //notifications about Image information as the Image is constructed
    //This is causing problems
              g.drawImage(offScreen, 0, 0, width, height, pad);
              g.dispose();
         //clear the canvas with this method
        synchronized public void clear()
         // The maximum size of the usable drawing canvas, for now, will be
         // 1024x768
         offScreen = createImage(1024, 768);
         //Creates an off-screen drawable image to be used for double buffering
         pad.setBackground(Color.white);
         //Set the showingPicture to false for paint method
         showingPicture = false;
         repaint();
         synchronized public void drawLine(Color color, int startx, int starty,
                              int endx, int endy, int thickness,
                              int mode)
         int dx, dy;
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         //if image is not intialised to null
         //the getGraphics is used for freehand drawing
         //Image.getGraphics() is often used for double buffering by rendering
            //into an offscreen buffer.
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
            //mode is put into the method and XOR is final and equal to 1
         if (mode == this.mode_xor)
                  //calls the setXOR mode for g1 and g2
                  //Sets the paint mode of this graphics context to alternate
                    //between this graphics context's current color and the
                    //new specified color.
              g1.setXORMode(Color.white);//This will
              g2.setXORMode(Color.white);
         else
                  //Sets this graphics context's current color to the
                    //specified color
              g1.setColor(color);
              g2.setColor(color);
         if (endx > startx)
             dx = (endx - startx);
         else
             dx = (startx - endx);
         if (endy > starty)
             dy = (endy - starty);
         else
             dy = (starty - endy);
         if (dx >= dy)
              starty -= (thickness / 2);
              endy -= (thickness / 2);
         else
              startx -= (thickness / 2);
              endx -= (thickness / 2);
         for (int count = 0; count < thickness; count ++)
              g1.drawLine(startx, starty, endx, endy);
              g2.drawLine(startx, starty, endx, endy);
              if (dx >= dy)
                  { starty++; endy++; }
              else
                  { startx++; endx++; }
            //Disposes of this graphics context and releases any system
            //resources that it is using.
         g1.dispose();
         g2.dispose();
         //This method is not causing trouble
         synchronized public void drawText(Color color, int x, int y,
                String text, int mode)
         Graphics g1 = pad.getGraphics();
         Graphics g2;
         if (offScreen != null)
             g2 = offScreen.getGraphics();
         else
             g2 = g1;
         if (mode == this.mode_xor)
              g1.setXORMode(Color.white);
              g2.setXORMode(Color.white);
         else
              g1.setColor(color);
              g2.setColor(color);
         g1.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g2.setFont(new Font("Times Roman", Font.PLAIN, 10));
         g1.drawString(text, x, y);
         g2.drawString(text, x, y);
         g1.dispose();
         g2.dispose();
          //connect to database
      public void connectToDB()
        try
           connection = DriverManager.getConnection(
           "jdbc:mysql://localhost/submissions?user=root&password=football");
                     //may have to load in a username and password
                                                     //code "?user=spider&password=spider"
        }catch(SQLException connectException)
           System.out.println("Unable to connect to db");
           System.exit(1);
      //use this method to instatiate connectToDB method
      public void init()
           connectToDB();
        protected void floatText(String text)
         draftText = new tempText(this.drawColor,
                            this.oldx,
                            this.oldy,
                                        text);
         this.floatingText = true;
        //nothing happens when the mouse is clicked
        public void mouseClicked(MouseEvent e)
        //When the mouse cursor enters the canvas make it the two
        //straigth lines type
        public void mouseEntered(MouseEvent e)
         pad.setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
        //When mouse exits canvas set to default type
        public void mouseExited(MouseEvent E)
         pad.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        //used for creating the shapes and positioning thetext
        public void mousePressed(MouseEvent e)
             // Save the coordinates of the mouse being pressed
         oldx = e.getX();
         oldy = e.getY();
         // If we are doing lines, rectangles, or ovals, we will show
         // draft lines to suggest the final shape of the object
         //Draw type is a publc int which can be changed
         if (drawType == this.line)
            draftLine = new tempLine(drawColor, oldx, oldy, oldx,
                                 oldy, drawThickness);
            // Set the draw mode to XOR and draw it.
            drawLine(draftLine.color, draftLine.startx,
            draftLine.starty, draftLine.endx,
            draftLine.endy, drawThickness, this.mode_xor);
        //mouse listener for when the mouse button is released
        public void mouseReleased(MouseEvent e)
             if (drawType == this.line)
              // Erase the draft line
              drawLine(draftLine.color, draftLine.startx, draftLine.starty,
                    draftLine.endx, draftLine.endy, drawThickness,
                    this.mode_xor);
              // Add the real line to the canvas
              //When the imput changes to "mode_paint" it is drawen
              //on the canvas
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              dragging = false;
         else if (drawType == this.text)
              if (floatingText)
                   // The user wants to place the text (s)he created.
                   // Erase the old draft text
                   drawText(drawColor, draftText.x, draftText.y,
                                            draftText.text, this.mode_xor);
                       String str = Integer.toString(e.getX());
                       String str1  = Integer.toString(e.getY());
                       coor.append(str + " " + str1 + "\n");
                   // Set the new coordinates
                   draftText.x = e.getX();
                   draftText.y = e.getY();
                   // Draw the permanent text
                   drawText(drawColor, draftText.x, draftText.y,
                         draftText.text, this.mode_paint);
                   floatingText = false;
         public void mouseDragged(MouseEvent e)
            if (drawType == this.freehand)
              drawLine(drawColor, oldx, oldy, e.getX(), e.getY(),
                    drawThickness, this.mode_paint);
              oldx = e.getX();
              oldy = e.getY();
         else
             dragging = true;
         if (drawType == this.line)
            // Erase the old draft line
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
            // Draw the new draft line
            draftLine.endx = e.getX();
            draftLine.endy = e.getY();
            drawLine(draftLine.color, draftLine.startx, draftLine.starty,
              draftLine.endx, draftLine.endy, drawThickness,
              this.mode_xor);
         public void mouseMoved(MouseEvent e)
             if (floatingText)
              // When the user has entered some text to place on the
              // canvas, it remains sticky with the cursor until another
              // click is entered to place it.
              // Erase the old draft text
              drawText(drawColor, draftText.x, draftText.y,
                                draftText.text, this.mode_xor);
              // Set the new coordinates
              draftText.x = e.getX();
              draftText.y = e.getY();
              // Draw the new floating text
              drawText(drawColor, draftText.x, draftText.y,
                        draftText.text, this.mode_xor);
         //declare  a class for the line shown before the is as wanted
        class tempLine
         public Color color;
         public int startx;
         public int starty;
         public int endx;
         public int endy;
         public int thickness;
         public tempLine(Color mycolor, int mystartx, int mystarty,
                      int myendx, int myendy, int mythickness)
             color = mycolor;
             startx = mystartx;
             starty = mystarty;
             endx = myendx;
             endy = myendy;
             thickness = mythickness;
        class tempText
         public Color color;
         public int x;
         public int y;
         public String text;
         public tempText(Color mycolor, int myx, int myy, String mytext)
             color = mycolor;
             x = myx;
             y = myy;
             text = mytext;
    }

    http://www.java2s.com/ExampleCode/2D-Graphics/DemonstratingUseoftheImageIOLibrary.htm

  • JTable problem...can anybody help me...

    hi i have try out some jtable program. I have done some alteration to the table that it can resize row and column via the gridline. but it seems that when i'm resizing through the gridline, the row header did not resize. I sense that the row header not syncronizing with the main table. So when i'm tried to resize, the row header didn't
    can you solve my problem...
    //the main program
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test {     public static void main(String[] args)
         //row headers:     
         String[][] rowHeaders = {{"Alpha"},{"Beta"}, {"Gamma"}};
         JTable leftTable = new JTable(rowHeaders, new Object[]{""});
         leftTable.setDefaultRenderer(
              Object.class, leftTable.getTableHeader().getDefaultRenderer());
         leftTable.setPreferredScrollableViewportSize(new Dimension(50,100));      
         //main table:
         Object[][] sampleData = {{"Homer", "Simpson"},{"Seymour","Skinner"},{"Ned","Flanders"}};
         JTable mainTable = new JTable(sampleData, new Object[]{"",""});
         //scroll pane:
         JScrollPane sp = new JScrollPane(
              mainTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);     
              sp.setRowHeaderView(leftTable);          
              sp.setColumnHeaderView(null);      
         new TableColumnResizer(mainTable);
         new TableRowResizer(mainTable); 
         //frame:
         final JFrame f = new JFrame("Test");
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.getContentPane().add(sp);     
         f.pack();
         SwingUtilities.invokeLater(new Runnable(){
                   public void run(){     f.setLocationRelativeTo(null);
                                       f.setVisible(true);               }          });     
    }This the TableColumnResizer.java
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import java.awt.event.*;
    public class TableColumnResizer extends MouseInputAdapter
        public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR);
        private int mouseXOffset;
        private Cursor otherCursor = resizeCursor;
        private JTable table;
        public TableColumnResizer(JTable table){
            this.table = table;
            table.addMouseListener(this);
            table.addMouseMotionListener(this);
        private boolean canResize(TableColumn column){
            return column != null
                    && table.getTableHeader().getResizingAllowed()
                    && column.getResizable();
        private TableColumn getResizingColumn(Point p){
            return getResizingColumn(p, table.columnAtPoint(p));
        private TableColumn getResizingColumn(Point p, int column){
            if(column == -1){
                return null;
            int row = table.rowAtPoint(p);
            if(row==-1)
                return null;
            Rectangle r = table.getCellRect(row, column, true);
            r.grow( -3, 0);
            if(r.contains(p))
                return null;
            int midPoint = r.x + r.width / 2;
            int columnIndex;
            if(table.getTableHeader().getComponentOrientation().isLeftToRight())
                columnIndex = (p.x < midPoint) ? column - 1 : column;
            else
                columnIndex = (p.x < midPoint) ? column : column - 1;
            if(columnIndex == -1)
                return null;
            return table.getTableHeader().getColumnModel().getColumn(columnIndex);
        public void mousePressed(MouseEvent e){
            table.getTableHeader().setDraggedColumn(null);
            table.getTableHeader().setResizingColumn(null);
            table.getTableHeader().setDraggedDistance(0);
            Point p = e.getPoint();
            // First find which header cell was hit
            int index = table.columnAtPoint(p);
            if(index==-1)
                return;
            // The last 3 pixels + 3 pixels of next column are for resizing
            TableColumn resizingColumn = getResizingColumn(p, index);
            if(!canResize(resizingColumn))
                return;
            table.getTableHeader().setResizingColumn(resizingColumn);
            if(table.getTableHeader().getComponentOrientation().isLeftToRight())
                mouseXOffset = p.x - resizingColumn.getWidth();
            else
                mouseXOffset = p.x + resizingColumn.getWidth();
        private void swapCursor(){
            Cursor tmp = table.getCursor();
            table.setCursor(otherCursor);
            otherCursor = tmp;
        public void mouseMoved(MouseEvent e){
            if(canResize(getResizingColumn(e.getPoint()))
               != (table.getCursor() == resizeCursor)){
                swapCursor();
        public void mouseDragged(MouseEvent e){
            int mouseX = e.getX();
            TableColumn resizingColumn = table.getTableHeader().getResizingColumn();
            boolean headerLeftToRight =
                    table.getTableHeader().getComponentOrientation().isLeftToRight();
            if(resizingColumn != null){
                int oldWidth = resizingColumn.getWidth();
                int newWidth;
                if(headerLeftToRight){
                    newWidth = mouseX - mouseXOffset;
                } else{
                    newWidth = mouseXOffset - mouseX;
                resizingColumn.setWidth(newWidth);
                Container container;
                if((table.getTableHeader().getParent() == null)
                   || ((container = table.getTableHeader().getParent().getParent()) == null)
                                    || !(container instanceof JScrollPane)){
                    return;
                if(!container.getComponentOrientation().isLeftToRight()
                   && !headerLeftToRight){
                    if(table != null){
                        JViewport viewport = ((JScrollPane)container).getViewport();
                        int viewportWidth = viewport.getWidth();
                        int diff = newWidth - oldWidth;
                        int newHeaderWidth = table.getWidth() + diff;
                        /* Resize a table */
                        Dimension tableSize = table.getSize();
                        tableSize.width += diff;
                        table.setSize(tableSize);
                         * If this table is in AUTO_RESIZE_OFF mode and has a horizontal
                         * scrollbar, we need to update a view's position.
                        if((newHeaderWidth >= viewportWidth)
                           && (table.getAutoResizeMode() == JTable.AUTO_RESIZE_OFF)){
                            Point p = viewport.getViewPosition();
                            p.x =
                                    Math.max(0, Math.min(newHeaderWidth - viewportWidth, p.x + diff));
                            viewport.setViewPosition(p);
                            /* Update the original X offset value. */
                            mouseXOffset += diff;
        public void mouseReleased(MouseEvent e){
            table.getTableHeader().setResizingColumn(null);
            table.getTableHeader().setDraggedColumn(null);
    } This is TableRowResizer.java
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.MouseInputAdapter;
    import java.awt.*;
    import java.awt.event.MouseEvent;
    public class TableRowResizer extends MouseInputAdapter
        public static Cursor resizeCursor = Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR);
        private int mouseYOffset, resizingRow;
        private Cursor otherCursor = resizeCursor;
        private JTable table;
        public TableRowResizer(JTable table){
            this.table = table;
            table.addMouseListener(this);
            table.addMouseMotionListener(this);
        private int getResizingRow(Point p){
            return getResizingRow(p, table.rowAtPoint(p));
        private int getResizingRow(Point p, int row){
            if(row == -1){
                return -1;
            int col = table.columnAtPoint(p);
            if(col==-1)
                return -1;
            Rectangle r = table.getCellRect(row, col, true);
            r.grow(0, -3);
            if(r.contains(p))
                return -1;
            int midPoint = r.y + r.height / 2;
            int rowIndex = (p.y < midPoint) ? row - 1 : row;
            return rowIndex;
        public void mousePressed(MouseEvent e){
            Point p = e.getPoint();
            resizingRow = getResizingRow(p);
            mouseYOffset = p.y - table.getRowHeight(resizingRow);
        private void swapCursor(){
            Cursor tmp = table.getCursor();
            table.setCursor(otherCursor);
            otherCursor = tmp;
        public void mouseMoved(MouseEvent e){
            if((getResizingRow(e.getPoint())>=0)
               != (table.getCursor() == resizeCursor)){
                swapCursor();
        public void mouseDragged(MouseEvent e){
            int mouseY = e.getY();
            if(resizingRow >= 0){
                int newHeight = mouseY - mouseYOffset;
                if(newHeight > 0)
                    table.setRowHeight(resizingRow, newHeight);
    }

    cross-post: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=755250

  • Can anybody help me in fixing the problem ? of JTable ( CODE GIVEN )

    My problem is
    1)when i select the combo box (2nd column) through keyboard the selected item is not visible in the cell
    2) i need to press TAB key twice to go to next cell .
    3) also before editing i need to press a key to start editing (caret visible) HELP ME
    CODE CAN BE RUN TO SEE WHAT I MEANT
    <code>
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import java.text.*;
    public class BaseTable
    public JScrollPane scrollPane;
         public JTable table;
         public int totalRows;
         public int i,numRows,numCols;
         public TableModel model;
         public int rowCount;
         public JComboBox box;
    public BaseTable()
              String[] items=new String[]{"item1","jItem2","kItem3","Item4","Item5","Item6"};
              String[] columns = {"Column1","Column2","Column3","Column4","Column5","Column6","Column7","Column8","Column9"};
              box=new JComboBox(items);
              box.setEditable(true);
    DefaultTableModel baseModel=new DefaultTableModel();
              baseModel.setColumnIdentifiers(columns);
    table = new JTable(baseModel)
                   protected void processKeyEvent(KeyEvent e)
                        if ( e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() != e.VK_TAB)
                             int column = table.getSelectedColumn();
                             int row = table.getSelectedRow();
                             Rectangle r = getCellRect(row, column, false);
                             Point p = new Point( r.x, r.y );
                             SwingUtilities.convertPointToScreen(p, table);
                             try
                                  System.out.println("PROCESS KEY EVENT Typing"+e.getKeyCode());
                                  Robot robot = new Robot();
                                  robot.mouseMove(p.x, p.y );
                                  robot.mousePress(InputEvent.BUTTON1_MASK);
                                  robot.mouseRelease(InputEvent.BUTTON1_MASK);
                                  robot.mouseMove(0, 0 );
                             catch (Exception e2) {}
                        else
                             System.out.println("PROCESS KEY EVENT IN ELSE");
                             if(e.getKeyCode() == e.VK_TAB && table.isEditing())
                                  ((DefaultCellEditor)table.getCellEditor()).stopCellEditing();
                             else
                                  super.processKeyEvent(e);
    Vector vectorRow = new Vector();
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              vectorRow.addElement("");
              TableCellEditor tableCellEditor_comboBox = new MyCustomTableCellEditor(box,this);
              table.getColumnModel().getColumn(1).setCellEditor(tableCellEditor_comboBox);
              ((DefaultTableModel)table.getModel()).addRow(vectorRow);
              rowCount = table.getRowCount();
              ((DefaultTableModel)table.getModel()).fireTableRowsInserted(rowCount,rowCount);
              scrollPane = new JScrollPane(table);
              scrollPane.setForeground(Color.white);
              rowCount = table.getRowCount();
    numCols = table.getColumnCount();
    public class MyCustomTableCellEditor extends DefaultCellEditor
                   JTable table=null;
                   BaseTable baseTable=null;
                   JComboBox box=null;
                   MyCustomTableCellEditor(JComboBox editorComponent,BaseTable baseTable)
                        super(editorComponent);
                        this.table=baseTable.table;
                        this.baseTable=baseTable;
                        setClickCountToStart(0);
                   public Component getTableCellEditorComponent(
                        JTable table,
                        Object value,
                        boolean isSelected,
                        int row,
                        int column)
                             super.getTableCellEditorComponent(table,value,isSelected,row,column);
                             box=(JComboBox)getComponent();
                             box.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
                             return box;
         public static void main(String s1[])
              BaseTable t=new BaseTable();
              JFrame f=new JFrame();
              f.getContentPane().add(t.scrollPane);
              f.setSize(800,200);
              f.setVisible(true);
    </code>

    sahas@sun, you're very impolite! farukkhan was trying to help, and he's right because when you use code formatting the code is really easier to read.
    Perhaps you have lost a chance for getting the answer!

  • Can any one tell what is the problem in this code?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.util.*;
    public class AppletTest2 extends JApplet implements ActionListener,MouseMotionListener,WindowListener{
    JFrame fr = new JFrame("Visual Tool -- Work Flow Editor");
         JPanel panel1 = new JPanel();
         JPanel panel2 = new JPanel();
         JButton sButton = new JButton("Source");
         JButton rButton = new JButton("Redirection");
         JButton dButton = new JButton("Destination");
         JButton connect = new JButton("Connect");
         BasicStroke stroke = new BasicStroke(2.0f);
         int flag = 1 ;
         Vector lines = new Vector();
         JButton sBut,rBut,dBut;
    int x1 = 0 ;
         int y1 = 0 ;
         int x2 = 0 ;
         int y2 = 0;
         int x3 = 0;
         int y3 = 0;
         int i=0;
         int j=0;
         int k=0;
         int l = 100;
    int b = 50;
    public void init(){
              /*********Frame ******************/
    fr.getContentPane().setLayout(new BorderLayout());
         fr.setSize(700,500);
              fr.getContentPane().add(panel1,BorderLayout.CENTER);
              fr.getContentPane().add(panel2,BorderLayout.SOUTH);
              fr.addWindowListener(this);
              /*****************PANEL 1*********************/
              panel1.setLayout(null);
    panel1.setBounds(new Rectangle(0,0,400,400));
              panel1.setBackground(new Color(105,105,205));
    /************************PANEL 2 *************/
              panel2.setLayout(new FlowLayout());
              panel2.setBackground(new Color(105,205,159));
              panel2.add(sButton);
              panel2.add(rButton);
              panel2.add(dButton);
              panel2.add(connect);
              connect.setToolTipText("Use this button after selecting From and To position to connect");
              /***************************LISTENER********************/
    sButton.addActionListener(this);
              rButton.addActionListener(this);
              dButton.addActionListener(this);
              connect.addActionListener(this);
              fr.setVisible(true);     
              fr.setResizable(false);
         } // init clse
    /************************** START METHOD **********************************************/
              public void start(){                                 
                   System.out.println("inside start");
                   paint(panel1.getGraphics());
    /*******************************APPLET METHODS **************************************************/
              public void stop(){}
              public void destroy(){}
    /******************************MOUSE MOTION LISTENERS METHOD*************************************/
              public void mouseMoved(MouseEvent e){System.out.println("moved");}
              public void mouseDragged(MouseEvent e){System.out.println("dragged");}
    /***************************************ACTION EVENT IMPLEMENTAION *******************************/
         public void actionPerformed(ActionEvent e){
              if (e.getSource().equals(sButton)){          
              sourceObject("Source Object");          
              else if (e.getSource().equals(rButton)){          
              redirectionObject("Redirection");
              i = i+1;
              else if (e.getSource().equals(dButton)){
              destinationObject("Destination");
                   j= j+1;
              else if (e.getSource().equals(connect)){
                   System.out.println("am inside connect");                
                   paint(panel1.getGraphics());               
    else if(e.getSource().equals(sBut)){
                   System.out.println("am s button");                
                   x1 = sBut.getX() + l;
                   y1 = sBut.getY() + (b/2);
              else if(e.getSource().equals(rBut)){
                   System.out.println("am r button");               
                   x2 = rBut.getX() ;
                   y2 = rBut.getY()+ b/2;
                   System.out.println("x2 : " + x2 + "y2 :" +y2 );
              else if(e.getSource().equals(dBut)){
                   System.out.println("am d button");                
                   x3 = dBut.getX();
    y3 = dBut.getY()+ b/2;
    } // action close
    /**********************Main **********************************/     
         public static void main(String args[]){
         JApplet at = new AppletTest2();
              at.init();
              at.start();
    /********************my methods starts here *******************/
         public void sourceObject(String name){     
    sBut = new JButton(name);
         panel1.add(sBut);
         sBut.setBounds(new Rectangle(20,208,l,b));     
         sBut.addActionListener(this);
    System.out.println("am inside the source object") ;
         public void redirectionObject(String name){     
         rBut = new JButton(name);
         panel1.add(rBut);
         rBut.setBounds(new Rectangle(290,208,l,b));     
    rBut.addActionListener(this);
    System.out.println("am inside the redirection :" + j) ;
    public void destinationObject(String name){     
         dBut = new JButton(name);
         panel1.add(dBut);     
    System.out.println("am inside the destination object") ;
    if (j == 0)
                   dBut.setBounds(new Rectangle(566,60,l,b));                    
                   System.out.println("am inside the destination:" + j) ;
                   } else if (j == 2)
                        dBut.setBounds(new Rectangle(566,208,l,b));     
                        System.out.println("am inside the destination :" + j) ;
                   } else if (j == 1)
    dBut.setBounds(new Rectangle(566,350,l,b));     
                        System.out.println("am inside the destination :" + j) ;
    dBut.addActionListener(this);
    /* public void connectObject(Object obj1,Object obj2){
    System.out.println("nothing");
    /************************************* PAINT **************************/
    public void paint(Graphics g){
         System.out.println("inside paint");
         Graphics2D g2 = (Graphics2D) g;
         g2.setStroke(stroke);
    if(flag == 1){
    System.out.println("inside flag");
    int np = lines.size();
                        System.out.println(np);
                             for (int I=0; I < np; I++) {                       
         Rectangle p = (Rectangle)lines.elementAt(I);
                             System.out.println("width" + p.width);
                             g2.setColor(Color.red);
                             g2.drawLine(p.x,p.y,p.width,p.height);
                             System.out.println(p.x +"" +""+ p.y + ""+ ""+ p.width+ "" + ""+ p.height);
    flag = -1;
    }else if(flag == -1){
         if(x1 != 0 && y1 != 0 && x2 != 0 && y2 != 0 ){
    // Graphics2D g2 = (Graphics2D) g;
         // g2.setStroke(stroke);
    g2.setColor(Color.red);
         g2.drawLine(x1,y1,x2,y2);
         lines.addElement(new Rectangle(x1,y1,x2,y2));     
         x1 = 0 ;y1 = 0 ;
         x2 = 0 ;y2 = 0 ;
    //     g2.drawLine(100,100,200,200);
    else if (x2 != 0 && y2 != 0 && x3 != 0 && y3 != 0 )
              // Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
              g2.setColor(Color.green);
                        g2.drawLine(x2,y2,x3,y3);
                        lines.addElement(new Rectangle(x2,y2,x3,y3));
                        x2 = 0; y2 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    else if (x1 != 0 && y1 != 0 && x3 != 0 && y3 != 0)
                   //     Graphics2D g2 = (Graphics2D) g;
                   // g2.setStroke(stroke);
                   g2.setColor(Color.red);
                   g2.drawLine(x1,y1,x3,y3);
                        lines.addElement(new Rectangle(x1,y1,x3,y3));                              
                        x1 = 0; y1 = 0 ;
                        x3 = 0 ; y3 = 0 ;                    
    // repaint();
    /********************************WINDOW LISTENER IMPLEMENTATION *****************************/
    public void windowActivated(WindowEvent we) { 
              flag = 1;
              paint(panel1.getGraphics());
    System.out.println("windowActivated -- event 1");
         //start();               
         public void windowClosed(WindowEvent we) {
                                                                System.out.println("windowClosed -- 2");
         public void windowClosing(WindowEvent we){
                                                                System.out.println("windowClosing -- 3");
    public void windowDeactivated(WindowEvent we) {
                                                                     System.out.println("windowDeactivated -- 4");
    public void windowDeiconified(WindowEvent we) {
                                                                     flag = 1;
                                                                     System.out.println("windowDeiconified -- 5");          
                                                                     paint(panel1.getGraphics());           
    public void windowIconified(WindowEvent we) {           
                                                           System.out.println("windowIconified -- 6");
                                                           //paint(panel1.getGraphics());
    public void windowOpened(WindowEvent we) {             
                                                      //     flag = 1;
                                                      //     paint(panel1.getGraphics());
                                                           System.out.println("windowopened -- 7");     
    The problem am facing here is that when i minimize the frame and maximize , my old lines are getting disappared.
    For avoiding that i am storing the old coordinates and
    try to redraw , when maximize.
    but the lines are coming for flash of second and disappearing once again ?
    can any one help?
    thanks all

    Very interestingly the same code is repainting in
    Linux SUSE,jdk1.3.
    but not in WINNT , jdk 1.3
    Any reason ?
    Is the swing 100 % platform independenet ?????
    Does swing also uses native thread ???

  • Problem in a drawing program

    Dear experts,
    While working on a program,i am having a problem which is just killing me.This is a simple drawing program.On clicking draw button,user
    can do free hand drawing.On clicking line he can stretch line to any
    coordinate.Similarily do erasing etc.
    Problem underlies in rectangle part.I am using some conditions.
    Conditions are based on analysis.Fixx and Fixy are the points
    when mouse is pressed.
    Prevx and Prevy are coordinates which are stored before retrieving
    newer ones.x and y are new coordinates.
    I have marked the relevant code as part of code for easy understanding.
    Problem is in behaviour for rectangle.If i draw twoards either side
    it works well but the moment i drag right ,left,up down ,i get
    patched near origin(fixed point) from where mouse was pressed ie
    fixx,fixy.
    I recommend if this could be copied as it is and run,the problem will come to light better.
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    public class FProf extends JPanel implements MouseListener,ActionListener,MouseMotionListener
    JFrame main_window;
    int draw_mode,erase_mode,line_mode,box_mode;
    double fixx,fixy;
    double initx,inity;
    double x,y;
    JButton b_draw;
    JButton b_erase;
    JButton b_line;
    JButton b_rec;
    JPanel draw_panel;
    JPanel bt_panel;
    Graphics2D g2;
    Point p;//Mouse pointer
    Image image=null;
    double prevx,prevy;
    double c1,c2,c3,c4,c5,c6,c7,c8;
    Stroke[] linestyles = new Stroke[] {
    new BasicStroke(25.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL),
    new BasicStroke(25.0f, BasicStroke.CAP_SQUARE,BasicStroke.JOIN_MITER),
    new BasicStroke(1.0f, BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER),
    new BasicStroke(25.0f, BasicStroke.CAP_ROUND,
    BasicStroke.JOIN_ROUND), };
    FProf()
    draw_mode=0; //Inactive
    erase_mode=0; //Inactive
    addMouseListener(this);
    addMouseMotionListener(this);
    GridLayout l=new GridLayout(4,4);
    main_window=new JFrame("Fountain Prof V.200");
    bt_panel=new JPanel();
    b_draw=new JButton ("Draw");
    b_draw.addActionListener(this);
    b_erase=new JButton("Erase");
    b_erase.addActionListener(this);
    b_line=new JButton("Line");
    b_line.addActionListener(this);
    b_rec=new JButton ("Box");
    b_rec.addActionListener(this);
    main_window.getContentPane().setLayout(new BorderLayout());
    main_window.getContentPane().add("Center",this);
    bt_panel.setLayout(l);
    bt_panel.add(b_draw);
    bt_panel.add(b_erase);
    bt_panel.add(b_line);
    bt_panel.add(b_rec);
    main_window.getContentPane().add("East",bt_panel);
    main_window.setSize(800,600);
    main_window.show();
    private void draw()
    if ((erase_mode==1) &&(draw_mode==0) &&(line_mode==0)&&(box_mode==0)) {
    g2.setPaintMode();
    g2.setColor(Color.white);
    g2.setStroke(linestyles[3]); // Select the line style to use
    g2.draw(new Line2D.Double(initx,inity,x,y));
    repaint();
    else if ((draw_mode==1) && (line_mode==0) &&(erase_mode==0)&&(box_mode==0))
    g2.setPaintMode();
    g2.setColor(Color.black);
    g2.setStroke(linestyles[2]); // Select the line style to use
    g2.draw(new Line2D.Double(initx,inity,x,y));
    repaint();
    else if ((draw_mode==0) && (erase_mode==0) &&(line_mode==1)&&(box_mode==0))
    repaint();
            else if ((draw_mode==0) && (erase_mode==0) &&(line_mode==0)&&(box_mode==1))
            repaint();
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    if (image == null)
    System.out.print(getHeight());
    g2=(Graphics2D) g;
    image = createImage(getWidth(), getHeight());
    g2 = (Graphics2D)image.getGraphics();
    g2.setColor(Color.white);
    g2.fillRect(0, 0, getWidth(), getHeight());
    g2.setColor(Color.black);
    Rectangle r = g.getClipBounds();
    g.drawImage(image, r.x, r.y, r.width+r.x, r.height+r.y, r.x, r.y, r.width+r.x, r.height+r.y, null);
    public void mouseReleased(MouseEvent e)
    public void mouseEntered(MouseEvent e)
    public void mouseExited(MouseEvent e)
    public void change_cursor()
    Toolkit tk=Toolkit.getDefaultToolkit();
    if ((draw_mode==1)&&(erase_mode==0)) {
    Image img=tk.getImage("Pen.gif");
    Cursor dym=tk.createCustomCursor(img,new Point(10,10),null);
    setCursor(dym);
    else if ((erase_mode==1)&&(draw_mode==0)) {
    Image img=tk.getImage("eraser.gif");
    Cursor dym=tk.createCustomCursor(img,new Point(10,10),null);
    setCursor(dym);
    public void mouseClicked(MouseEvent e)
    public void mouseDragged(MouseEvent e)
    Point p;
    if ((draw_mode ==1)||(erase_mode==1)) {
    initx=x;inity=y;
    p=e.getPoint();
    x=p.getX();
    y=p.getY();
    draw();
    if ((line_mode==1)&&(box_mode==0)) {
    if (mousehasmoved(e)) {
    prevx=x;prevy=y;
    p=e.getPoint();
    x=p.getX();
    y=p.getY();
    g2 = (Graphics2D)image.getGraphics();
    g2.setColor(Color.black);
    g2.setXORMode(Color.white);
    g2.draw(new Line2D.Double(fixx,fixy,prevx,prevy)); //erasing previous line
    draw();
    g2.draw(new Line2D.Double(fixx,fixy,x,y)); //redrawing newer one
    draw();
    if ((line_mode==0)&&(box_mode==1)) {
    if (mousehasmoved(e)) {
    prevx=x;prevy=y;
    p=e.getPoint();
    x=p.getX();
    y=p.getY();
    g2 = (Graphics2D)image.getGraphics();
    g2.setColor(Color.black);
    g2.setXORMode(Color.white);
    if ((x<=fixx) && (y>=fixy)) {
    c1=x;c2=fixy;c3=fixx-x;c4=y-fixy;c5=prevx;c6=fixy;c7=fixx-prevx;c8=prevy-fixy;
    else if ((x>=fixx)&&(y>=fixy)) {
    c1=fixx;c2=fixy;c3=x-fixx;c4=y-fixy;c5=fixx;c6=fixy;c7=prevx-fixx;c8=prevy-fixy;
    else if ((x>=fixx)&&(y<=fixy)) {
    c1=fixx;c2=y;c3=x-fixx;c4=fixy-y;c5=fixx;c6=prevy;c7=prevx-fixx;c8=fixy-prevy;
    else if ((x<=fixx)&&(y<=fixy)) {
    c1=x;c2=y;c3=fixx-x;c4=fixy-y;c5=prevx;c6=prevy;c7=fixx-prevx;c8=fixy-prevy;
    g2.draw(new  Rectangle2D.Double(c5,c6,c7,c8));
    draw();
    g2.draw(new  Rectangle2D.Double(c1,c2,c3,c4));
    draw();
    }public void mouseMoved(MouseEvent e)
    p=e.getPoint();
    x=p.getX();
    y=p.getY();
    main_window.setTitle("X- "+x+" "+"Y- "+y);
    initx=x;inity=y; //Get me current position
    if ((draw_mode==1)||(erase_mode==1)) {
    //change_cursor();
    else {
    setCursor(Cursor.getDefaultCursor());
    public void mousePressed(MouseEvent ex)
    if ((draw_mode==0) && (erase_mode==0) &&((line_mode==1)||(box_mode==1))) {
    fixx=ex.getX();fixy=ex.getY();
    public void actionPerformed(ActionEvent ev)
    Object ob=ev.getSource();
    if (ob==b_draw) {
    draw_mode=1;erase_mode=0;line_mode=0;
    box_mode=0;
    if (ob==b_erase) {
    erase_mode=1;draw_mode=0;line_mode=0;
    box_mode=0;
    if (ob==b_line) {
    erase_mode=0;draw_mode=0;line_mode=1;
    box_mode=0;
    if (ob==b_rec) {
    erase_mode=0;draw_mode=0;line_mode=0;box_mode=1;
    public static void main(String args[])
    new FProf();
    public boolean mousehasmoved (MouseEvent e)
    return((initx != e.getX()) ||(inity!=e.getY()));
    }}

    change your mouseDragged method to something like:
        public void mouseDragged(MouseEvent e)
            Point p;
            if ((draw_mode == 1) || (erase_mode == 1))
                initx = x;
                inity = y;
                p = e.getPoint();
                x = p.getX();
                y = p.getY();
                draw();
            if ((line_mode == 1) && (box_mode == 0))
                if (mousehasmoved(e))
                    prevx = x;
                    prevy = y;
                    p = e.getPoint();
                    x = p.getX();
                    y = p.getY();
                    g2 = (Graphics2D) image.getGraphics();
                    g2.setColor(Color.black);
                    g2.setXORMode(Color.white);
                    g2.draw(new Line2D.Double(fixx, fixy, prevx, prevy)); // erasing
                                                                            // previous
                                                                            // line
                    draw();
                    g2.draw(new Line2D.Double(fixx, fixy, x, y)); // redrawing
                                                                    // newer one
                    draw();
            if ((line_mode == 0) && (box_mode == 1))
                if (mousehasmoved(e))
                    prevx = x;
                    prevy = y;
                    p = e.getPoint();
                    x = p.getX();
                    y = p.getY();
                    g2 = (Graphics2D) image.getGraphics();
                    g2.setColor(Color.black);
                    g2.setXORMode(Color.white);
                     * calculate the former rectangle - it does not depend to
                     * the new rectangle!
                    if((prevx <= fixx) && (prevy >= fixy))
                        c5 = prevx;
                        c6 = fixy;
                        c7 = fixx - prevx;
                        c8 = prevy - fixy;                   
                    else
                        if ((prevx >= fixx) && (prevy >= fixy))
                            c5 = fixx;
                            c6 = fixy;
                            c7 = prevx - fixx;
                            c8 = prevy - fixy;
                        else
                            if ((prevx >= fixx) && (prevy <= fixy))
                                c5 = fixx;
                                c6 = prevy;
                                c7 = prevx - fixx;
                                c8 = fixy - prevy;
                            else
                                if ((prevx <= fixx) && (prevy <= fixy))
                                    c5 = prevx;
                                    c6 = prevy;
                                    c7 = fixx - prevx;
                                    c8 = fixy - prevy;
                     * calculate the new rectangle here
                    if ((x <= fixx) && (y >= fixy))
                        c1 = x;
                        c2 = fixy;
                        c3 = fixx - x;
                        c4 = y - fixy;
                    else
                        if ((x >= fixx) && (y >= fixy))
                            c1 = fixx;
                            c2 = fixy;
                            c3 = x - fixx;
                            c4 = y - fixy;
                        else
                            if ((x >= fixx) && (y <= fixy))
                                c1 = fixx;
                                c2 = y;
                                c3 = x - fixx;
                                c4 = fixy - y;
                            else
                                if ((x <= fixx) && (y <= fixy))
                                    c1 = x;
                                    c2 = y;
                                    c3 = fixx - x;
                                    c4 = fixy - y;
                    g2.draw(new Rectangle2D.Double(c5, c6, c7, c8));
                    draw();
                    g2.draw(new Rectangle2D.Double(c1, c2, c3, c4));
                    draw();
        }why?
    You calculated the former rectangle in dependence to the newly created one. It does not depend on that, but needs its own if statements. I'm sure you will understand what I mean when looking at the method.

  • Display .gif In Applet Problem

    I have been making a game. Very simply, the game has a main class and another truely important class that extends JFrame, it is the map. In it i need to upload .gif files and display them. It worked up until recently because i needed to make a sepperate class. I know how to use the getImage() for Images and the the way for ImageIcons, but for some reason, they never display (they display just whiteness). My Code is as follows
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import java.io.*;
    // when this puppy reads from a file, it'll be able to have 55 15 x 15 terrains per row
    // 35 15 x 15 terrains per column
    // arrows by everythign that u would need to consider in finding the problem
    // this is not the main class
    public class GameMap extends JPanel implements MouseListener, MouseMotionListener, KeyListener{
         public static final int MAX_BULLETS = 200;
         public static final int MAX_PLAYERS = 50;
         public static final int SPLAT_SIZE = 15;
         public static final int PLAYER_SIZE = 15;
         public static final int MAX_MESSAGES = 10;
         public static final int ROBOT_SIZE = 15;
         private static final int rowTerrains = 35;
         private static final int columnTerrains = 55;
         private static int currentBullets = 0;
         private static int currentPlayers = 0;
         private static int bulletRotation = 0;
         private static int aimX, aimY;
         private boolean mapLoaded;
         private boolean writingMessage;
         private boolean imagesLoaded;
         private int messageRotation;
         private int tileCoord;
         private String messageText = "";
         private String currentMap;
        private Bullet bullet[] = new Bullet[MAX_BULLETS];
        private Player player[] = new Player[MAX_PLAYERS];
        private Message message[] = new Message[MAX_MESSAGES];
        private Color backgroundColor = new Color(81, 141, 23);
        private Image offscreenMap; // offscreen image of map
        private Graphics mapGraphics;
         private ImageIcon yellowSplat1, yellowSplat2, yellowSplat3, yellowSplat4, yellowSplat5, bluePlayerBack, bluePlayerFront, bluePlayerRight, bluePlayerLeft, grass, tree, mountain, robot1;
         private Terrain terrain[] = new Terrain[(rowTerrains * columnTerrains)];
         public GameMap(){
              this(800, 450);
         public GameMap(int width, int height){
              addMouseListener(this);
              addMouseMotionListener(this);
              addKeyListener(this); // use method requestFocusInWindow() for this to work
              setPreferredSize(new Dimension(width, height));
              setBackground(backgroundColor);
              for (int x = 0; x < bullet.length; x++){
                   bullet[x] = new Bullet();
              for (int x = 0; x < player.length; x++){
                   player[x] = new Player();
              for (int x = 0; x < message.length; x++){
                   message[x] = new Message();
              for (int x = 0, currentX = 0, currentY = 0; x < (rowTerrains * columnTerrains); x++){
                   terrain[x] = new Terrain();
                   terrain[x].setX(currentX);
                   terrain[x].setY(currentY);
                   currentX += 15;
                   if (currentX > columnTerrains * 15){
                        currentX = 0;
                        currentY += 15;
              player[0].drawPlayer(0, 0);
              //loadMap("Map1.txt"); // this is called to load the map right when this object is initialized
         public void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D)g;
              Composite originalComposite = g2d.getComposite();
              if (imagesLoaded == false){
                   yellowSplat1 = new ImageIcon("yellow1.gif");
                   yellowSplat2 = new ImageIcon("yellow2.gif");
                   yellowSplat3 = new ImageIcon("yellow3.gif");
                   yellowSplat4 = new ImageIcon("yellow4.gif");
                   yellowSplat5 = new ImageIcon("yellow5.gif");
                   bluePlayerBack = new ImageIcon("BlueBack.gif");
                   bluePlayerFront = new ImageIcon("BlueFront.gif");
                   bluePlayerLeft = new ImageIcon("BlueLeft.gif");
                   bluePlayerRight = new ImageIcon("BlueRight.gif");
                   grass = new ImageIcon("Grass.gif");
                   tree = new ImageIcon("Tree.gif");
                   mountain = new ImageIcon("Mountain.gif");
                   robot1 = new ImageIcon("Robot1.gif");
              if (mapLoaded == false){ // so a map is loaded when game is started
                   loadMap("Map1.txt");
                   mapLoaded = true;
              g.drawImage(offscreenMap, 0, 0, this);
              for (int x = 0; x < bullet[0].totalBullets; x++){
                   if (bullet[x].getArrived()){
                        //find splat type and display it
                        g2d.setComposite(makeComposite(0.5f));
                        switch (bullet[x].getSplatType()){
                             case 0:
                                  yellowSplat1.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 1:
                                  yellowSplat2.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 2:
                                  yellowSplat3.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 3:
                                  yellowSplat4.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                             case 4:
                                  yellowSplat5.paintIcon(this, g2d, bullet[x].getDestX() - SPLAT_SIZE / 2, bullet[x].getDestY() - SPLAT_SIZE / 2);
                                  break;
                   else{
                        g2d.setComposite(originalComposite);
                        g2d.setColor(Color.yellow);
                        g2d.fillOval(bullet[x].getX(), bullet[x].getY(), 3, 3);
              g2d.setComposite(originalComposite);
              g.setColor(Color.yellow);
              for (int x = 0; x < player[0].totalPlayers; x++){
                   if (player[x].getPlayerPosition().equals("Back")){
                        bluePlayerBack.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else if (player[x].getPlayerPosition().equals("Right")){
                        bluePlayerRight.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else if (player[x].getPlayerPosition().equals("Left")){
                        bluePlayerLeft.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else if (player[x].getPlayerPosition().equals("Front")){
                        bluePlayerFront.paintIcon(this, g2d, player[x].getX(), player[x].getY());
                   else{
                        g2d.fillOval(player[x].getX(), player[x].getY(), 15, 15);
              if (writingMessage){
                   g2d.setColor(new Color(0, 0, 130));
                   g2d.setComposite(makeComposite(0.5f));
                   g2d.draw3DRect(8, 7, 800, 17, true);
                   g2d.setComposite(originalComposite);
                   g2d.setColor(Color.yellow);
                   g2d.drawString(messageText, message[0].getX(), 20);
              for (int x = 0; x < MAX_MESSAGES; x++){
                   if (message[x].isDisplayed()){
                        g2d.drawString(message[x].getMessage(), message[x].getX(), message[x].getY());
         private AlphaComposite makeComposite(float alpha) {
              int type = AlphaComposite.SRC_OVER;
              return(AlphaComposite.getInstance(type, alpha));
         public void drawBullet(int aimX, int aimY){
              bullet[bulletRotation].drawBullet(player[0].getX() + PLAYER_SIZE / 2, player[0].getY() + PLAYER_SIZE / 2, aimX, aimY);
              player[0].setPlayerPosition(bullet[bulletRotation].getPlayerPosition());
              bulletRotation++;
              if (bulletRotation >= MAX_BULLETS){
                   bulletRotation = 0;
         public void loadMap(String map){
              mapLoaded = false;
              currentMap = map;
              try{
                   BufferedReader in = new BufferedReader(new FileReader(map));
                   String input, string1, string2;
                   for (int x = 0; x < terrain.length; x++){
                        terrain[x].setFilled(false);
                   for (int x = 0, currentArray; x < terrain.length; x++){
                        if ((input = in.readLine()) != null) {
                             StringTokenizer st = new StringTokenizer(input);
                             currentArray = Integer.parseInt(st.nextToken());
                             terrain[currentArray].setTerrainType(st.nextToken());
                             terrain[currentArray].setFilled(true);
                        else{
                             break;
                   in.close();
                   offscreenMap = createImage(size().width, size().height);
                   mapGraphics = offscreenMap.getGraphics();
                   //mapGraphics.clearRect(0, 0, size().width, size().height);
                   // everything from here down is to be painted to mapGraphics... but it doesn't get this far cuz of an error
                   for (int x = 0; x < terrain.length; x++){
                        if (terrain[x].getTerrainType().equals("Grass")){
                             grass.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
                             System.out.println("terrain(" + x + ") is Grass");
                        else if (terrain[x].getTerrainType().equals("Tree")){
                             tree.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
                             System.out.println("terrain(" + x + ") is Tree");
                        else if (terrain[x].getTerrainType().equals("Mountain")){
                             mountain.paintIcon(this, mapGraphics, terrain[x].getX(), terrain[x].getY());
                             System.out.println("terrain(" + x + ") is Mountain");
              catch (FileNotFoundException e){
                   System.out.println("Map not found");
              catch (IOException e){
                   System.out.println("IOException Error!");
              // **** mouse Listener ****//
         public void mouseClicked(MouseEvent e){}
         public void mousePressed(MouseEvent e){}
         public void mouseReleased(MouseEvent e){
              if (e.getButton() == 1){
                   //System.out.println("player[0].movePlayer(" + e.getX() + ", " + e.getY() + ")");
                   aimX = e.getX();
                   aimY = e.getY();
                   movePlayer(aimX, aimY);
              else if (e.getButton() == 3){
                   aimX = e.getX();
                   aimY = e.getY();
                   drawBullet(aimX, aimY);
         public void mouseEntered(MouseEvent e){
              if (isFocusOwner() != true){
                   requestFocusInWindow();
         public void mouseExited(MouseEvent e){}
         // **** end mouse listener ****//
         // **** mouse motion listener ****//
         public void mouseDragged(MouseEvent e){}
         public void mouseMoved(MouseEvent e){}
         // **** end mouse motion listener ****/
         public void keyPressed(KeyEvent e){}
         public void keyReleased(KeyEvent e){}
         public void keyTyped(KeyEvent e){}
    }I removed a few unnecessary methods from this code to make it easier to view. EVERYTHING works except for the images displaying. The reason i'm having this problem now is i just redid my workspace and copied the code and i think some glitch stopped it from compiling correctly all along so now i experience this problem in the applet viewer. Though, even before, i couldn't get anything to display in an applet.
    And yes, everything is in the same place as the html file.
    Thanks for your help!

    Here's a way to keep track of and paint images with a simple Rectangle array. And also a way to remove lengthy initialization code blocks from paintComponent. Move the images by moving the rectangles.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class GameMapRx
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new GameMapPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class GameMapPanel extends JPanel
        Image[] images;
        Rectangle[] rects;
        boolean firstTime;
        final int PAD;
        public GameMapPanel()
            loadImages();
            firstTime = true;
            PAD = 20;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            int w = getWidth();
            int h = getHeight();
            if(firstTime)
                initializeGameMap(w, h);
            for(int i = 0; i < rects.length; i++)
                Rectangle r = rects;
    g.drawImage(images[i], r.x, r.y, this);
    g2.draw(r);
    private void loadImages()
    String path = "images/duke/";
    String ext = ".gif";
    images = new Image[10];
    for(int i = 0; i < images.length; i++)
    try
    URL url = getClass().getResource(path + "T" + (i + 1) + ext);
    images[i] = ImageIO.read(url);
    catch(MalformedURLException mue)
    System.out.println("Bad URL: " + mue.getMessage());
    catch(IOException ioe)
    System.out.println("Unable to read: " + ioe.getMessage());
    private void initializeGameMap(int w, int h)
    rects = new Rectangle[images.length];
    int imageWidth = images[0].getWidth(this);
    int imageHeight = images[0].getHeight(this);
    int cols = (w - 2*PAD) / imageWidth;
    int xInc = imageWidth + (w - cols * imageWidth) / (cols + 1);
    int x0 = (w - cols * imageWidth -
    (cols - 1) * ((w - cols * imageWidth) / (cols + 1))) / 2;
    for(int i = 0; i < images.length; i++)
    int x = x0 + xInc * (i % cols);
    int rows = i / cols;
    int y = PAD + (imageHeight + PAD) * rows;
    rects[i] = new Rectangle(x, y, imageWidth, imageHeight);
    firstTime = false;

  • Problem in moving Rotated Shape object

    Hi All,
    I want to move the rotated shape object based on the mouse movement
    m able to move the object which is not rotated, but m facing the problem when i move the rotated object its moving position is not correct . I am expecting to maintain both shape objects movement is same, i mean if i did mouse movement to right rotated object moves upwards and normal object moves towards right insted of moving both r moving towards to right.
    Pls help me
    the following code is m using to moving the object
    The one which in red color is not rotated and the one which is in black color has rotated.
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import com.clinapps.LDPConstants;
    public class MoveRotatedObj extends JFrame
         public MoveRotatedObj()
              JPanel pane = new Dorairaj();
              add(pane);
         public static void main(String[] args)
              MoveRotatedObj f = new MoveRotatedObj();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              f.setSize(400, 400);
              f.setLocation(200, 200);
              f.setVisible(true);
         static class Dorairaj extends JPanel
              implements
                   MouseListener,
                   MouseMotionListener
              Shape o = null;
              Rectangle2D rect = new Rectangle2D.Double(
                   10, 10, 100, 100);
              Graphics2D g2 = null;
              boolean flag = true;
              int x=10,y=10,x1, y1, x2, y2;
              AffineTransform af = new AffineTransform();
              AffineTransform originalAt = new AffineTransform();
              int origin = 0;
              public Dorairaj()
                   addMouseListener(this);
                   addMouseMotionListener(this);
              protected void paintComponent(Graphics g)
                   super.paintComponent(g);
                   g2 = (Graphics2D) g;
                   g2.draw(new Rectangle2D.Double(0,0,500,500));
                   g2.translate(origin, origin);
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
                   rect = new Rectangle2D.Double(
                        x, y, 150, 100);
                   g2.setColor(Color.RED);
                   g2.draw(rect);
                   g2.setColor(Color.black);
                   originalAt = g2.getTransform();
                   g2.rotate(Math.toRadians(270), 200, 200);               
                   g2.draw(rect);
                   g2.setTransform(originalAt);
              * Invoked when a mouse button has been pressed on a component.
              public void mousePressed(MouseEvent e)
                   e.translatePoint(-origin, -origin);
                   x1 = e.getX();
                   y1 = e.getY();
              public void mouseDragged(MouseEvent e)
                   x2 = e.getX();
                   y2 = e.getY();
                   x = x + x2 - x1;
                   y = y + y2 - y1;
                   x1 = x2;
                   y1 = y2;
                   repaint();
              public void mouseMoved(MouseEvent e)
              * Invoked when the mouse button has been clicked (pressed and released)
              * on a component.
              public void mouseClicked(MouseEvent e)
                   repaint();
              * Invoked when a mouse button has been released on a component.
              public void mouseReleased(MouseEvent e)
              * Invoked when the mouse enters a component.
              public void mouseEntered(MouseEvent e)
              * Invoked when the mouse exits a component.
              public void mouseExited(MouseEvent e)
    Edited by: DoraiRaj on Sep 16, 2009 12:51 PM
    Edited by: DoraiRaj on Sep 16, 2009 1:00 PM
    Edited by: DoraiRaj on Sep 16, 2009 1:07 PM

    Thanks for replay and suggestion morgalr,
    I mean MoveRotatedObj1 is MoveRotatedObj only jsut m maintaing a copy on my system like MoveRotatedObj1.
    finally i solved my problem like this ,
    Is this correct approach m followinig or not pls let me know .
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Shape;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import com.clinapps.LDPConstants;
    public class MoveRotatedObj extends JFrame
    public MoveRotatedObj()
      JPanel pane = new Dorairaj();
      add(pane);
    public static void main(String[] args)
      MoveRotatedObj f = new MoveRotatedObj();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setSize(400, 400);
      f.setLocation(200, 200);
      f.setVisible(true);
    static class Dorairaj extends JPanel
      implements
       MouseListener,
       MouseMotionListener
      Shape o = null;
      Rectangle2D rect = new Rectangle2D.Double(
       10, 10, 100, 100);
      Rectangle2D rect1 = new Rectangle2D.Double(
       10, 10, 100, 100);
      Graphics2D g2 = null;
      boolean flag = true;
      double lx, ly;
      int x = 10, y = 10, x1, y1, x2, y2;
      int l = 20, m = 20;
      int angle = 270;
      AffineTransform af = new AffineTransform();
      AffineTransform originalAt = new AffineTransform();
      int origin = 0;
      public Dorairaj()
       addMouseListener(this);
       addMouseMotionListener(this);
      protected void paintComponent(Graphics g)
       super.paintComponent(g);
       g2 = (Graphics2D) g;
       g2.draw(new Rectangle2D.Double(
        0, 0, 500, 500));
       g2.translate(origin, origin);
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
       rect = new Rectangle2D.Double(
        x, y, 150, 100);
       g2.setColor(Color.RED);
       g2.draw(rect);
       rect1 = new Rectangle2D.Double(
        l, m, 150, 100);
       g2.setColor(Color.black);
       originalAt = g2.getTransform();
       g2.rotate(Math.toRadians(angle), 200, 200);
       g2.draw(rect1);
       g2.setTransform(originalAt);
      public void mousePressed(MouseEvent e)
       e.translatePoint(-origin, -origin);
       x1 = e.getX();
       y1 = e.getY();
      public void mouseDragged(MouseEvent e)
       boolean left, right, up, bottm;
       int dx, dy;
       left = right = up = bottm = false;
       x2 = e.getX();
       y2 = e.getY();
       dx = x2 - x1;
       dy = y2 - y1;
       x = x + dx;
       y = y + dy;
       up = dy < 0;
       bottm = dy > 0;
       left = dx < 0;
       right = dx > 0;
       if (left || right)
        // b += dx;
        m += dx;
       if (up || bottm)
        // a -= dy;
        l -= dy;
       x1 = x2;
       y1 = y2;
       repaint();
      public void mouseMoved(MouseEvent e)
      public void mouseClicked(MouseEvent e)
       repaint();
      public void mouseReleased(MouseEvent e)
      public void mouseEntered(MouseEvent e)
      public void mouseExited(MouseEvent e)
    }

Maybe you are looking for

  • Bootcamp failure, iMac stuck in black screen with cursor line.

    I was in the midst of insalling windows when I ran into a speed bump with my windows install disk and i wanted to start over. So i turned of the iMac from the back power button after stoping the install and wanted to start over again from the os X bo

  • Why my phone is getting crashed in middle

    Hello!! Sir. I have purchased intex fx cloud phone. Online.. It runs on fxv07 version...whenever i use it continuously till one hour. Phone gets strucked off my contacts.get interchanged thwmselves.. It doesnt display. Messages when when i must recie

  • Grid Control Configure Monitor Username

    Hi, I dropped the standby and recreated it. Now i'm trying to add this to the OMS for monitoring. Host is success but when i try to add the standby database to OMS, the Monitor Username parameter is defaulting to dbsnmp and not allowing me change to

  • Cann't  find TutWD_BonusCalculation_Init

    Hi,    I went to https://www.sdn.sap.com/irj/sdn/developerareas/webdynpro?rid=/library/uuid/49f2ea90-0201-0010-ce8e-de18b94aee2d link but there is so many links for download.Where I will get the exact link to download TutWD_BonusCalculation_Init file

  • Video rendering error -50 iMovie version 10.0.6

    Every time I try to share my project, it says "Video Rendering failed" or something and when I click on details it says "Video Rendering Error : -50". I have the newest version of iMovie version 10.0.6 and i need to know how to fix this. Thank you!