Hi guys,
I am new in java programming ,
I wrote this pregame which is a simple GUI program with 2 buttons one to get the full date , and the other to get the time only .
I used Thread in this program in order to make the time update every 1 second.
here is the code :
import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GUI extends JFrame { private JButton B1; private JButton B2; private JLabel L1; private JPanel P1; private JPanel P2; private MYThread TH; String S =""; public GUI (){ super ("Time"); TH = new MYThread(); B1 = new JButton("Get full Time"); B2 = new JButton("Get Time"); L1 = new JLabel(); P1 = new JPanel(); P2 = new JPanel(); P1.add(B1); P1.add(B2); P2.add(L1); add(P1 , BorderLayout.SOUTH); add(P2 , BorderLayout.CENTER); B1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { S = "1"; TH.start(); } catch (IllegalThreadStateException e){ } } }); B2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { S = "2"; try { TH.start(); } catch (IllegalThreadStateException e){ } } }); } class MYThread extends Thread{ String T ; public void run() { super.run(); while (true){ if(S.equals("1")){ Calendar C = new GregorianCalendar(); T = C.getTime() + ""; L1.setText(T); try { MYThread.sleep(1000); } catch (Exception e){ } } if(S.equals("2")){ GregorianCalendar C = new GregorianCalendar(); L1.setText(C.get(Calendar.HOUR)+":"+C.get(Calendar.MINUTE)+":"+C.get(Calendar.SECOND)); try { MYThread.sleep(1000); } catch (Exception e){ } } } } } }
My question is :
Can I use " TH.start(); " more than once in the same class ??
I used "TH.start() " in the Action Listener .
Sorry for my English