JScrollPane Animation

Can someone tell me the proper technique for writing code that will cause the viewport position in a JScrollPane component to scroll smoothly to a given set of coordinates rather than just jumping directly to the new coordinates?
Below is the code I have so far... it sort of works but the animation is not very smooth or consistent... sometimes it scrolls slowly, sometimes it scrolls quickly. I'm also very confused about when or if I should use SwingUtilities.invokeLater or if I should just use normal multi-thread technique or if I should multi-thread at all. The algorithm that calculates the coordinates in the animation is trivial to me; I'm more concerned with the smoothness of the animation which is probably swing or thread related.
public class GameCanvas extends JPanel
     public void panToPoint(final Point p)
          SwingUtilities.invokeLater(new Runnable()
               public void run()
                    Point p1 = getViewPosition(); //convienance method that gets center point of viewport (see below for definition)
                    Point p2 = p;
                    double m = (p2.y - p1.y) / (p2.x - p1.x); //calculate the slope
                    double b = p1.y - (m * p1.x); //calculate the y-intersect
                    for (int x = p1.x; x < p2.x; x++)
                         int y = (int)(m * x + b); //y = mx + b formula from gradeschool
                         setViewPosition(new Point(x, y)); //convienance method that sets center point of viewport (see below for definition)
                         try
                              Thread.sleep(1);
                         catch (Exception ex)
                              ex.printStackTrace();
     public Point getViewPosition()
          Point p = new Point();
          Rectangle r = getVisibleRect();
          p.x = r.x + r.width / 2;
          p.y = r.y + r.height / 2;
          return p;
     public void setViewPosition(final Point p)
          Rectangle r = getVisibleRect();
          r.x = p.x - r.width / 2;
          r.y = p.y - r.height / 2;
          scrollRectToVisible(r);
}Edited by: user6093557 on Feb 25, 2011 9:30 PM
Edited by: user6093557 on Feb 25, 2011 9:34 PM

You should never use Thread.sleep() on the Event Dispatch Thread. This will cause the GUI to freeze.
If you want animation then you should be using a Swing Timer to schedule the animation.

