0

Why is that When I user the Timer.util the JLabel wont allign with my String that I inserted in my JTextPane? But when I use the Timer it Allign. I need the Timer.util for my database so it wont lag.

Here is the image when I use the Timer swing

enter image description here

Timer t2 = new Timer(250,new ActionListener(){

        public void actionPerformed(ActionEvent arg0) {

            fetchMessageData2();
        }
    });
    t2.start();


public static void fetchMessage(JTextPane jtep,StyledDocument sd,int count  )
{

    try{

    String query = "SELECT members.username, message FROM chat JOIN members ON    chat.user_id = members.id WHERE message_id > "+count+"";
    rs = st.executeQuery(query);
    while(rs.next())
    {

        try {
            final JLabel jp = new JLabel(rs.getString("username")+ "\n");
            jp.setAlignmentY(0.75f);
            jp.setFont(new Font("arial",Font.BOLD,16));
            jtep.insertComponent(jp);
            sd.insertString(sd.getLength(), ": "+rs.getString("message")+ "\n", MainPanel.sas);
        } catch (BadLocationException e1) {

            e1.printStackTrace();
        }


        MainPanel.count++;}

    }catch(Exception ex){System.out.print(ex);}

}

Here is the image result using the Timer.util

enter image description here

Timer t  = new Timer();
    t.schedule(new runnableMethods(), 0,500);

import java.util.TimerTask;


public class runnableMethods extends TimerTask{

@Override
public void run() {

    SubPanel1.checkOfflineOnline();
}
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Poldz Kerk
  • 69
  • 3
  • 15

1 Answers1

3

Don't use java.util.Timer's on the Swing event dispatch thread, the EDT, as it is not thread safe for use with Swing. Either use the javax.swing.Timer or if you must use the java.util.Timer, use it on a background thread, and make sure that you make Swing calls only on the EDT. A SwingWorker would work well for this.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • what should I do in the backGround cause it is still laggin like hell due to the database call. BTW I am using swing workers now but it didnt work should I separate mysql call? – Poldz Kerk May 06 '13 at 03:28