Intermittent MousePressed Events

I am having trouble with mouse pressed events. I have a JFrame with 2 images in JPanels, with a separate JComponent sindow that will display one or the other image with a delay. It flickers between the 2 images using a thread. The JPanel responds to MousePressed events with the flickering turned off. When it is turned on the mouse pressed events are intermittent, I placed a print statement in the MousePressed method and I have to keep clicking the mouse to get it to work.
Has anyone seen MousePressed problems with threads before?
Thanks, Greg

I am afraid it was my own bug :(
I had reimplemented processMouseEvent() in my subclass of JTextPane to consume mouse events in the margin area if the click count was >1 thinking this applied only to mouse clicks and not mouse pressed.
Still had the issue of the JTextPane itself being a mouse listener to do text selection (word for double click, line for triple click). So what I did was : if the click was in the margin area I would determine if it was the type i needed (pressed) and pass the event to my listener and otherwise not pass it to the super method. So all solved now. :)
I prepared a small test - obstensibly to post - but that showed it was indeed my bug and after more searching found the answer. It is quite a big project with parts written many years ago. Even so, a bit red faced now ...

Similar Messages

  • Detecting the shift or ctrl key in the mousePressed event, ...

    In the mousePressed event, how do I detect
    if the shift or ctrl key is pressed?
    Thanks,
    Ben

    What I've posted is for j2sdk1.4, check the link below for older version:
    http://java.sun.com/j2se/1.4/jcp/j2se-1_4-rc-mr_docs-spec/apidiffs/java/awt/event/MouseEvent.html#DIFF1
    ;o)
    V.V.

  • Can't get mousePressed event to work

    Hi all!
    I have class, that extends DefaultTableModel. I can not make that when end user click on specifc cell, to create new class.
    Code looks like this:
    public class ContactList extends DefaultTableModel implements MouseListener {
        public void mousePressed(MouseEvent mouseEvent) {
          ContactUpdate conUpd =  new ContactUpdate ();
    }Can you help me with this? Thank you in advance!

    In the future, Swing related questions should be posted in the Swing forum.
    Attach the MouseListener to the JTable, not its model.

  • Changing times of an intermittently recurring event

    Let me clarify that.
    So I have my work dates/times in iCal.
    I work a varied schedule (shift work in a hospital) as in varied days on a given week.
    I am now changing my hours worked from a 3am start to a 7pm start.
    Is there a way to change all my current 3am work entries to this new time?
    Many thanks!

    Steven,
    The only way that I know of is to drag the events to the new time using the week view.
    ;~)

  • Unexpected Behaviors of Mouse Event in Look And Feel

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test{
         public static void main(String[] args){
              try {
                  // Set System L&F
                 UIManager.setLookAndFeel(
                     UIManager.getSystemLookAndFeelClassName());
             catch (UnsupportedLookAndFeelException e) {
                // handle exception
             catch (ClassNotFoundException e) {
                // handle exception
             catch (InstantiationException e) {
                // handle exception
             catch (IllegalAccessException e) {
                // handle exception
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(400,400);
              final JPopupMenu popup = new JPopupMenu();
              popup.add(new JMenuItem("Test"));
              JPanel panel = new JPanel();
              panel.addMouseListener(new MouseAdapter(){
                   public void mousePressed(MouseEvent e){
                        System.out.println("Mouse Pressed!");
                        if(e.isPopupTrigger())
                             popup.show(e.getComponent(), e.getX(), e.getY());
                   public void mouseReleased(MouseEvent e){
                        System.out.println("Mouse Released!");
                        if(e.isPopupTrigger())
                             popup.show(e.getComponent(), e.getX(), e.getY());
              frame.add(panel);
              frame.setVisible(true);
    }When I right click, the popup menu shows up and prints:
    Mouse Pressed!
    Mouse Released!
    Then I click on another position, it will print:
    Mouse Pressed!
    Mouse Released!
    The problem is when I set the LookAndFeel to SystemLookAndFeel (which is Windows XP), it only prints:
    Mouse Released!
    after the pop up menu shows up.
    I wonder what happened to the Mouse Pressed Event?

    Late to the party, but I'd like to add that I came across this same problem when we recently upgraded from 1.6_02 to 1.6_11. I have a JTable where a right-click produces a JPopupMenu, but a double right-click is a shortcut to one of the popup menu functions. Popup shows up fine on the single-click in both, but the double-click function didn't work in the later version.
    As hinted in this thread, it happens when you are reacting to the mousePressed event and you've install the System L&F (at least on Windows XP). I printed out PopupMenu.consumeEventOnClose after setting the L&F, and it reported true. So all I did was override that property to false after setting the L&F, and everything was back to normal.
    Not sure why that changed between those two updates. There were bug fixes 6539458 in u4 and 6217905 in u10 that are both related to JPopupMenu, so maybe one of those accounts for the difference. Hopefully I'm not breaking something by overriding the property.

  • How to enqueue custom AWT event?

    hi,
    in my applet I need to use custom AWT events. I subclass them from java.awt.AWTEvent and set their id to higher as AWTEvent.RESERVED_ID_MAX - as recomended in documentation.
    But how to enqueue such event? A tried to use following approach:
    getToolkit().getSystemEventQueue().postEvent( myEvent );
    and it works fine - but only in browsers usings Sun's VM implementation. In browsers using Microsoft's VM I'm getting following exception:
    com.ms.security.SecurityExceptionEx[matlu/client/ClientConnection.enQueue]: Event queue access denied.
    So the question is: is there any other way to enqueue custom event, which will keep Microsoft's security manager happy?
    thak you very much
    Lubo Matecka

    I know it must be visible... (But it doesnt have to be bigger than 1 pixel...)
    The code I posted is just to illustrate the idea.
    If you need to post multiple events you just replace the AWTEvent member with a LinkedList (or some similar FIFO).
    Then in postEvent you do theLinkedList.addFirst(yourEvent)
    And in paint() you do AWTEvent ev = (AWTEvent)theLinkedList.removeLast();
    process ev.
    if(theLinkedList.size() > 0)
       repaint();Yes. I have run into the same problem, and I did not use the repaint- trick...
    My applet communicates with the server in a separate thread. When a response receives the communication thread should post an event to the AWT- thread to get the response processed.
    My solution here is to process the thread in the communicator- thread. This is a bad solution because it might create multithreading bugs.... but it has proven to work ok in practice.
    Another example is like this. The use presses the mouse at Component B so that:
    1 Component A gets a focusLost event.
    2 Component B gets a mousePressed.
    3 I want to do something in component A that should be done after component B has processed the mousePressed event. This can be solved without using events. You just have to write some more code (You are already in the right thread).

  • JTabel double click event

    Hello,
    Is there a way to let a JTable listen to a double click event? I know that you can easily get the selection by a 1 click, but now I want that when there is double clicked an action happens (in this case a popup with a question).
    For the double click event, I think you best could use the mousePressed event together with the int getClickCount(). Can you put that mousePressedEvent on the ListSelectListener and than count the amount of clicks and if 2 or more you fire an action (popup)?
    Grtz

    Using MouseAdapter is a nicety, because you OVERRIDE only the methods you need. In this case mouseClicked(MouseEvent mouseEvent). You did not have to implement all the methods defined in the http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/MouseListener.html interface.
    The @override annotation should be there because you have just overridden a method already defined in a super class. The main reason is for compiler checking. It basically marks the method, then if the compiler sees the method does not override anything it will complain (For example someone changed the super classes methods name and you did not realise, in this case the compiler will fail because it no longer overrides anything, and you know you need to fix it...i.e. rename your method to match).
    So it's not imperative you add the annotation but it can save you some anguish.... especially if you deal with alot of third party library's that do not maintain backwards compatibility.
    http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html
    "@Override—the @Override annotation informs the compiler that the element is meant to override an element declared in a superclass "
    Edited by: rh---gnt on Jan 7, 2010 7:56 AM

  • Mouse_Exited without event?

    Hello,
    Situation:
    in my application, I open up a new window (singelton). There I have a "close"-Button with a mouse_over effect. When I close the window and reopen it with this button, the button is still selected, because no mouse_exited has taken place.
    Question:
    How can I simulate the Mouse event or set back the status of the button?
    Thanks,
    Wolfgang

    What you could do is add a mouse listener to your component, and when you detect a mousePressed event, set an internal flag like "buttonDown" or something so that your componentResized method knows when to ignore that event. Maybe something like this:
      myComponent.addMouseListener(new MouseAdapter()
        public void mousePressed(MouseEvent e)
          mouseButtonDown = true;
        public void mouseReleased(MouseEvent e)
          mouseButtonDown = false;
      myComponent.addComponentListener(new ComponentAdapter()
        public void componentResized(ComponentEvent e)
          if (mouseButtonDown)
            return;
          // now do whatever

  • CDC mousePressed Bug (in J9)

    I have found a horrid bug in IBM's J9 CDC implementation.
    The way they have implemented popup trigger is by placing it in the mousePressed event. Since the trigger on PocketPC is to hold the pen on the screen for a "while", this means the mousePressed event is not delivered straight away.
    The result of this is that the application does not know when the pen hits the screen, but only at some point later! this makes all kinds of stuff impossible; from signature captures to drawing apps, to custom on screen keyboards... loads of stuff.
    It is sounding like IBM does not regard this as a bug but a feature of the platform. I do not agree with this at all, as it is just poorly implemented. If the trigger was placed in the mouseRelaesed event the mousePressed event could be delivered striaght away, and the trigger could be detected from the difference in time beteeen the press and release (providing no or little mouse movement ocurred in the elaped time). This is not a tricky fix by any means.
    Anyway, to my point;
    Surely the certification for whether a CDC platform is compliant or not should cover obvious things like making sure events happened when they are meant to. After all, mousePressed() is called that for a very good reason! maybe mousePressedSomeTimeAgo() would be better ;)

    Hi,
    I tried both Socket and Connector.
    For Socket take:
            try {
                Socket sock = new Socket("61.31.254.13", 4004);
                OutputStream out = sock.getOutputStream();
                out.write("hello".getBytes());
                // start another reader thread...
            } catch (Exception ex) {
                ex.printStackTrace();
            }Exceptions look like:
    java.net.ConnectException:61.31.254.13/61.31.254.13:4004 - Operation failed: 10065 (FormatMessage failed: 317)
            at java.net.PlainSocketImpl.connect(Unkown Source)
            at java.net.Socket.startupSocket(Unkown Source)
            at java.net.Socket.<init>(Unkown Source)
            ....For Connector take:
            try {
                StreamConnection c = (StreamConnection) Connector.open("socket://61.31.254.13:4004");
                OutputStream out = c.openOutputStream();
                out.write("hello".getBytes());
                // start another reader thread...
            } catch (Exception ex) {
                ex.printStackTrace();
            }Exceptions:
    javax.microedition.io.ConnectionNotFoundException: Cound not establish connection: (61.31.254.13) 61.31.254.13:4004 - Operation failed: 10065 (FormatMessage failed: 317)
            at com.ibm.oti.connection.socket.Connection.setParameters(Unknown Source)
            at com.ibm.oti.connection.socket.Connection.setParameters(Unknown Source)
            at javax.microedition.io.Connector.open(Unknown Source)
            at javax.microedition.io.Connector.open(Unknown Source)
            ... ...Please note that the above 2 takes both work when gprs connection is opened manually.
    Thanks.
    JC.L

  • Mouse status without event?

    Is there any way to get information about the mouse (e.g., which buttons if any are pressed) without an MouseEvent?
    I'm listening for Component events, and in the componentResized method I'd like to know if the mouse button is down so I can ignore the resizing events until the user is done resizing. There's no "isAdjusting" option like JSlider has.
    Thanks.
    -J

    What you could do is add a mouse listener to your component, and when you detect a mousePressed event, set an internal flag like "buttonDown" or something so that your componentResized method knows when to ignore that event. Maybe something like this:
      myComponent.addMouseListener(new MouseAdapter()
        public void mousePressed(MouseEvent e)
          mouseButtonDown = true;
        public void mouseReleased(MouseEvent e)
          mouseButtonDown = false;
      myComponent.addComponentListener(new ComponentAdapter()
        public void componentResized(ComponentEvent e)
          if (mouseButtonDown)
            return;
          // now do whatever

  • JPanel key events blocked by JToolBar?

    I have a JPanel that I'm drawing on, and the frame containing the panel also holds a JToolBar. The JPanel doesn't catch any KeyEvents, which I really would like to monitor.
    I have overridden isFocusable() as suggested in another thread like so:
    public boolean isFocusable()
    return true;
    }My JPanel still doesn't catch KeyEvents, unless I get rid of the JToolBar. It seems that the controls in the toolbar don't pass the focus on to the panel. How do I change this behavior, without removing the toolbar?

    Found the answer elsewhere.
    I now add a "requestFocus()" call in my mousePressed event handler, and the JPanel catches the key events again.

  • Timer Class not accurate and slows down my animation!?

    Does anyknow how why my timer object is not accurate and why it slows down my animation that is also present on my GUI at the same time?
    I have a timer in the form of 0.00 the left of the decimal point should represent a second but it doesnt, run my code and see for yourselves. below is my code if anyone can fix these 2 problems i will be very thankfull:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Shape;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.Timer;
    import java.sql.*;
    import java.text.*;
    public class RT extends JFrame implements MouseMotionListener
        //declares a number of swing componets to be used for the JFrame
        private JTextArea infoJTextArea;
        private JPanel showJPanel, startJPanel, helpJPanel, resultsJPanel;
        private JLabel de4JLabel, de3JLabel, mainTitleJLabel, nameJLabel, ageJLabel,
                       deJLabel, de1JLabel, de2JLabel, timeJLabel,nameResultJLabel,
                       ageResultJLabel, timeResultsJLabel, ratingJLabel, coJLabel, shJLabel;
        private JTextField nameJTextField, ageJTextField,nameResultJTextField,
                       ageResultsJTextField, timeResultsJTextField, ratingJTextField;
        private JButton exitJButton, showJButton, loginJButton, startTestJButton,
                        tempObjectJButton;
        private JScrollPane scroll;
    public JComboBox colourJComboBox, sizeJComboBox, shapeJComboBox, speedJComboBox;
    private static Connection dbcon;
    int temp=0;
    private String[] col = { "Red", "Blue", "Green","Yellow","Orange","Black"};
    private String[] shapeA = { "Normal Rectangle", "Normal Circle", "Normal Oval","BIG Rectangle", "BIG Circle","BIG Oval","small rectangle","small circle", "small oval"};
    private String[] speed = { "Fast", "Normal", "Slow"};
    public int checking;
    static int flag, flagshape, flagspeed;
        // creates and sets up a number of varibles to be used by the class
        public long timeLimit = 0;
        DecimalFormat timeDec = new DecimalFormat (":00");
        public int age;
        public String name, shapeChoice="Normal Rectangle(Never selected anything)", colourChoice="Black(Never selected anything)";
        private Timer TimeNow;
        private JTextField timerJTextField;
        ShapeMovingPanel testJPanel;
        Random seed;
        Shape shape;
        Shape[] shapes = {new Rectangle2D.Double(50, 30, 75, 25),new Ellipse2D.Double(175, 125, 50, 50),new Ellipse2D.Double(90, 100, 75, 35),new Rectangle2D.Double(50, 30, 175, 125),new Ellipse2D.Double(175, 125, 125, 125),new Ellipse2D.Double(90, 100, 175, 135),new Rectangle2D.Double(50, 30, 55, 15),new Ellipse2D.Double(175, 125, 20,20),new Ellipse2D.Double(90, 100, 55, 15)};
    //50, 30, 75, 25 change starting point here****************************************
        public RT()            // constructor method
            seed = new Random();
            shape = shapes[0];
            //sets up the Timer
            TimeNow = new Timer((1), new TimerListener());//++++++++++++++++++++++++++timer -17
            createUserInterface();          // method that creates the user interface     
        private void createUserInterface()
            new Thread(new Runnable()
                public void run()
                    String results = "";
                    int count = 0;
                    boolean journeyOn = true;
                    while(journeyOn && count < 3)
                        try
                            Thread.sleep(1000);
                        catch(InterruptedException ie)
                            System.err.println("show interrupt: " + ie.getMessage());
                            journeyOn = false;
                        results += count++ + ", ";
                    try {
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                             dbcon = DriverManager.getConnection("jdbc:odbc:CMT3991", "", ""); // Access/ODBC
                          //connection ash used to connect to the user table in access
                           } catch(Exception eee)
                           eee.printStackTrace();  //exception if error occurs during the driver connection
                             System.out.println("* UserDA CONNECTED *");
            }).start();
            Container contentPane = getContentPane();
            contentPane.setLayout( null );
            // set up infoJTextField
            infoJTextArea = new JTextArea();
            infoJTextArea.setBounds( 20, 420, 550, 170  );
            infoJTextArea.setEditable( false);
            infoJTextArea.setText("\n    Welcome to the reaction testing program, this " +
                            "program is designed to test your reactions in a  \n"+
                            "    number of different situations.\n"+"\n    Please " +
                            "enter your name and age, or select show previous results.");
            contentPane.add( infoJTextArea );
            scroll = new JScrollPane(infoJTextArea);
            scroll.setBounds(  20, 420, 550, 170 );
            contentPane.add( scroll );
                  startJPanel = new JPanel();
            startJPanel.setBounds( 16,16, 560, 375 );
            startJPanel.setBorder(
                    new TitledBorder( "WELCOME - PLEASE ENTER YOUR NAME AND AGE:" ) );
            startJPanel.setLayout( null );
            contentPane.add( startJPanel );
            //sets up a JPanel
            mainTitleJLabel = new JLabel();
            mainTitleJLabel.setIcon( new ImageIcon( "title.png" ) );
            mainTitleJLabel.setBounds( 30, 10, 520, 170 );
            mainTitleJLabel.setHorizontalAlignment( JLabel.CENTER );
            startJPanel.add( mainTitleJLabel );
            //creates a newJLabel
            nameJLabel= new JLabel();
            nameJLabel.setBounds( 52, 200, 70, 35 );
            nameJLabel.setText("Name:");
            startJPanel.add( nameJLabel);
            //creates a new JTextField
            nameJTextField = new JTextField();
            nameJTextField.setBounds( 130, 200, 300, 24 );
            startJPanel.add( nameJTextField );
            //creates a newJLabel
            ageJLabel = new JLabel();
            ageJLabel.setBounds( 52, 245, 100, 35 );
            ageJLabel.setText("Age:");
            startJPanel.add( ageJLabel );
            //creates a new JTextField
            ageJTextField = new JTextField();
            ageJTextField.setBounds( 130, 245, 300, 24 );
            startJPanel.add( ageJTextField );
            //creates a JButton
            loginJButton = new JButton();
            loginJButton.setBounds( 440, 200, 90, 24 );
            loginJButton.setText( "Login" );
            loginJButton.setBackground( Color.YELLOW );
            startJPanel.add( loginJButton );
            loginJButton.setEnabled(true);
    //        loginJButton.setVisible(true);
            loginJButton.addActionListener(
                new ActionListener()    // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                        // not necessary to pass events to these methods...
                        Login();  // calls the Login method                       
            //creates a JButton
            showJButton = new JButton();
            showJButton.setBounds( 200, 320, 180, 24 );
            showJButton.setText( "Show previous results" );
            showJButton.setBackground( Color.YELLOW );
            startJPanel.add( showJButton );
            showJButton.setEnabled(true);
    //        showJButton.setVisible(true);
            showJButton.addActionListener(
                new ActionListener()    // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                        showData();   // calls the showData method                       
            //sets up a JPanel
            showJPanel = new JPanel();
            showJPanel.setBounds( 16,16, 560, 375 );
            showJPanel.setBorder(new TitledBorder( "PREVIOUS RESULTS:" ) );
            showJPanel.setLayout( null );
            contentPane.add( showJPanel );
            //sets up a JPanel
            helpJPanel = new JPanel();
            helpJPanel.setBounds( 16,16, 560, 375 );
            helpJPanel.setBorder(
            new TitledBorder( "CHOOSE A NUMBER OF OPTIONS AND GET READY:" ) );
            helpJPanel.setLayout( null );
            helpJPanel.setVisible(false);
            contentPane.add( helpJPanel );
            //creates a newJLabel
            deJLabel= new JLabel();
            deJLabel.setBounds( 23, 390, 530, 35 );
            deJLabel.setText("Details:");
            contentPane.add( deJLabel);
            //creates a newJLabel
            coJLabel= new JLabel();
            coJLabel.setBounds( 70, 40, 530, 35 );
            coJLabel.setText("Choose a colour:");
            helpJPanel.add( coJLabel);
            //creates a newJLabel
            de1JLabel= new JLabel();
            de1JLabel.setBounds( 25, 100, 530, 35 );
            de1JLabel.setText("You are about to start the reaction test, when you " +
                              "press the start button it will begin.");
            helpJPanel.add( de1JLabel);
            //creates a newJLabel
            de1JLabel= new JLabel();
            de1JLabel.setBounds(160, 145, 530, 35 );
            de1JLabel.setText("Simply catch the moving item and click.");
            helpJPanel.add( de1JLabel);
            colourJComboBox = new JComboBox( col );
               colourJComboBox.setBounds( 70, 70, 135, 21 );
               colourJComboBox.setMaximumRowCount( 3 );
               helpJPanel.add( colourJComboBox );
              colourJComboBox.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                         colourChoice="Black";
                         int x = colourJComboBox.getSelectedIndex();
                        if( x  == 0)
                             flag = 1;
                             colourChoice="Red";
                        else if(x  == 1)
                             flag = 2;
                             colourChoice="Blue";
                        else if(x  == 2)
                             flag = 3;
                                colourChoice="Green";
                         else if(x  == 3)
                             flag = 4;
                                colourChoice="Yellow";
                         else if(x  == 4)
                             flag = 5;
                                colourChoice="Orange";
                           else if(x  == 5)
                             flag = 6;
                                colourChoice="Black";
            shJLabel= new JLabel();
            shJLabel.setBounds( 340, 40, 530, 35 );
            shJLabel.setText("Choose a shape and size:");
            helpJPanel.add( shJLabel);
            shapeJComboBox = new JComboBox( shapeA );
               shapeJComboBox.setBounds( 340, 70, 135, 21 );
               shapeJComboBox.setMaximumRowCount( 3 );
               helpJPanel.add( shapeJComboBox );
              shapeJComboBox.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                          int xshape = shapeJComboBox.getSelectedIndex();
                        //shapeChoice="Normal Rectangle";
                        if( xshape  == 0)
                        {     flagshape = 1;
                             shapeChoice="Normal Rectangle";
                        else if(xshape  == 1)
                        {     flagshape = 2;
                             shapeChoice="Normal Circle";
                        else if(xshape  == 2)//**********here
                        {     flagshape = 3;
                             shapeChoice="Normal Oval";
                        else if(xshape  == 3)
                        {     flagshape = 4;
                             shapeChoice="BIG Rectangle";
                        else if(xshape  == 4)
                       {      flagshape = 5;
                             shapeChoice="BIG Circle";
                        else if(xshape  == 5)
                     {        flagshape = 6;
                             shapeChoice="BIG Oval";
                        else if(xshape  == 6)
                             flagshape = 7;
                             shapeChoice="small rectangle";
                        else if(xshape  == 7)
                     {        flagshape = 8;
                             shapeChoice="small circle";
                        else if(xshape  == 8)
                     {        flagshape = 9;
                             shapeChoice="small oval";
          /*  speedJComboBox = new JComboBox( speed );
               speedJComboBox.setBounds( 10, 150, 135, 21 );
               speedJComboBox.setMaximumRowCount( 3 );
               helpJPanel.add( speedJComboBox );
              speedJComboBox.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                          int xspeed = speedJComboBox.getSelectedIndex();
                        if( xspeed  == 0)
                             flagspeed = 1;
                             else if(xspeed  == 1)
                             flagspeed = 2;
                             else
                             flagspeed = 3;
                        System.out.println(flagspeed);     
            //creates a newJLabel
            de2JLabel= new JLabel();
            de2JLabel.setBounds( 20, 380, 70, 35 );
            de2JLabel.setText("Details:");
            helpJPanel.add( de2JLabel);
            //creates a JButton
            startTestJButton = new JButton();
            startTestJButton.setBounds( 185, 205, 180, 60 );
            startTestJButton.setText( "START" );
            startTestJButton.setBackground( Color.YELLOW );
            helpJPanel.add( startTestJButton );
            startTestJButton.setEnabled(true);
    //        startTestJButton.setVisible(true);
            startTestJButton.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                        startTest();
            //sets up an animation panel
            testJPanel = new ShapeMovingPanel(this);
            testJPanel.setBounds( 16,16, 560, 375 );
            testJPanel.setBorder(new TitledBorder("Click the moving object:"));
            testJPanel.setLayout( null );
            testJPanel.setVisible(false);
            contentPane.add( testJPanel );
            testJPanel.addMouseMotionListener(this);
            //creates a newJLabel
            timeJLabel = new JLabel();
            timeJLabel.setBounds( 440, 330, 100, 35 );
            timeJLabel.setText("Time:");
            testJPanel.add( timeJLabel );
            //creates a new JTextField
            timerJTextField = new JTextField();
            timerJTextField.setBounds( 480, 335, 60, 24 );
            timerJTextField.setText(String.valueOf(timeLimit));
            timerJTextField.setHorizontalAlignment(JTextField.CENTER );
            timerJTextField.setEditable(false);
            timerJTextField.setBackground( Color.YELLOW );
            testJPanel.add( timerJTextField );
            resultsJPanel = new JPanel();
            resultsJPanel.setBounds( 16,16, 560, 375 );
            resultsJPanel.setBorder(new TitledBorder("HERE ARE YOUR RESULTS:"));
            resultsJPanel.setLayout( null );
            resultsJPanel.setVisible(false);
            contentPane.add( resultsJPanel );
            de3JLabel= new JLabel();
            de3JLabel.setBounds(20, 200, 530, 35 );
            de3JLabel.setText("Below is also the movements you made with your mouse, " +
                              "you may exit the program now.");
            resultsJPanel.add( de3JLabel);
            de4JLabel= new JLabel();
            de4JLabel.setBounds(135, 245, 530, 35 );
            de4JLabel.setText("Thank you for trying the Reaction Testing program");
            resultsJPanel.add( de4JLabel);
            //creates a newJLabel
            nameResultJLabel= new JLabel();
            nameResultJLabel.setBounds( 62, 55, 50, 35 );
            nameResultJLabel.setText("Name:");
            resultsJPanel.add( nameResultJLabel);
            //creates a new JTextField
            nameResultJTextField = new JTextField();
            nameResultJTextField.setBounds( 140, 55, 300, 24 );
            resultsJPanel.add( nameResultJTextField );
            nameResultJTextField.setEditable(false);
            //creates a newJLabel
            ageResultJLabel = new JLabel();
            ageResultJLabel.setBounds( 62, 90, 100, 35 );
            ageResultJLabel.setText("Age:");
            resultsJPanel.add( ageResultJLabel );
            //creates a new JTextField
            ageResultsJTextField = new JTextField();
            ageResultsJTextField.setBounds( 140, 90, 300, 24 );
            resultsJPanel.add( ageResultsJTextField );
            ageResultsJTextField.setEditable(false);
            //creates a newJLabel
            timeResultsJLabel = new JLabel();
            timeResultsJLabel.setBounds( 62, 125, 100, 35 );
            timeResultsJLabel.setText("Time taken:");
            resultsJPanel.add( timeResultsJLabel );
            //creates a new JTextField
            timeResultsJTextField = new JTextField();
            timeResultsJTextField.setBounds( 140, 125, 300, 24 );
            resultsJPanel.add( timeResultsJTextField );
            timeResultsJTextField.setEditable(false);
            //creates a newJLabel
            ratingJLabel = new JLabel();
            ratingJLabel.setBounds( 62, 160, 100, 35 );
            ratingJLabel.setText("Your Rating:");
            resultsJPanel.add( ratingJLabel );
            ratingJTextField = new JTextField();
            ratingJTextField.setBounds( 140, 160, 300, 24 );
            resultsJPanel.add( ratingJTextField );
            ratingJTextField.setEditable(false);
            //creates a JButton
            exitJButton = new JButton();
            exitJButton.setBounds( 235, 310, 90, 24 );
            exitJButton.setText( "Exit" );
            exitJButton.setBackground( Color.WHITE );
            resultsJPanel.add( exitJButton );
            exitJButton.setEnabled(true);
            exitJButton.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when exitJButton is pressed
                    public void actionPerformed( ActionEvent event )
                        System.exit(0); //closes the programme
            }); // end anonymous inner class
            addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            // set properties of application's window
            setTitle( "Reaction Tester - CMT3991" ); // set JFrame's title bar string
            //setSize( 1280,995 );    // set width and height of JFrame
            setSize( 608, 650 );         // set width and height of JFrame
            setVisible( true );       // display JFrame on screen
        //** set up of method main */
        public static void main( String[] args )
            RT application = new RT();
            application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        } // end method main
         * action listener for TimeNow Timer
        private class TimerListener implements ActionListener
            public void actionPerformed(ActionEvent event)
                timeLimit ++;          
                if (timeLimit==100)
                     temp++;
                     timeLimit=0;
                timerJTextField.setText(String.valueOf(temp +""+timeDec.format(timeLimit)));
        private void Login()
            try
                name = nameJTextField.getText();
                age = Integer.parseInt(ageJTextField.getText());
                startJPanel.setVisible(false);
                showJPanel.setVisible(false);
                helpJPanel.setVisible(true);
                infoJTextArea.setText("\n    Welcome "+name+" you will soon know how " +
                                      "fast your reactions are.");
            catch (NumberFormatException exception)
                JOptionPane.showMessageDialog(this,
                        "There is either a blank field or a number hasn't been entered",
                        "Input Type error", JOptionPane.ERROR_MESSAGE);
                //shows this is something has been entered wrong
        private void startTest()
            helpJPanel.setVisible(false);
          //  System.out.println(""+ seed.nextInt(shapes.length));
            //shape = shapes[seed.nextInt(shapes.length)];//****************************
            if (flagshape==1)
                 shape = shapes[0];// changed colour here***************************
            else if (flagshape==2)
                 shape = shapes[1];// changed colour here***************************
            else if (flagshape==3)
                 shape = shapes[2];// changed colour here***************************
           else if (flagshape==4)
                 shape = shapes[3];// changed colour here***************************
             else if (flagshape==5)
                 shape = shapes[4];// changed colour here***************************
            else if (flagshape==6)
                 shape = shapes[5];// changed colour here***************************
            else if (flagshape==7)
                 shape = shapes[6];// changed colour here***************************
            else if (flagshape==8)
                 shape = shapes[7];// changed colour here***************************
            else if (flagshape==9)
                 shape = shapes[8];// changed colour here***************************
           // shape = shapes[8];
            System.out.println(shape.toString());
            testJPanel.setShape(shape);
            testJPanel.setVisible(true);
            testJPanel.start();
            infoJTextArea.setText("");
            TimeNow.start();
         * called by animation panel after shape is clicked
        public void stop()
            TimeNow.stop();
            movingObject();
         * this will compete with your animation
         * ie, it will slow it down or make it appear jerky
        public void mouseMoved(MouseEvent e)
            saySomething("\n    Mouse moved", e);
        public void mouseDragged(MouseEvent e)
            saySomething("\n    Mouse dragged", e);
        void saySomething(String eventDescription, MouseEvent e)
            infoJTextArea.append(eventDescription
                         + " (" + e.getX() + "," + e.getY() + ")");
            infoJTextArea.setCaretPosition(infoJTextArea.getDocument().getLength());
        private void movingObject()
            TimeNow.stop();
            //timeLimit;
            testJPanel.setVisible(false);
            resultsJPanel.setVisible(true);
            nameResultJTextField.setText(name);
            ageResultsJTextField.setText(String.valueOf(age)+" years old");
    System.out.println("shape used: "+shapeChoice);
            String mouse = infoJTextArea.getText();
            String tick = timerJTextField.getText();
            timeResultsJTextField.setText(tick);
            try
                // create a file called welch.txt
                final FileWriter outputFile = new FileWriter("Backup_of_"+name+"s_results.txt", true);
                final BufferedWriter outputBuffer = new BufferedWriter(outputFile);
                // converts data to a formatted string
                final PrintWriter printstream = new PrintWriter(outputBuffer);
                printstream.println("THIS IS A BACKUP");
                printstream.println("The person's name is: "+name);
                printstream.println("There age is: "+age);
                printstream.println("Time taken: "+tick+" seconds");
                printstream.println("The Shape and size was: "+shapeChoice);
                printstream.println("It's colour was: "+colourChoice);
                printstream.println("The mouse moved as follows: "+mouse);
                //states what needs to be printed to the new file
                printstream.close(); // closes teh printstream
            catch(IOException eio)
                //catchs the IO exception
            if(temp<5.00)
                ratingJTextField.setText("Thierry Henry");     
            else if(timeLimit<=10)
                ratingJTextField.setText("Average");     
            else if(timeLimit<=15)
                ratingJTextField.setText("You gotta be fat or something");     
            else if(timeLimit<=20)
                ratingJTextField.setText("See a doctor");
            else if(timeLimit>20)
                ratingJTextField.setText("DO YOU KNOW WHAT YOU DOING!?");
            String rate=ratingJTextField.getText();
            try
                   Statement st = dbcon.createStatement();
                   String cmd = "INSERT INTO users (Name, Age, Time_Taken, Rating, Mouse_Movement,Shape_and_Size, Shape_Colour) VALUES ('" + name + "' , " + age + " , '" + tick + "' , '" + rate+"','"+ mouse+"','"+ shapeChoice+"','"+ colourChoice+"');";
                //creates a SQL statement and executes it
                st.executeUpdate(cmd);
                   st.close();//close the statement
              } catch (Exception eDA)
                   eDA.printStackTrace();
        private void showData()
            // pretend this takes awhile -> 3 seconds (count)
            new Thread(new Runnable()
                public void run()
                    String results = "";
                    int count = 0;
                    boolean journeyOn = true;
                    while(journeyOn && count < 3)
                        try
                            Thread.sleep(1000);
                        catch(InterruptedException ie)
                            System.err.println("show interrupt: " + ie.getMessage());
                            journeyOn = false;
                        results += count++ + ", ";
                    infoJTextArea.setText("Here are your results:\n"+results);
                    startJPanel.setVisible(false);
                    showJPanel.setVisible(true);
            }).start();
    class ShapeMovingPanel extends JPanel implements ActionListener
        RT host;
        Timer timer;
        Shape shape, xformed;
        int x, y, dx, dy;
        public ShapeMovingPanel(RT rt)
            timer = new Timer(-20, this);     
            host = rt;
        /*    if (rt.flagspeed==1)
            timer = new Timer(-20, this);
            else if (rt.flagspeed==2)
                timer = new Timer(20, this);
            else if (rt.flagspeed==3)
            timer = new Timer(100, this);
            //change speed here******************************
            x = 0;//0
            y = 0;//0
            dx =2;//2
            dy = 3;//3
            //setBackground(Color.pink);
            addMouseListener(new ShapeTender());
        public void actionPerformed(ActionEvent e)
            int w = getWidth();
            int h = getHeight();
            if(w <= 0 || h <= 0)
                return;
            checkBoundries(w,h);
            x += dx;
            y += dy;
            repaint();
        private void checkBoundries(int w, int h)
            Rectangle r = xformed.getBounds();
            Insets insets = getInsets();
            if(r.x + dx < insets.left || r.x + r.width + dx > w - insets.right)
                dx *= -1;
            if(r.y + dy < insets.top || r.y + r.height + dy > h - insets.bottom)
                dy *= -1;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            if (RT.flag==1)
            {g2.setPaint(Color.red);// changed colour here***************************
            else if (RT.flag==2)
            {g2.setPaint(Color.blue);// changed colour here***************************
            else if (RT.flag==3)
            {g2.setPaint(Color.green);// changed colour here***************************
            else if (RT.flag==4)
            {g2.setPaint(Color.yellow);// changed colour here***************************
            else if (RT.flag==5)
            {g2.setPaint(Color.orange);// changed colour here***************************
            else if (RT.flag==6)
            {g2.setPaint(Color.black);// changed colour here***************************
            xfo                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

    I'm (being lazy and) using the older RT app posted on your last thread. I removed the
    TimeNow timer from the RT class and used System.currentTimeMillis (as you requested) to
    determine the elapsed time during the animation (see "startTest", "stop" and
    "movingObject" methods). Also changed the DecimalFormat to NumberFormat and set the
    "maximumFractionDigits" to "2" so it will truncate the fraction to two digits (more simple
    than before). Made arrangements for the ShapeMovingPanel class to update the
    "timerJTextField" during the animation (RT.updateTime method).
    The MouseMotionListener is causing the animation to appear jerky and uneven. The
    "mouseMoved" method is very busy while the mouse is moving. You might consider recording
    the "mousePressed" events instead of the "mouseMoved" events, ie, the events where the user
    is attempting to click inside the moving shape. It would allow the app to be more
    responsive and might eliminate the uneven motion of the animating shape.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.Timer;
    public class RT extends JFrame implements MouseMotionListener
        //declares a number of swing componets to be used for the JFrame
        private JTextArea infoJTextArea;
        private JPanel showJPanel, startJPanel, helpJPanel, resultsJPanel;
        private JLabel de4JLabel, de3JLabel, mainTitleJLabel, nameJLabel, ageJLabel,
                       deJLabel, de1JLabel, de2JLabel, timeJLabel,nameResultJLabel,
                       ageResultJLabel, timeResultsJLabel, ratingJLabel;
        private JTextField nameJTextField, ageJTextField,nameResultJTextField,
                       ageResultsJTextField, timeResultsJTextField, ratingJTextField;
        private JButton exitJButton, showJButton, loginJButton, startTestJButton,
                        tempObjectJButton;
        private JScrollPane scroll;;
        // creates and sets up a number of varibles to be used by the class
        private long startTime;
        private long endTime;
        public int timeLimit = 0;
        public int age;
        public String name;
        private JTextField timerJTextField;
        ShapeMovingPanel testJPanel;
        NumberFormat timeDec;
        Random seed;
        Shape shape;
        Shape[] shapes = {
            new Rectangle2D.Double(50, 30, 75, 25),
            new Ellipse2D.Double(175, 125, 50, 50),
            new Ellipse2D.Double(90, 100, 75, 35)
        public RT()
            timeDec = NumberFormat.getInstance();
            timeDec.setMaximumFractionDigits(2);
            seed = new Random();
            shape = shapes[0];
            createUserInterface();
        private void createUserInterface()
            Container contentPane = getContentPane();
            contentPane.setLayout( null );
            // set up infoJTextField
            infoJTextArea = new JTextArea();
            infoJTextArea.setBounds( 20, 420, 550, 170  );
            infoJTextArea.setEditable( false);
            infoJTextArea.setText("\n    Welcome to the reaction testing program, this " +
                            "program is designed to test your reactions in a  \n"+
                            "    number of different situations.\n"+"\n    Please " +
                            "enter your name and age, or select show previous results.");
            contentPane.add( infoJTextArea );
            scroll = new JScrollPane(infoJTextArea);
            scroll.setBounds(  20, 420, 550, 170 );
            contentPane.add( scroll );
              startJPanel = new JPanel();
            startJPanel.setBounds( 16,16, 560, 375 );
            startJPanel.setBorder(
                    new TitledBorder( "WELCOME -PLEASE ENTER YOUR NAME AND AGE:" ) );
            startJPanel.setLayout( null );
            contentPane.add( startJPanel );
            //sets up a JPanel
            mainTitleJLabel = new JLabel();
            mainTitleJLabel.setIcon( new ImageIcon( "title.png" ) );
            mainTitleJLabel.setBounds( 30, 10, 520, 170 );
            mainTitleJLabel.setHorizontalAlignment( JLabel.CENTER );
            startJPanel.add( mainTitleJLabel );
            //creates a newJLabel
            nameJLabel= new JLabel();
            nameJLabel.setBounds( 52, 200, 70, 35 );
            nameJLabel.setText("Name:");
            startJPanel.add( nameJLabel);
            //creates a new JTextField
            nameJTextField = new JTextField();
            nameJTextField.setBounds( 130, 200, 300, 24 );
            startJPanel.add( nameJTextField );
            //creates a newJLabel
            ageJLabel = new JLabel();
            ageJLabel.setBounds( 52, 245, 100, 35 );
            ageJLabel.setText("Age:");
            startJPanel.add( ageJLabel );
            //creates a new JTextField
            ageJTextField = new JTextField();
            ageJTextField.setBounds( 130, 245, 300, 24 );
            startJPanel.add( ageJTextField );
            //creates a JButton
            loginJButton = new JButton();
            loginJButton.setBounds( 440, 200, 90, 24 );
            loginJButton.setText( "Login" );
            loginJButton.setBackground( Color.YELLOW );
            startJPanel.add( loginJButton );
            loginJButton.setEnabled(true);
            loginJButton.addActionListener(
                new ActionListener()    // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                        // not necessary to pass events to these methods...
                        Login();  // calls the Login method                       
            //creates a JButton
            showJButton = new JButton();
            showJButton.setBounds( 200, 320, 180, 24 );
            showJButton.setText( "Show previous results" );
            showJButton.setBackground( Color.YELLOW );
            startJPanel.add( showJButton );
            showJButton.setEnabled(true);
            showJButton.addActionListener(
                new ActionListener()    // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                        showData();   // calls the showData method                       
            //sets up a JPanel
            showJPanel = new JPanel();
            showJPanel.setBounds( 16,16, 560, 375 );
            showJPanel.setBorder(new TitledBorder( "PREVIOUS RESULTS:" ) );
            showJPanel.setLayout( null );
            contentPane.add( showJPanel );
            //sets up a JPanel
            helpJPanel = new JPanel();
            helpJPanel.setBounds( 16,16, 560, 375 );
            helpJPanel.setBorder(
            new TitledBorder( "HELP DETAILS:" ) );
            helpJPanel.setLayout( null );
            helpJPanel.setVisible(false);
            contentPane.add( helpJPanel );
            //creates a newJLabel
            deJLabel= new JLabel();
            deJLabel.setBounds( 23, 390, 530, 35 );
            deJLabel.setText("Details:");
            contentPane.add( deJLabel);
            //creates a newJLabel
            de1JLabel= new JLabel();
            de1JLabel.setBounds( 25, 100, 530, 35 );
            de1JLabel.setText("You are about to start the reaction test, when you " +
                              "press the start button it will begin.");
            helpJPanel.add( de1JLabel);
            //creates a newJLabel
            de1JLabel= new JLabel();
            de1JLabel.setBounds(160, 145, 530, 35 );
            de1JLabel.setText("Simply catch the moving item and click.");
            helpJPanel.add( de1JLabel);
            //creates a newJLabel
            de2JLabel= new JLabel();
            de2JLabel.setBounds( 20, 380, 70, 35 );
            de2JLabel.setText("Details:");
            helpJPanel.add( de2JLabel);
            //creates a JButton
            startTestJButton = new JButton();
            startTestJButton.setBounds( 185, 205, 180, 60 );
            startTestJButton.setText( "START" );
            startTestJButton.setBackground( Color.YELLOW );
            helpJPanel.add( startTestJButton );
            startTestJButton.setEnabled(true);
            startTestJButton.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when search is pressed
                    public void actionPerformed( ActionEvent event )
                        startTest();
            //sets up an animation panel
            testJPanel = new ShapeMovingPanel(this);
            testJPanel.setBounds( 16,16, 560, 375 );
            testJPanel.setBorder(new TitledBorder("Click the moving object:"));
            testJPanel.setLayout( null );
            testJPanel.setVisible(false);
            contentPane.add( testJPanel );
    // this is causing the animation to appear uneven
    // you can try the app with and without this to see
    //        testJPanel.addMouseMotionListener(this);
            //creates a newJLabel
            timeJLabel = new JLabel();
            timeJLabel.setBounds( 440, 330, 100, 35 );
            timeJLabel.setText("Time:");
            testJPanel.add( timeJLabel );
            //creates a new JTextField
            timerJTextField = new JTextField();
            timerJTextField.setBounds( 480, 335, 60, 24 );
            timerJTextField.setText(String.valueOf(timeLimit));
            timerJTextField.setHorizontalAlignment(JTextField.CENTER );
            timerJTextField.setEditable(false);
            timerJTextField.setBackground( Color.YELLOW );
            testJPanel.add( timerJTextField );
            resultsJPanel = new JPanel();
            resultsJPanel.setBounds( 16,16, 560, 375 );
            resultsJPanel.setBorder(new TitledBorder("HERE ARE YOUR RESULTS:"));
            resultsJPanel.setLayout( null );
            resultsJPanel.setVisible(false);
            contentPane.add( resultsJPanel );
            de3JLabel= new JLabel();
            de3JLabel.setBounds(20, 200, 530, 35 );
            de3JLabel.setText("Below is also the movements you made with your mouse, " +
                              "you may exit the program now.");
            resultsJPanel.add( de3JLabel);
            de4JLabel= new JLabel();
            de4JLabel.setBounds(135, 245, 530, 35 );
            de4JLabel.setText("Thank you for trying the Reaction Testing program");
            resultsJPanel.add( de4JLabel);
            //creates a newJLabel
            nameResultJLabel= new JLabel();
            nameResultJLabel.setBounds( 62, 55, 50, 35 );
            nameResultJLabel.setText("Name:");
            resultsJPanel.add( nameResultJLabel);
            //creates a new JTextField
            nameResultJTextField = new JTextField();
            nameResultJTextField.setBounds( 140, 55, 300, 24 );
            resultsJPanel.add( nameResultJTextField );
            nameResultJTextField.setEditable(false);
            //creates a newJLabel
            ageResultJLabel = new JLabel();
            ageResultJLabel.setBounds( 62, 90, 100, 35 );
            ageResultJLabel.setText("Age:");
            resultsJPanel.add( ageResultJLabel );
            //creates a new JTextField
            ageResultsJTextField = new JTextField();
            ageResultsJTextField.setBounds( 140, 90, 300, 24 );
            resultsJPanel.add( ageResultsJTextField );
            ageResultsJTextField.setEditable(false);
            //creates a newJLabel
            timeResultsJLabel = new JLabel();
            timeResultsJLabel.setBounds( 62, 125, 100, 35 );
            timeResultsJLabel.setText("Time taken:");
            resultsJPanel.add( timeResultsJLabel );
            //creates a new JTextField
            timeResultsJTextField = new JTextField();
            timeResultsJTextField.setBounds( 140, 125, 300, 24 );
            resultsJPanel.add( timeResultsJTextField );
            timeResultsJTextField.setEditable(false);
            //creates a newJLabel
            ratingJLabel = new JLabel();
            ratingJLabel.setBounds( 62, 160, 100, 35 );
            ratingJLabel.setText("Your Rating:");
            resultsJPanel.add( ratingJLabel );
            ratingJTextField = new JTextField();
            ratingJTextField.setBounds( 140, 160, 300, 24 );
            resultsJPanel.add( ratingJTextField );
            ratingJTextField.setEditable(false);
            //creates a JButton
            exitJButton = new JButton();
            exitJButton.setBounds( 235, 310, 90, 24 );
            exitJButton.setText( "Exit" );
            exitJButton.setBackground( Color.WHITE );
            resultsJPanel.add( exitJButton );
            exitJButton.setEnabled(true);
            exitJButton.addActionListener(
                new ActionListener() // adds an action listener,anonymous inner class
                    // event handler called when exitJButton is pressed
                    public void actionPerformed( ActionEvent event )
                        System.exit(0); //closes the programme
            }); // end anonymous inner class
            addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            // set properties of application's window
            setTitle( "Reaction Tester - CMT3991" ); // set JFrame's title bar string
            //setSize( 1280,995 );    // set width and height of JFrame
            setSize( 608, 650 );         // set width and height of JFrame
            setVisible( true );       // display JFrame on screen
        //** set up of method main */
        public static void main( String[] args )
            RT application = new RT();
            application.setDefaultCloseOperation( EXIT_ON_CLOSE );
        } // end method main
        private void Login()
            try
                name = nameJTextField.getText();
                age = Integer.parseInt(ageJTextField.getText());
                startJPanel.setVisible(false);
                showJPanel.setVisible(false);
                helpJPanel.setVisible(true);
                infoJTextArea.setText("\n    Welcome "+name+" you will soon know how " +
                                      "fast your reactions are");
            catch (NumberFormatException exception)
                JOptionPane.showMessageDialog(this,
                        "There is either a blank field or a number hasn't been entered",
                        "Input Type error", JOptionPane.ERROR_MESSAGE);
                //shows this is something has been entered wrong
        private void startTest()
            helpJPanel.setVisible(false);
            shape = shapes[seed.nextInt(shapes.length)];
            testJPanel.setShape(shape);
            testJPanel.setVisible(true);
            testJPanel.start();
            startTime = System.currentTimeMillis();
            infoJTextArea.setText("");
         * called by animation panel after shape is clicked
        public void stop()
            endTime = System.currentTimeMillis();
            movingObject();
         * called by timer actionPerformed in ShapeMovingPanel
        public void updateTime()
            long timeNow = System.currentTimeMillis();
            double elapsed = (timeNow - startTime)/1000.0;
            timerJTextField.setText(timeDec.format(elapsed));
         * this will compete with your animation
         * ie, it will slow it down or make it appear jerky
        public void mouseMoved(MouseEvent e)
            saySomething("\n    Mouse moved", e);
        public void mouseDragged(MouseEvent e)
            saySomething("\n    Mouse dragged", e);
        void saySomething(String eventDescription, MouseEvent e)
            infoJTextArea.append(eventDescription
                         + " (" + e.getX() + "," + e.getY() + ")");
            infoJTextArea.setCaretPosition(infoJTextArea.getDocument().getLength());
        private void movingObject()
            testJPanel.setVisible(false);
            resultsJPanel.setVisible(true);
            nameResultJTextField.setText(name);
            ageResultsJTextField.setText(String.valueOf(age)+" years old");
            double elapsedTime = (endTime - startTime)/1000.0;
            timeLimit = (int)elapsedTime;
            timeResultsJTextField.setText(timeDec.format(elapsedTime)+" seconds");
            String mouse = infoJTextArea.getText();
            String tick = timeDec.format(elapsedTime);
            try
                // create a file called welch.txt
                final FileWriter outputFile = new FileWriter(name+".txt", true);
                final BufferedWriter outputBuffer = new BufferedWriter(outputFile);
                // converts data to a formatted string
                final PrintWriter printstream = new PrintWriter(outputBuffer);
                printstream.println("The person's name is: "+name);
                printstream.println("There age is: "+age);
                printstream.println("Time taken: "+tick+" seconds");
                printstream.println("The mouse moved as follows: "+mouse);
                //states what needs to be printed to the new file
                printstream.close(); // closes teh printstream
            catch(IOException eio)
                //catchs the IO exception
            if(timeLimit<5)
                ratingJTextField.setText("Thierry Henry");     
            if(timeLimit>5)
                ratingJTextField.setText("Average");     
            if(timeLimit>10)
                ratingJTextField.setText("You gotta be fat or something");     
            if(timeLimit>20)
                ratingJTextField.setText("See a doctor");
            String rate=ratingJTextField.getText();
        private void showData()
    //        String results = "";
    //        infoJTextArea.setText("Here are your results:\n"+results);
            startJPanel.setVisible(false);
            showJPanel.setVisible(true);
    class ShapeMovingPanel extends JPanel implements ActionListener
        RT host;
        Timer timer;
        Shape shape, xformed;
        int x, y, dx, dy;
        public ShapeMovingPanel(RT rt)
            host = rt;
            timer = new Timer(25, this);
            x = 0;
            y = 0;
            dx = 2;
            dy = 3;
            setBackground(Color.pink);
            addMouseListener(new ShapeTender());
        public void actionPerformed(ActionEvent e)
            int w = getWidth();
            int h = getHeight();
            if(w <= 0 || h <= 0)
                return;
            checkBoundries(w,h);
            x += dx;
            y += dy;
            repaint();
            // update RT.timerJTextField
            host.updateTime();
        private void checkBoundries(int w, int h)
            Rectangle r = xformed.getBounds();
            Insets insets = getInsets();
            if(r.x + dx < insets.left || r.x + r.width + dx > w - insets.right)
                dx *= -1;
            if(r.y + dy < insets.top || r.y + r.height + dy > h - insets.bottom)
                dy *= -1;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            g2.setPaint(Color.red);
            xformed = at.createTransformedShape(shape);
            g2.draw(xformed);
        public void start()
            if(!timer.isRunning())
                timer.start();
        public void setShape(Shape s)
            shape = s;
            Rectangle r = shape.getBounds();
            x = r.x;
            y = r.y;
            repaint();
        private class ShapeTender extends MouseAdapter
            public void mousePressed(MouseEvent e)
                if(xformed.contains(e.getPoint()))
                    timer.stop();
                    host.stop();
    }

  • Mouse clicks......problems

    Hello.
    i�m using mouse events to run some events in my apps..
    but the problem is that this only occurs once in a while, and it should happen every time i give a double click...
    i�m using the mouseclicked event...is i clicked twice (getmouseclick == 2), then an event is done...but this doesn�t occur always....
    can this be caused because i�m clicking too fast that tha app isn�t catching the clicks?? should i use the mousepressed event??
    thanx

    you can not move the mouse when you click. the mouse has to stay in the same spot when you click and release.

  • Chess Piece display problem in applet

    Hi,
    I'm writing a chess game applet which will be played between to players over the internet. I'm currently working on the applet side at the moment and will develop the server side once I have completed the applet. I'm currently having problems displaying the actual chess pieces on the board at the moment. One of my design decisions was to make a Board class which extends a JPanel. I have painted the actual chess board squares within the Board JPanel. I then propose to draw the pieces on top of these squares (good design decsion? Can anyone suggest another way. I was thinking of having the images as a separate layer which will sit on top of the squares but wasn't sure how to implement it). The chess pieces are contained in a gif strip www.dur.ac.uk/j.d.p.murphy called ChessPieces02.gif . The problem I am having is to display several pieces at the same time. I lloked at a Java tutorial which suggested using g.clipRect() method to display a defined section of the strip (i.e. a single piece of a certain length). Below is the Board class that I am using.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Board extends JPanel{
    // Holds location of the mousePressed event
    Point point = null;
    // Size of a square square on the board
    int square_size = 40;
    // Mediatracker to monitor the loading of the images
    MediaTracker tracker;
    Image image;
    void init() {
    tracker = new MediaTracker(this);
    image = Toolkit.getDefaultToolkit().getImage("ChessPieces02.gif");
    tracker.addImage(image, 0);
    try {
    //Start downloading the images. Wait until they're loaded.
    tracker.waitForAll();
    } catch (InterruptedException e) {
    e.printStackTrace();
    throw new Error("error");
    if (tracker.isErrorAny()) {
    throw new Error("Could not load image");
    addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
    if (point == null)
    point = new Point(0, 0);
    int x = e.getX();
    int y = e.getY();
    System.out.println("X co-ord: " + x + " Y co-ord: " + y);
    // Floor the x and y values to the nearest unit of 25
    x = x - x % square_size;
    y = y - y % square_size;
    point.setLocation(x, y);
    repaint();
    System.out.println(point);
    public void paintComponent(Graphics g) {
    super.paintComponent(g); //paint background
    System.out.println("Chess Board Paint");
    // Loop to produce the black and white squares to represent the board
    for(int jj = 0; jj < 8; jj ++){
    for(int ii = 0; ii < 8; ii++){
    if(ii % 2 == jj % 2)
    g.setColor(Color.white);
    else
    g.setColor(Color.lightGray);
    g.fillRect(ii * square_size, jj * square_size, square_size, square_size );
    // Draw a highlighted square
    if (point != null){
    g.setColor(Color.green);
    g.fillRect( (int)point.getX(), (int)point.getY(), square_size, square_size);
    //imageStrip is the Image object representing the image strip.
    //imageWidth is the size of an individual image in the strip.
    //imageNumber is the number (from 0 to numImages)
    // of the image to paint.
    int stripWidth = image.getWidth(this);
    int stripHeight = image.getHeight(this);
    int imageWidth = stripWidth / 6;
    System.out.println("Width = " + imageWidth);
    g.clipRect(120, 0, imageWidth, stripHeight / 2);
    g.drawImage(image, 0 * imageWidth, 0, this);
    What code do i need to add more pieces to the board? I plan to make a ChessPiece array (8x8) which will holld all the chess pieces on the board. Should I hold this array in the board class to make drawing the pieces easier? Any other tips for game development would also be most welcome.
    Thanks

    cross post, I think.
    http://forum.java.sun.com/thread.jsp?thread=496287&forum=406

  • Clicking on a column without disturbing the existing selection

    Hello good people,
    I am still getting used to Swing and my question may be really silly. Thanks in advance for helping me out!
    I have a JTable in which one of the columns has checkboxes. Using Ctrl+select, one can select multiple rows. Clicking without ctrl, unselects the previous selection. This is all good and default behavior. However, I would like to be able to click on one of the checkboxes in one of the selected rows and not disturb the selection. My target is to enable/disable the checkboxes of all the selected rows.
    Basically, my question is: How do I not disturb the selection if a user clicks in one of the already selected rows and the checkbox column. In other words, if I clicked on the cell (r, c) where row r is already selected and column 'c' is the checkbox column, I would like to retain the selection.
    Thanks,

    what I meant was if you click on the flag cell of one of the selected rows, all the rows (emails) will be flaggedIn my version of Outlook (which is really old) only the row you click on will be flagged and the other rows are deselected.
    But you could try adding a MouseListener to the table. When a mousePressed event is received you could save all the selected rows. You would also add a TableModelListener to the TableModel. Whenever the flag field is selected you could then loop through all the saved selected row and set the flag. You would want to remove the TableModelListener before you start the loop to prevent multiple table model events from being generated. Then when the loop finishes you would need to add the listener back to the model.
    However, this is not a very good solution since it depends on the mousePressed event firing before the ListSelectionModel is updated.

Maybe you are looking for

  • How to invoke secure web service from BPEL in SOA 11g

    In SOA 11g I have a simple bpel process in which I am invoking a secured webservice as partnerlink. The webservice which is used in bpel process is deployed in weblogic and the SSL port is enabled on weblogic server. The wsdl url starts with "https:\

  • Pdf links don't work for imported text

    Hi. I imported some common sections located in their own frame file into three different books. I tried this by reference first because I want to make changes only once, to the actual file. When I make a pdf, the toc links to the imported reference t

  • Help with slideshow, please and thank you

    My brother created a slideshow and sent me the link. I was able to download the slideshow to my desktop. Is there a way to individually move the pictures from the slideshow to an album in iPhoto? When I try moving the whole slideshow or individual pi

  • Script runs exponentially slower as scheduled task

    I have a script that I've run a few times before using Citrix snapins. It runs just fine in the console, generally taking around 20 minutes. When I try to run it as a scheduled task, it never completes. The script is as follows: $time1 = get-date Add

  • Unable to refresh webi report in live office

    I have a webi report and using live office, i want to create a dashboard, i can able to refresh this webi report in infoview but can't in live office, giving an error not sufficient rights. what are the rights to be modified to refresh this report in