Similar Messages

  • Help needed with project

    Hello everyone. Some help would be appreciated. I have created a wildlife resort database with access.
    It has an animals table with 5 entries, a species table with 3 entries and a user table with 3 entries.
    I have set up a JDBC-ODBC bridge.
    The server side of this application when run gets stuck upon pressing connect the first time so I have to run the server again while the first server window is running in the background and press connect for it to start running. The server works just fine after that. I can add and remove from the tables using the server.
    When I run the client and try to connect it, it doesn't accept the hostname. I can't connect or log in.
    I think the problem is with the threads but I'm not sure what to do to fix it.
    Also I use java beans for coding.
    These are some errors I get when running the client:
    java.lang.IllegalThreadStateException
    at java.lang.ThreadGroup.add(ThreadGroup.java:856)
    at java.lang.Thread.start(Thread.java:573)
    at org.apache.tools.ant.taskdefs.ProcessDestroyer.removeShutdownHook(ProcessDestroyer.java:145)
    at org.apache.tools.ant.taskdefs.ProcessDestroyer.remove(ProcessDestroyer.java:198)
    at org.apache.tools.ant.taskdefs.Execute.execute(Execute.java:487)
    at org.apache.tools.ant.taskdefs.Java.fork(Java.java:746)
    at org.apache.tools.ant.taskdefs.Java.executeJava(Java.java:170)
    at org.apache.tools.ant.taskdefs.Java.execute(Java.java:83)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:64)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.taskdefs.MacroInstance.execute(MacroInstance.java:377)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:275)
    at org.apache.tools.ant.Task.perform(Task.java:364)
    at org.apache.tools.ant.Target.execute(Target.java:341)
    at org.apache.tools.ant.Target.performTasks(Target.java:369)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1214)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1062)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:217)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:236)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:125)
    Exception in thread "Thread-7" java.lang.NullPointerException
    at Client.Connect.connecting(Connect.java:45)
    at Client.ClientGUI.run(ClientGUI.java:214)
    at java.lang.Thread.run(Thread.java:595)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Client.Connect.userPass(Connect.java:206)
    at Client.ClientGUI.actionPerformed(ClientGUI.java:164)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
    at javax.swing.AbstractButton.doClick(AbstractButton.java:302)
    at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1000)
    at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1041)
    at java.awt.Component.processMouseEvent(Component.java:5488)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3093)
    at java.awt.Component.processEvent(Component.java:5253)
    at java.awt.Container.processEvent(Container.java:1966)
    at java.awt.Component.dispatchEventImpl(Component.java:3955)
    at java.awt.Container.dispatchEventImpl(Container.java:2024)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
    at java.awt.Container.dispatchEventImpl(Container.java:2010)
    at java.awt.Window.dispatchEventImpl(Window.java:1766)
    at java.awt.Component.dispatchEvent(Component.java:3803)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:234)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    These are the classes I have created:
    On the client side:
    //imports needed for the GUI and I/O Operations
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    public class ClientGUI extends JFrame implements ActionListener, Runnable {
    JPanel pane = new JPanel();
    //Create the Menubar Items
    JMenuBar bar = new JMenuBar();
    JMenu jMenu1 = new JMenu();
    JMenu jMenu2 = new JMenu();
    JMenu jMenu3 = new JMenu();
    JMenuItem Exit = new JMenuItem();
    JMenuItem Open = new JMenuItem();
    JMenuItem Close = new JMenuItem();
    JMenuItem Find = new JMenuItem();
    static JMenuItem Add = new JMenuItem();
    static JMenuItem Remove = new JMenuItem();
    static JMenuItem Connect1 = new JMenuItem();
    static JMenuItem Disconnect = new JMenuItem();
    static JMenuItem Login = new JMenuItem();
    static JMenuItem Logout = new JMenuItem();
    static boolean check = true;
    static JLabel running = new JLabel("You are not Connected");
    //Creates the animal JTable and adds it to a scrollpane
    public static String[] animalH = {"Id" , "Name" , "Description" , "Species Id"};
    public static Object rows1 [] [] = new Object[40][4];
    public static JTable animal = new JTable(rows1 , animalH);
    JScrollPane animalP;
    //Creates the species JTable and adds it to a scrollpane
    public static String[] speciesH = {"Species Id" , "Species Name"};
    public static Object rows2 [] [] = new Object[40][2];
    public static JTable species = new JTable(rows2 , speciesH);
    JScrollPane speciesP;
    public static Thread runner;
    //Declares Globale variables
    static int currentT;
    int respones;
    static String hostname;
    static boolean connected = false;
    /** Creates a new instance of ClientGUI */
    public ClientGUI() {
    super("SA Wildlife -- Client");
    setSize(800 , 600);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().add(running , BorderLayout.SOUTH);
    Add.setEnabled(false);
    Remove.setEnabled(false);
    Logout.setEnabled(false);
    Disconnect.setEnabled(false);
    try {
    jbInit();
    }catch(Exception e) {
    e.printStackTrace();
    addListener();
    setJMenuBar(bar);
    setVisible(true);
    //Add the actionListeners to the components
    public void addListener(){
    Open.addActionListener(this);
    Close.addActionListener(this);
    Exit.addActionListener(this);
    Connect1.addActionListener(this);
    Disconnect.addActionListener(this);
    Find.addActionListener(this);
    Login.addActionListener(this);
    Logout.addActionListener(this);
    Add.addActionListener(this);
    Remove.addActionListener(this);
    //Add the actions which the components must perform
    public void actionPerformed(ActionEvent evt){
    Object s = evt.getSource();
    if (s == Open){
    choice();
    Close();
    if (respones == 0){
    currentT = 1;
    clearTableAnimals();
    Connect.allAnimal();
    animal = new JTable(rows1, animalH);
    animalP = new JScrollPane(animal);
    getContentPane().add(animalP, BorderLayout.CENTER);
    setVisible(true);
    }else if (respones == 1 ){
    currentT = 2;
    clearTableSpecies();
    Connect.allSpecies();
    species = new JTable(rows2 , speciesH);
    speciesP = new JScrollPane(species);
    getContentPane().add(speciesP, BorderLayout.CENTER);
    setVisible(true);
    }else if (s == Close){
    Close();
    }else if (s == Exit){
    exit();
    }else if (s == Connect1){
    hostname = JOptionPane.showInputDialog(null , "Please enter Hostname");
    if (check = true){
    runner = new Thread(this);
    runner.start();
    Connect1.setEnabled(false);
    Disconnect.setEnabled(true);
    }else if (s == Disconnect){
    Connect.out.println("Bye");
    runner = null;
    try {
    Connect.out.close();
    Connect.in.close();
    Connect.clientSocket.close();
    } catch (IOException ioe) {
    JOptionPane.showMessageDialog(null,
    "Error " + ioe.toString(),
    "IO Exception",
    JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    }else if (s == Find){
    choice();
    Close();
    if (respones == 0){
    currentT = 1;
    String Aname = JOptionPane.showInputDialog(null , "Enter Animal name to find ");
    clearTableAnimals();
    Connect.findAnimal(Aname);
    animal = new JTable(rows1, animalH);
    animalP = new JScrollPane(animal);
    getContentPane().add(animalP, BorderLayout.CENTER);
    setVisible(true);
    }else{
    currentT = 2;
    String Sname = JOptionPane.showInputDialog(null , "Enter Species name to find ");
    clearTableSpecies();
    Connect.findSpecies(Sname);
    species = new JTable(rows2 , speciesH);
    speciesP = new JScrollPane(species);
    getContentPane().add(speciesP, BorderLayout.CENTER);
    setVisible(true);
    }else if( s== Login){
    String name = JOptionPane.showInputDialog(null , "Please enter a UserName");
    String password = JOptionPane.showInputDialog(null , "Please enter a Password");
    Connect.userPass(name , password);
    }else if (s == Logout){
    Logout();
    }else if (s== Add){
    choice();
    Close();
    if(respones == 0){
    currentT = 1;
    String id = JOptionPane.showInputDialog(null , "Enter an Animal id");
    String name = JOptionPane.showInputDialog(null , "Enter an Animal Name");
    String desc = JOptionPane.showInputDialog(null , "Enter an Animal Description");
    String speciesid = JOptionPane.showInputDialog(null , "Enter an Animal species id");
    clearTableAnimals();
    Connect.toAddAnimal(id , name , desc , speciesid);
    Connect.allAnimal();
    animal = new JTable(rows1, animalH);
    animalP = new JScrollPane(animal);
    getContentPane().add(animalP, BorderLayout.CENTER);
    setVisible(true);
    }else{
    currentT = 2;
    String id = JOptionPane.showInputDialog(null , "Enter a Species id");
    String name = JOptionPane.showInputDialog(null , "Enter a Species name");
    clearTableSpecies();
    Connect.toAddSpecies(id , name);
    Connect.allSpecies();
    species = new JTable(rows2 , speciesH);
    speciesP = new JScrollPane(species);
    getContentPane().add(speciesP, BorderLayout.CENTER);
    setVisible(true);
    }else if (s == Remove){
    choice();
    Close();
    if(respones == 0){
    currentT = 1;
    String id = JOptionPane.showInputDialog(null , "Enter an Animal id to Remove");
    Connect.toRemoveAnimal(id);
    }else{
    currentT = 2;
    String id = JOptionPane.showInputDialog(null , "Enter a Species id to Remove");
    Connect.toRemoveSpecies(id);
    public void run() {
    Connect connect = new Connect();
    while (runner != null) {
    try {
    connect.connecting();
    catch (IOException ioe) {
    System.out.println("Error: " + ioe);
    ClientGUI.running.setText("You are now connected");
    //Method the creates the dialog box for the user to choose what he wants to do
    void exit(){
    String [] option = { "Exit" , "Minimize" , "Cancel" };
    int which = JOptionPane.showOptionDialog(null , "Sure you want to exit"
    , "Exiting" , 0 , JOptionPane.WARNING_MESSAGE ,
    null , option , option[2] );
    if (which == 0){
    System.exit(1);
    }else if (which == 1){
    setState(JFrame.ICONIFIED);
    }else{}
    //Closes the current table on the panel
    public void Close(){
    if(currentT == 1){
    animalP.setVisible(false);
    }else if (currentT == 2){
    speciesP.setVisible(false);
    }else{}
    //Method that give the user a choice on which table to perform actions on
    public void choice(){
    String[] choices = {"Animals" , "Species"};
    respones = JOptionPane.showOptionDialog(null ,
    "Please select Table" , "Table" , 0 , JOptionPane.INFORMATION_MESSAGE ,
    null , choices , choices[1] );
    //Clears the Species table
    public void clearTableSpecies(){
    for (int i = 0; i < 40; i++){
    rows2[0] = "";
    rows2[i][1] = "";
    //Clears the Animal table
    public void clearTableAnimals(){
    for (int i = 0; i < 40; i++){
    rows1[i][0] = "";
    rows1[i][1] = "";
    rows1[i][2] = "";
    rows1[i][3] = "";
    //Method for the Logout button
    public void Logout(){
    JOptionPane.showMessageDialog(null , "You are now logged out ");
    Login.setEnabled(true);
    Add.setEnabled(false);
    Remove.setEnabled(false);
    Logout.setEnabled(false);
    //Main Methof
    public static void main(String[] args) {
    ClientGUI GUI1 = new ClientGUI();
    // Adds all components to the panel
    private void jbInit() throws Exception {
    jMenu1.setText("File");
    Exit.setText("Exit");
    jMenu2.setText("Table Action");
    Open.setText("Open Table");
    Add.setText("Add to Table");
    Remove.setText("Remove from Table");
    Find.setText("Find In table");
    Close.setText("Close Current");
    jMenu3.setText("Client");
    Connect1.setText("Connect");
    Disconnect.setText("Disconnect");
    Login.setText("Login");
    Logout.setText("Logout");
    bar.add(jMenu1);
    bar.add(jMenu2);
    bar.add(jMenu3);
    jMenu1.add(Exit);
    jMenu2.add(Open);
    jMenu2.add(Add);
    jMenu2.add(Remove);
    jMenu2.add(Find);
    jMenu2.add(Close);
    jMenu3.add(Connect1);
    jMenu3.add(Disconnect);
    jMenu3.add(Login);
    jMenu3.add(Logout);
    package Client;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    import java.util.*;
    public class Connect {
    static public Socket clientSocket = null;
    static public PrintWriter out = null;
    static public BufferedReader in = null;
    public void connecting() throws IOException {
    try{
    clientSocket = new Socket(ClientGUI.hostname , 1234);
    out = new PrintWriter(clientSocket.getOutputStream() , true);
    in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    }catch (UnknownHostException e){
    JOptionPane.showMessageDialog(null , "Dont know about host");
    ClientGUI.check = false;
    ClientGUI.Connect1.setEnabled(true);
    ClientGUI.Disconnect.setEnabled(false);
    ClientGUI.runner = null;
    }catch(IOException i){
    ClientGUI.check = false;
    JOptionPane.showMessageDialog(null,"Couldnt get i/O for the connection to 127.0.0.0.1");
    ClientGUI.Connect1.setEnabled(true);
    ClientGUI.Disconnect.setEnabled(false);
    ClientGUI.runner = null;
    if (ClientGUI.check = true){
    String fromServer;
    StringTokenizer token1;
    String First;
    String Second;
    String Third;
    while ( (fromServer = in.readLine()) != null) {
    System.out.println("From SerVer ---------------> " + fromServer);
    token1 = new StringTokenizer(fromServer, "%");
    StringTokenizer token2;
    StringTokenizer token3;
    First = token1.nextToken();
    System.out.println("First ------- > " + First);
    if (First.equalsIgnoreCase("SelectedAnimal")) {
    System.out.println("IT's ON ");
    Second = token1.nextToken();
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In the 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In the 2while");
    token3 = new StringTokenizer(token2.nextToken(), "@");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows1[y][x] = token3.nextToken();
    x++;
    y++;
    else if (First.equalsIgnoreCase("SelectedSpecies")) {
    System.out.println("IT's ON BITCH ");
    Second = token1.nextToken();
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In die 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In die 2while");
    token3 = new StringTokenizer(token2.nextToken(), "@");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows2[y][x] = token3.nextToken();
    x++;
    y++;
    else if (First.equalsIgnoreCase("FoundAnimal")) {
    Second = token1.nextToken();
    if (! (Second.equalsIgnoreCase("NONE"))) {
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In the 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In the 2while");
    token3 = new StringTokenizer(token2.nextToken(), "#@#");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows1[y][x] = token3.nextToken();
    x++;
    y++;
    else {
    JOptionPane.showMessageDialog(null,
    "Could not find Animal , Please try again");
    else if (First.equalsIgnoreCase("FoundSpecies")) {
    Second = token1.nextToken();
    if (! (Second.equalsIgnoreCase("NONE"))) {
    System.out.println("Second ----> " + Second);
    int y = 0;
    int x = 0;
    System.out.println("In die 1while");
    token2 = new StringTokenizer(Second, "$");
    while (token2.hasMoreTokens()) {
    System.out.println("In die 2while");
    token3 = new StringTokenizer(token2.nextToken(), "#@#");
    x = 0;
    while (token3.hasMoreTokens()) {
    ClientGUI.rows2[y][x] = token3.nextToken();
    x++;
    y++;
    else {
    JOptionPane.showMessageDialog(null,
    "Could not find Species , Please try again");
    else if (First.equalsIgnoreCase("FoundUser")) {
    System.out.println("From Server --- > " + First);
    String login = token1.nextToken();
    System.out.println("Find true or false ---- > " + login);
    if (login.equalsIgnoreCase("isUser")) {
    JOptionPane.showMessageDialog(null, "You are now logged in");
    ClientGUI.Add.setEnabled(true);
    ClientGUI.Remove.setEnabled(true);
    ClientGUI.Logout.setEnabled(true);
    ClientGUI.Login.setEnabled(false);
    else {
    JOptionPane.showMessageDialog(null,
    "Invalid Username or Password, Please try again");
    else if (First.equalsIgnoreCase("RecordAddedA")) {
    JOptionPane.showMessageDialog(null, "Record Added");
    else if (First.equalsIgnoreCase("RecordAddedS")) {
    JOptionPane.showMessageDialog(null, "Record Added");
    else if (First.equalsIgnoreCase("SQLE")) {
    System.out.println("ERROR SQL ERROR");
    else if (First.equalsIgnoreCase("Blah1")) {
    System.out.println("ERROR Ander ERROR");
    else if (First.equalsIgnoreCase("AnimalRemoved")) {
    JOptionPane.showMessageDialog(null, "Record Removed");
    else if (First.equalsIgnoreCase("SpeciesRemoved")) {
    JOptionPane.showMessageDialog(null, "Record Removed");
    }else{
    System.out.println("BLAAAAAAAAH");
    static public void Close() throws IOException{
    out.println("bye");
    ClientGUI.runner = null;
    ClientGUI.Disconnect.setEnabled(false);
    ClientGUI.Connect1.setEnabled(true);
    out.close();
    in.close();
    clientSocket.close();
    static public void allAnimal(){
    out.println("SELECTANIMALS");
    static public void allSpecies(){
    out.println("SELECTSPECIES");
    static public void findAnimal(String name){
    out.println("FINDANIMAL" + "@" + name);
    static public void findSpecies(String name){
    out.println("FINDSPECIES@" + name);
    static public void userPass(String name , String password){
    System.out.println("FINDUSER -----> " + name + " " + password);
    out.println("FINDUSER@" + name + "@" + password);
    static public void toAddAnimal(String id , String name , String desc , String species){
    out.println("toAddAnimal@" + id +"@" + name +"@" + desc +"@" + species );
    static public void toAddSpecies(String id , String name){
    out.println("toAddSpecies@" + id +"@" + name );
    static public void toRemoveAnimal(String id){
    out.println("toRemoveAnimal@" + id);
    static public void toRemoveSpecies(String id){
    out.println("toRemoveSpecies@" + id);
    On the server side:
    package Server;
    ////import everything necesary for the Database Connection
    import java.sql.*;
    import java.util.StringTokenizer;
    import javax.swing.*;
    import java.util.*;
    public class DatabaseConnect {
    //Declaration of Globale variables
    static int hoeveel = 0;
    static ResultSet rec ;
    static String bidData[] = new String[100];
    static String toSend[] = new String[100];
    //Connects the program to the database
    public DatabaseConnect() {
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    }catch(ClassNotFoundException cnf){
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    System.out.println("SqlExeption" + se);
    //Selects the data from the databas and adds the data to the tables
    public void open(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    if (ServerGUI.currentT == 1){
    hoeveel = 0;
    rec = st.executeQuery("SELECT * FROM ANIMALS");
    while (rec.next()) {
    bidData[hoeveel++] = rec.getString(1) + "@#@" +
    rec.getString(2) + "@#@" +
    rec.getString(3) + "@#@" +
    rec.getString(4);
    readintoTable1();
    }else if (ServerGUI.currentT == 2){
    hoeveel = 0;
    rec = st.executeQuery("SELECT * FROM SPECIES");
    while (rec.next()) {
    bidData[hoeveel++] = rec.getString(1) + "@#@" + rec.getString(2);
    readintoTable2();
    }else if(ServerGUI.currentT == 3){
    hoeveel = 0;
    rec = st.executeQuery("SELECT * FROM USER");
    while (rec.next()) {
    bidData[hoeveel++] = rec.getString(1) + "@#@" + rec.getString(2)
    + "@#@" + rec.getString(3);
    readintoTable3();
    }catch(ClassNotFoundException cnf){
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    System.out.println("SqlExeption" + se);
    //Clean the table and reads the data into the animal table
    public void readintoTable1(){
    for(int a = 0; a < 40; a++){
    ServerGUI.rows1[a][0] = "";
    ServerGUI.rows1[a][1] = "";
    ServerGUI.rows1[a][2] = "";
    ServerGUI.rows1[a][3] = "";
    for (int i = 0; i < hoeveel; i++) {
    StringTokenizer str = new StringTokenizer(bidData[i], "@#@");
    ServerGUI.rows1[i][0] = str.nextToken();
    ServerGUI.rows1[i][1] = str.nextToken();
    ServerGUI.rows1[i][2] = str.nextToken();
    ServerGUI.rows1[i][3] = str.nextToken();
    //Clean the table and reads the data into the Species table
    public void readintoTable2(){
    for(int a = 0; a < 40; a++){
    ServerGUI.rows2[a][0] = "";
    ServerGUI.rows2[a][1] = "";
    for (int i = 0; i < hoeveel; i++) {
    StringTokenizer str = new StringTokenizer(bidData[i], "@#@");
    ServerGUI.rows2[i][0] = str.nextToken();
    ServerGUI.rows2[i][1] = str.nextToken();
    //Clean the table and reads the data into the User table
    public void readintoTable3(){
    for(int a = 0; a < 40; a++){
    ServerGUI.rows3[a][0] = "";
    ServerGUI.rows3[a][1] = "";
    ServerGUI.rows3[a][2] = "";
    for (int b = 0; b < hoeveel; b++) {
    StringTokenizer str = new StringTokenizer(bidData, "@#@");
    ServerGUI.rows3[b][0] = str.nextToken();
    ServerGUI.rows3[b][1] = str.nextToken();
    ServerGUI.rows3[b][2] = str.nextToken();
    //add animal information to the Animal table in the database
    public void addAnimal(String id , String name , String desc , String species_id){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    int toAdd;
    String sqlstm = "INSERT INTO animals" + "(animal_id, animal_Name , description , species_id)" +
    "VALUES (" + id + ", '" + name + "', '" + desc + "', " + species_id + ")";
    toAdd = st.executeUpdate(sqlstm);
    dbconnect.close();
    JOptionPane.showMessageDialog(null , "New Record Added");
    ServerGUI.refreshAnimal();
    ServerGUI.currentT = 1;
    open();
    }catch(ClassNotFoundException cnf){
    JOptionPane.showMessageDialog(null,
    "Class Not Found -> " + cnf.toString(),
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    JOptionPane.showMessageDialog(null,
    "SQL Exception -> " + se.toString()
    + "\n Please make sure all data is entered correctly ",
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("SqlExeption" + se);
    //add animal information to the Species table in the database
    public void addSpecies(String id1 , String name1){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    int toAdd;
    String sqlstm = "INSERT INTO species" + "(species_id, species_name)" +
    "VALUES ( '" + id1 + "', '" + name1 + "')";
    toAdd = st.executeUpdate(sqlstm);
    dbconnect.close();
    JOptionPane.showMessageDialog(null , "New Record Added");
    ServerGUI.refreshSpecies();
    ServerGUI.currentT = 2;
    open();
    }catch(ClassNotFoundException cnf){
    JOptionPane.showMessageDialog(null,
    "Class Not Found -> " + cnf.toString(),
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("classNotFound" + cnf);
    }catch(SQLException se) {
    JOptionPane.showMessageDialog(null,
    "SQL Exception -> " + se.toString()
    + "\n Please make sure all data is entered correctly ",
    "Error!!",
    JOptionPane.ERROR_MESSAGE);
    System.out.println("SqlExeption" + se);
    //add animal information to the User table in the database
    public void addUser(String id2 , String user , String pass){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String source = "jdbc:odbc:Database";
    Connection dbconnect = DriverManager.getConnection(source);
    Statement st = dbconnect.createStatement();
    int toAdd;
    String sqlstm = "INSERT INTO user" + "(user_id, user_name ,user_password)" +
    "VALUES ( '" + id2 + "', '" + user + "', '"+ pass + "')";
    toAdd = st.executeUpdate(sqlstm);
    dbconnect.close();
    JOptionPane.showMessageDialog(null , "New Record Added");
    ServerGUI.refreshUser();
    ServerGUI.currentT = 3

    Your code is completely unreliable and it should be placed inside a code block when you add it. Also your question would be better off in the JDBC forum than the networking one.

  • 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();
    }

  • Animated .gif in JTable cell

    Hi -
    I have an actual animated .gif that I would like to display in a JTable's cell. By 'actual animated .gif', I mean that it is one file that is animated, and not a succession of files that I would loop through to look like animation.
    I have edited the following code that I found in a previous post. My .gif does display in the JTable and animates only ONCE. Once it animates once, it stops. How can I cause it to keep looping through and repeating the animation?
    Thanks!
    Kelly
    Code below:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class AnimatedIconTableExample extends JFrame
    public AnimatedIconTableExample()
    super("AnimatedIconTable Example");
    final Object[][] data = new Object[][]
    { new ImageIcon("images/Upload.gif") }
    final Object[] column = new Object[]
    { "Image Uploading" };
    AbstractTableModel model = new AbstractTableModel()
    public int getColumnCount()
    return column.length;
    public int getRowCount()
    return data.length;
    public String getColumnName(int col)
    return (String) column[col];
    public Object getValueAt(int row, int col)
    return data[row][col];
    public Class getColumnClass(int col)
    return ImageIcon.class;
    JTable table = new JTable(model);
    table.setRowHeight(50);
    setImageObserver(table);
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
    private void setImageObserver(JTable table)
    TableModel model = table.getModel();
    int colCount = model.getColumnCount();
    int rowCount = model.getRowCount();
    for (int col = 0; col < colCount; col++)
    if (ImageIcon.class == model.getColumnClass(col))
    for (int row = 0; row < rowCount; row++)
    ImageIcon icon = (ImageIcon) model.getValueAt(row, col);
    if (icon != null)
    icon.setImageObserver(new CellImageObserver(table, row,
    col));
    class CellImageObserver implements ImageObserver
    JTable table;
    int row;
    int col;
    CellImageObserver(JTable table, int row, int col)
    this.table = table;
    this.row = row;
    this.col = col;
    public boolean imageUpdate(Image img, int flags, int x, int y, int w,
    int h)
    if ((flags & (FRAMEBITS | ALLBITS)) != 0)
    Rectangle rect = table.getCellRect(row, col, false);
    table.repaint(rect);
    return (flags & (ALLBITS | ABORT)) == 0;
    public static void main(String[] args)
    AnimatedIconTableExample frame = new AnimatedIconTableExample();
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    frame.setSize(300, 150);
    frame.setVisible(true);

    I've heard of that problem before... I think it has something to do with how the image is loaded. I found an example of how Sun does animated gifs here: http://java.sun.com/products/java-media/2D/samples/suite/Image/DukeAnim.java
    I hope it helps.

  • Animated GIFs won't display properly in Mail.app

    I have a weird problem with animated GIFs received as attachments in Mail.app. On my Mac mini, they're only displayed as the first frame within the Mail message window and the animations don't play. But on my iMac G4, the same messages display the animations properly within Mail.app. Both Macs are currently running Mac OS X 10.4.4, but I've observed this problem since 10.4.3. I have the same software installed on both machines. Does anyone have any ideas why this is happening?

      * Test.java
      * Created on January 13, 2007, 6:52 PM
      * To change this template, choose Tools | Template Manager
      * and open the template in the editor.
    package Test;
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
      * @author Calbrenar
    public class Test extends JFrame
        private JList testList;
        private DefaultListModel listModel;
        private JScrollPane serverLogScroller;
        private Container container;
        /** Set up GUI */
        public Test()
           super ("List Test");
           //Get content pane
           container = getContentPane();
           container.setLayout(new FlowLayout());
           listModel = new DefaultListModel();
           listModel.addElement("");
           testList = new JList(listModel);
           testList.setVisibleRowCount(1);
           //testList.setFixedCellHeight(35);
           //testList.setFixedCellWidth(400);
           serverLogScroller = new JScrollPane(testList);
           serverLogScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
           serverLogScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
           container.add( new JScrollPane( testList));
           setSize(700, 75);
           setVisible(true);
        public void addStatus(String str)
           listModel.add(0, str);
           //testList.setPreferredSize(new Dimension(400, 15));
           //serverLogScroller.revalidate();
           container.validate();
        public static void main ( String args[])
           Test application = new Test();
           application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
           application.addStatus("-ERR");
           application.addStatus("+OK Enter Password");
           application.addStatus("-ERR Bad Pass");
    } // end class Test

  • Problem with simple animation.  Any help greatly appreciated.

    I am trying to make a circle (which is actually an array of polygons in the shape of a circle) change color over time. Basically what the inner loop does is assign each polygon a random color. The desired effect here is for the circle to be assigned a certain array of colors then have swing repaint the component so we can see the change and repeat, resulting in a nice animation of colors changing over time. What ends up happening is the applet only updates after it has done the entire outer loop. So only the last color state of the circle is seen after it has done all the computations. So it goes from the intial color to the end color, without showing the states in between. What can I do for it to repaint for each of the recolorings? The computation is complex enough so it's not as if it displays the colors so fast that you only notice the end state.
    for (int year=0; year<500000; year+=500)
    for (int x=0; x<180; x++)
    polys[x].setColor(generator.nextInt(250),generator.nextInt(250),generator.nextInt(250));
    repaint();
    poly.update(polys);
    }

    I was struggling to find a relevant piece of code to demonstrate how this can be done. I eventually ended up with the ugliest animation ever.import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    public class AnimationDemo extends JPanel {
         private static final Color[] COLORS = {Color.WHITE, Color.RED, Color.BLUE, Color.YELLOW, Color.BLACK};
         private static int getNextColorIndex(int aColorIndex) {
              return ++aColorIndex % COLORS.length;
         private static class ColoredSquare {
              int theColorIndex;
              Rectangle theRectangle;
              public ColoredSquare(int aColorIndex, Rectangle aRectangle) {
                   theColorIndex = aColorIndex;
                   theRectangle = aRectangle;
         private static class Mozaic extends JComponent implements Runnable {
              private ColoredSquare[] theColoredSquares;
              public Mozaic() {
                   int width = 49;
                   int height = 49;
                   Dimension squareDimension = new Dimension(10, 10);
                   theColoredSquares = new ColoredSquare[width * height];
                   int index = 0;
                   int colorIndex = 0;
                   Point currentPoint;
                   for (int x = 0; x < width; x++) {
                        for (int y = 0; y < height; y++) {
                             currentPoint = new Point(x * squareDimension.width, y * squareDimension.height);
                             theColoredSquares[index] = new ColoredSquare(colorIndex, new Rectangle(currentPoint, squareDimension));
                             index++;
                             colorIndex = getNextColorIndex(colorIndex);
                   setPreferredSize(new Dimension(width * squareDimension.width, height * squareDimension.height));
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2D = (Graphics2D)g;
                   Color tempColor = g2D.getColor();
                   for (int i = 0; i < theColoredSquares.length; i++) {
                        ColoredSquare coloredSquare = theColoredSquares;
                        int colorIndex = getNextColorIndex(coloredSquare.theColorIndex);
                        g2D.setColor(COLORS[colorIndex]);
                        g2D.fill(coloredSquare.theRectangle);
                        coloredSquare.theColorIndex = colorIndex;
                   g2D.setColor(tempColor);
              public void run() {
                   try {
                        for (int year = 0; year < 500000; year += 500) {
                             repaint();
                             Thread.sleep(50);
                   } catch (InterruptedException e) {
                        e.printStackTrace();
         public AnimationDemo() {
              super(new BorderLayout());
              final Mozaic mozaic = new Mozaic();
              add(new JScrollPane(mozaic), BorderLayout.CENTER);
              add(new JButton(new AbstractAction("start animation") {
                   public void actionPerformed(ActionEvent e) {
                        new Thread(mozaic, "Animation Thread").start();
              }), BorderLayout.SOUTH);
         public static void main(String[] args) {
              final JFrame frame = new JFrame("Animation Demo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new AnimationDemo());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(400, 300);
                        frame.show();

  • JList/ListCellRenderer/JScrollPane

    Hi Listeners!
    I'm using a JList using an own renderer for displaying the data.
    Every cell contains among other components a text field embedded in a scroll pane. The text field may contain text or images (animated ones).
    Both components have information about the available sizes.
    The problem comes with displaying the cells because neither the scroll pane nor the animated gif work correctly. Altough the scroll pane is shown I cannot use it and it seems that the scroll pane cannot or does not receive (mouse) events. Finally the animated gif changes to a standard gif without animation. All other things do work.
    Has anybody tried to use the JList for presenting scroll pane based content?
    ThanX
    franzR

    Thanks for the suggestion. With those changes, though, it seems I still have to set the width (setColumns()) inside the renderer in order to get the wrap to occur. getPreferredSize() returns the size of a single line without setting it.
    Do you know any way I can access the width of the JList (or the containing JScrollPane), or pass it to the renderer? getPreferredSize() of the JList object yields a StackOverflowError when accessed from within the renderer.

  • JScrollPane Auto Scrolling for Teleprompter

    I am working on a piece of software to scroll text for a teleprompter. I have a class that scrolls the text that is in a JEditorPane nested in a JScrollPane. Here is the class that scrolls the text:
    package teleprompter;
    import javax.swing.JScrollPane;
    public class Scroll extends Thread
        JScrollPane scrlMain;
        public Scroll(JScrollPane scrlMain)
            this.scrlMain = scrlMain;
        public void run()
            int iPos = scrlMain.getVerticalScrollBar().getValue();
            for (;;)
                iPos += 5;
                scrlMain.getVerticalScrollBar().setValue(iPos);
    }My problem is that it is not a consistent, smooth scroll so that someone can read it. It is real jumpy, sometimes it will jump an entire page. For now, the speed of the scroll can be changed by making the 5 in "iPos += 5" a higher number.
    Is there a better way to do an auto scroll that is not so inconsistent and jumpy that anyone can think of?
    Edited by: 879705 on Aug 18, 2011 1:40 PM

    879705 wrote:
    I am working on a piece of software to scroll text for a teleprompter. I have a class that scrolls the text that is in a JEditorPane nested in a JScrollPane.One possibility occurred to me, although I'm no GUI expert and it maybe totally the wrong approach.
    One of the characteristics of a teleprompter (at least in most Western languages) is that new text is always likely to appear at the bottom so, rather than worrying about scrolling, why not either:
    (a) Set the scroll value to 100% and add new lines to the end as and when required, or
    (b) Maintain the text array yourself and simply display it in a fixed area.
    It seems to me that the same technique could also be combined with text animation to display a line at a time.
    However, as I say, I'm no GUI expert, so feel free to laugh...
    Winston

  • Open and edit animated .gif while preserving frame timing

    CS4 Premium Design Edition, Win XP
    I was disappointed with the removal of Image Ready from CS3 because although some of the functionality was placed into Photoshop 10, there was no way to open and edit an existing animated .gif while preserving the timing of each individual frame. I was told on the PS forum at the time that I really needed to use Fireworks. I resented that, because I was very happy with Image Ready and I didn't want to have to learn a new application just to gain functionality that had been included in previous versions of PS/IM.
    I've now got CS4 Premium Design Edition which of course includs Fireworks... and here's what Help has to say on the subject of imported .gifs.
    "Note: When you import an animated GIF, the state delay setting defaults to 0.07 seconds. If necessary, use the States panel to restore the original timing."
    This is no use to me. What if I don't know the individual frame timings? What if there are 200 frames with varying timings?
    Simple question: which current Adobe product is capable of importing a .gif while retaining the frame timings? If anyone knows, or if I've misunderstood the nature of the Fireworks Help quote above, I'd really appreciate some input here. Thanks :)
    Not so simple question: why was an excellent gif-editing application thrown out to have its functionality partially replaced by a bunch of scripts and half-effective workarounds cooked up by desperate users ("import a gif by using the video import and typing *.* into the filename box..")? It's a fair question I think.
    Mark

    Hi Bob, that's not glib at all, it's a reasonable question.
    I uninstalled it along with everything else when I installed CS3, in the reasonable expectation that whatever replaced IR would be at least equal in functionality.
    Perhaps I should just dig out CS2 and install IM from there, but I have some serious reservations about doing so, because I don't know if/how a partial install of CS2 will impact upon my installation of CS4, and I'm not confident of getting support.
    I am also curious to know if/why Adobe actually removed basic functionality without replicating or replacing it in their other software. I really want to know: which recent, currently supported Adobe product
    should I be using in order to regain this functionality? Or do Adobe no longer produce a geniuinely comprehensive .gif-editing application?
    Mark

  • Animated GIF ignoring frame timing

    I am trying to create simple animated GIFs with a few layers
    of text that simply fade in and fade out in sequence. My initial
    attempt worked perfectly. Most frames use the default 7/100's of a
    second delay as they fade. A few frames were manually set to much
    longer delays so that the text pauses, before fading out to be
    replaced by the next text.
    When I reopened the file, to adjust the background color, and
    then re-saved it, the GIF now plays straight through, ignoring the
    timing of each frame. Nothing I do now can get it to pause on the
    appropriate frames. I've tried cutting the symbols out and pasting
    them into a new file, removing the animation from the symbols and
    reapplying it, etc.
    Any ideas, anyone?
    Thanks in advance.

    None, None.

  • Edit animated gif

    Hi,
    How can I edit an animated gif in Photoshop Elements 6 for Mac?
    When I open the file there is just the first frame in one layer - no other layers available.
    Thanks!

    Thanks Barbara!
    Barbara B. wrote:
    ... then bring it to PSE.
    I can't drag the single frames from Preview to PSE, because PSE 6 doesn't run in window mode.
    (Is this improved in the current version?)
    I can only drag the single frames to the desktop (as TIFF files, I guess transparency info is lost then?).
    Barbara B. wrote:
    ... there's a bug beginning in PSE 6 where you can't change the frame delay rate from the default when you save an animated gif.
    What's the default frame delay rate? Maybe it's just what I need.
    Barbara B. wrote:
    You might  want to look into a free program like giffun from stone.com instead.
    Yes that's maybe a better idea. It doesn't have to be free software. Can you recommend something good?
    Thanks again!

  • Can i open and edit animated GIF in Adobe Photoshop Touch?

    Can i open and edit animated GIF in Adobe Photoshop Touch?

    No, only regular static GIF images are supported. The desktop version of Photoshop does support this however.

  • Gif animations in Mail

    I've read some threads about this problem, and while there is lively debate, there doesn't seem to be an answer. So I thought I would try it again with a new question.
    A friend of mine (he has an old IMac) forwarded me an email with an animated gif. It was funny, and I wanted to forward it on. But I have never been able to do this. If I try to save the file, it saves as a MIME attachment, and I can't even open it. If I Download the file, the Get Info says it is a gif file, but if I open it in Preview, or attach it to a new email, it no longer animates and is just a still picture.
    I tried forwarding the original email with the animated gif back to myself, and when it arrives, it no longer animates. My friend is no help. He's not really in to computing. He told me he just gets them from somebody else, and forwards it to me.
    So why can I see the animated gif in my Mail, but can't save it, download it, cut & paste it, or forward it? I tried the Append Message suggestion from an old post, and that did not work either.
    I noticed in some of the old posts some people seem to really hate gif's. I don't really care one way or the other. I just want to understand why my computer can receive them, but can't do anything else with them.

    Although Jaguar and Panther Mail renders HTML received, they do not support composing HTML which also includes when forwarding a message received that was composed in HTML including animated gifs.
    Although you cannot compose complex HTML within the body of a message with Tiger Mail, RTF with Tiger Mail is HTML and supports forwarding a message received that was composed in HTML including animated gifs.
    Reason for this: if you automatically render all HTML received (with any email client with OS X) and a spammer uses HTML for message composition and includes embedded images or objects that must be rendered from a remote server, if the Mail.app Junk Mail filter does not automatically mark the message as junk and you open the message, this can reveal that your email address is valid to the spammer causing more spam to be received.
    Copied from Why HTML in E-Mail is a Bad Idea:
    "Because it introduces accessibility problems. When you write in plain text, the receiving mail client renders the text in whatever font the reader chooses. When you format email with HTML, the sender controls the formatting. But this is a trap: You only think your message will render the same way to the viewer as it appears to the sender. In reality, the receiver can end up squinting because the font looks so tiny, or vice versa. HTML is not rendered the same way from one viewing client to the next - all guarantee of accessiblity goes out the window. This is especially problematic for visually impaired persons."
    Because it can introduce security issues and trojan horses -- it's a gateway to danger as any Outlook user can tell you. HTML can include any number of scripts, dangerous links, controls, etc.
    Powerbook G4 17"   Mac OS X (10.4.5)  

  • Animated GIFs are ridiculously large - why?

    Hi all,
    I cannot figure out why the animated GIFs I am exporting are
    so massive in file size. For example, I import a small 5-frame
    650Byte GIF. I edit the size of the canvas to pad it to a square
    (from 54x40 to 54x54, or something like that), then I save it with
    the following settings:
    Animated GIF
    Exact Palette
    0 Loss
    4 Colours (5 including alpha channel)
    No dither
    And it comes out as 64.4KB. How can the file size increase by
    100 times with barely any change? Even if I import it, change
    nothing and save the file with the same settings as above, it's
    still 64.4KB. Is Fireworks padding the file with unnecessary
    information or something?
    Thanks for any help,
    John.

    > But the original image is an animated GIF and it's less
    than 1KB big! So
    > how
    > does it increase in size 100 times when I save it
    even if I don't
    > change
    > anything about the image before saving? There is no
    PNG file but I can
    > link
    > you to the original 650 Byte Animated GIF:
    I'm confused. What is this I am looking at. What have you
    done to it to
    make it increase in weight?
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "Quircus" <[email protected]> wrote in
    message
    news:g6fohk$mip$[email protected]..
    > But the original image is an animated GIF and it's less
    than 1KB big! So
    > how
    > does it increase in size 100 times when I save it
    even if I don't
    > change
    > anything about the image before saving? There is no
    PNG file but I can
    > link
    > you to the original 650 Byte Animated GIF:
    >
    >
    http://www.aotplaza.com/Prod.gif
    >
    > Is it something to do with my settings perhaps? Like
    telling it to save
    > extra
    > information in the file?
    >

  • Gif not animating when on the Internet

    Hopefully some one can help as I have tried everything i can
    think of
    I have create a animation using Flash 8 I have exported this
    as a Animated gif to my computer. I can open the file and it
    animates fine on my pc. When i upload to myspace it does not
    animate.
    I have tried downloading a random gif from the net and
    uploading it to myspace and this animates (Just wanted to check
    Myspace works with gifs)
    The problem only appears to be with animations I have made.
    I have tried making a really small animation (about 110kb)
    then uploading it to myspace but again it doesnt animate (so its
    not a size issue)
    Flash - I have tried exporting movie as a gif and publishing
    as a gif. The Animation has been made using motion tweed and not an
    action script and I have tried every combination of gif option i
    can think of i.e loop animation, loop twice, changing the frame
    rate, size , colours, transarency etc
    Please help as im so confused as to why this doesnt work.

    Perhaps Safari isn't quite what you require, too much work involved all the time making it easier to see
    Take a look at my customized Firefox:
    it always opens to the same size window (or full screen if you like)
    it always zooms all web pages 160% (or whateve you like)
    it always has large type on the menu bar area. (to whatever you like)
    it's very highly customizable,  (or use the plain default settings)
    has more add-ons than anyone (a real plus when you need it)
    has more themes and personas than anyone (make it YOUR browser)
    Easier surfing option for hard of seeing users
    Safari is about the absolute worst browser since Internet Explorer, it's because Apple has already got your money so there isn't any incentive for them to make a better browser.

Maybe you are looking for

  • Can no longer drag and drop in iTunes

    I've seen this addressed in a recent thread but that thread seemed to involve the Wacom tablet, which I don't have. I found today that I could no longer drag songs in iTunes at all, not even to add to a playlist, never mind moving from my computer to

  • I want to connect my PS3 to my macbook.

    I have seen HDMI to USB 2.0 cords out there, but I would love to use the thunderbolt port if possible. So, is there a way I can use my Macbook Pro as a monitor for my PS3?

  • Text of additional fields on SAP query show blank

    Hi All, I'm encountered a problem when text of additional fields on SAP query is not working and it's show blank after HRSP is implemented. SAP_ABA : Rel. 701 Lvl. 3 SAP_BASIS: Rel. 701 Lvl. 3 SAP_HR: Rel. 604 Lvl. 8 Below are the config that we have

  • Actobat 9 Execute Menu Item problem

    I have a new PC with Window 7 and have successfully loaded Acrobat 9 pro - but a lot of the Acrobat functionality is now missing (it all worked under the XP platform). For example, when creating a form, using a buttom with an 'Execute menu item' comm

  • Deploy a J2EE Web Services App in CE 7.1 SP1 SDN Preview

    Hi, I am new to SAP CE 7.1 SP1 (SDN Preview). I have a SAP J2EE (web services) application developed for SAP Netweaver 7.0. How to deply the application in CE 7.1 SP1. thanks in advance, Nagarjuna.