We help IT Professionals succeed at work.
Get Started

Adding this timer to my GUI

islandguy10
islandguy10 asked
on
533 Views
Last Modified: 2013-12-14
Hello Java Experts.  I'm relatively new to Java(read this is my second GUI ever) and I'm trying to add in a timer that I found on a previous thread.  The issue is that the timer I found is its own separate window and I want to add it into the text field in my GUI.  I will show my code first, then the timer I found on EE.  I want to have the timer display where my clock string is displaying, and probably to have it replace that panel entirely.  Any suggestions on where to start would be greatly appreciated.  I am doing all development in NetBeans.
import java.applet.*;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;

import java.text.*;
import java.util.Date;
import javax.swing.border.Border;

public class ClockSim extends JPanel
                      

{
        //Values for fields(Temporary till I figure out clocks)
        private String time = "23:59:59";

        //Fonts
        private Font clockFont = new Font("Verdana", Font.BOLD, 58);
        private Font mcFont = new Font("Verdana", Font.BOLD, 20);
        
        //Create Labels to identify fields
        private JLabel counterLabel;
        private JLabel multiCastLabel;

        //create Strings for labels
        private String counterString = "Clock";
        private String multiCastString = "Multicast Address";

        //Fields for data entry and display
        private JFormattedTextField counterField;
        private JFormattedTextField multiCastField;

        //Create Main Panels(nested Panels declared in ClockSim())
        private JPanel clockPanel;
        public static JPanel clockButtonPanel;
        private JPanel multiCastPanel;
        private JPanel utilityButtonPanel;

        //Formate to format and parse numbers(Probable be replaced)
        private NumberFormat counterFormat = null;
        private NumberFormat multiCastFormat = null;

        public ClockSim()
        {
            super(new GridLayout(2,2));
            setSize(600,600);



            //setUpClocks();use later
        
            //Create Labels
            counterLabel = new JLabel(counterString);
            multiCastLabel = new JLabel(multiCastString);

            //Create TextFields
            counterField = new JFormattedTextField(counterFormat);
            counterField.setValue(new String(time));
            counterField.setToolTipText("Displays time in hh:mm:ss");
            counterField.setFont(clockFont);
            counterField.setHorizontalAlignment(SwingConstants.CENTER);

            multiCastField = new JFormattedTextField();
            multiCastField.setText("222.0.4.32");
            multiCastField.setFont(mcFont);
            multiCastField.setToolTipText("Displays Multicast Address");

            //Create Text and Label Pairs
            counterLabel.setLabelFor(counterField);
            multiCastLabel.setLabelFor(multiCastField);

            //Create Panels
            //Main Panels
            clockPanel = new JPanel();
            clockPanel.setLayout(new BoxLayout(clockPanel, BoxLayout.PAGE_AXIS));
            clockButtonPanel = new JPanel(new FlowLayout());
            multiCastPanel = new JPanel();
            multiCastPanel.setLayout(new BoxLayout(multiCastPanel, BoxLayout.PAGE_AXIS));
            utilityButtonPanel = new JPanel();
            utilityButtonPanel.setLayout(new BoxLayout(utilityButtonPanel, BoxLayout.PAGE_AXIS));

            //Nested Panels for clockPanel
            JPanel clockLabelPanel = new JPanel(new GridLayout(0,1));
            clockLabelPanel.add(counterLabel);

            JPanel clockFieldPanel = new JPanel(new GridLayout(0,1));
            clockFieldPanel.add(counterField);

            JPanel clockPanelFieldPane = new JPanel();
            JPanel clockPanelButtonPane = new JPanel();

            //Nested Panels for clockButtonPanel

            //Nested Panels for multiCastPanel
            JPanel multiCastLabelPanel = new JPanel(new GridLayout(0,1));
            multiCastLabelPanel.add(multiCastLabel);

            JPanel multiCastFieldPanel = new JPanel(new GridLayout(0,1));
            multiCastFieldPanel.add(multiCastField);

            JPanel multiCastFieldPane = new JPanel();
            JPanel multiCastButtonPane = new JPanel();

            //Nested Panels for utilityButtonPanel
            JPanel invisPlaceHold1 = new JPanel();
            JPanel invisPlaceHold2 = new JPanel();
            JPanel utilityButtonPane = new JPanel();

            //Add features to clockPanel
            clockPanel.add(clockLabelPanel, BorderLayout.WEST);
            clockPanel.add(clockFieldPanel, BorderLayout.CENTER);
            clockPanel.add(clockPanelButtonPane, BorderLayout.PAGE_END);
            clockPanel.add(Box.createRigidArea(new Dimension(0,0)));
            //clockPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

            //Create Buttons
            JButton clearClockButton = new JButton("Clear Countdown");
            clearClockButton.addActionListener(new ActionListener()
            {
            public void actionPerformed(ActionEvent ae)
                {
                 counterField.selectAll();
                 counterField.setText("");
                }
            });

            //Add Hold Button
            JButton holdClockButton = new JButton("Hold Countdown");
            holdClockButton.addActionListener(new ActionListener()
            {
            public void actionPerformed(ActionEvent ae)
                {

                }
            });

            //Add Start button
            JButton startClockButton = new JButton("Start Countdown");
            startClockButton.addActionListener(new ActionListener()
            {
            public void actionPerformed(ActionEvent ae)
                {

                }
            });           

            //Layout Buttons from left to right
            clockPanelButtonPane.setLayout(new BoxLayout(clockPanelButtonPane, BoxLayout.LINE_AXIS));
            clockPanelButtonPane.add(startClockButton);
            clockPanelButtonPane.add(Box.createHorizontalGlue());
            clockPanelButtonPane.add(holdClockButton);
            clockPanelButtonPane.add(Box.createHorizontalGlue());
            clockPanelButtonPane.add(clearClockButton);
            clockPanelButtonPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));


            //Add Features to clockButtonPanel

            clockButtonPanel.setLayout(new java.awt.BorderLayout());
            setSize(350, 125);
            
            //clockButtonPanel.add(new Watch());
            //clockButtonPanel.add(Watch.ivjContentsPane1);

            JButton startButton = new JButton("Start");
            startButton.addActionListener(new ActionListener()
            {
            public void actionPerformed(ActionEvent ae)
                {

                }
            });
            //clockButtonPanel.add(startButton);


            //Add features to multiCastPanel
            multiCastPanel.add(Box.createVerticalStrut(70));
            multiCastPanel.add(multiCastFieldPane);
            multiCastPanel.add(Box.createVerticalStrut(20));
            multiCastPanel.add(multiCastButtonPane, BorderLayout.PAGE_END);
            multiCastPanel.add(Box.createRigidArea(new Dimension(0,0)));

            //Add featrues to nested Panels
            //Set up field pane
            multiCastFieldPane.setLayout(new BoxLayout(multiCastFieldPane, BoxLayout.PAGE_AXIS));
            multiCastFieldPane.add(multiCastLabelPanel);
            multiCastFieldPane.add(multiCastFieldPanel);

            //Create and add Button(s)
            JButton enterMultiCastButton = new JButton("Enter Multicast Address");
            enterMultiCastButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                    String multiAddress = multiCastField.getText();
                }
            });
            

            JButton clearMultiCastButton = new JButton("Clear Multicast Address");
            clearMultiCastButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                 multiCastField.selectAll();
                 multiCastField.setText("");
                }
            });
           
            //Lay out buttons left to right
            multiCastButtonPane.setLayout(new BoxLayout(multiCastButtonPane, BoxLayout.LINE_AXIS));
            multiCastButtonPane.add(Box.createHorizontalGlue());
            multiCastButtonPane.add(enterMultiCastButton, BorderLayout.CENTER);
            multiCastButtonPane.add(Box.createHorizontalGlue());
            multiCastButtonPane.add(clearMultiCastButton, BorderLayout.CENTER);
            multiCastButtonPane.add(Box.createHorizontalGlue());

            //Add features to utilityButtonPanel
            //Set up Panes
            utilityButtonPanel.setLayout(new BoxLayout(utilityButtonPanel, BoxLayout.PAGE_AXIS));
            utilityButtonPanel.add(Box.createRigidArea(new Dimension(0,5)));
            utilityButtonPanel.add(utilityButtonPane);
            
            //Set up nested Panes

            //Create Buttons
            JButton exitButton = new JButton("Exit");
            exitButton.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent ae)
                {
                    System.exit(0);
                }
            });

            //Button Layout
            utilityButtonPane.setLayout(new BoxLayout(utilityButtonPane, BoxLayout.LINE_AXIS));
            utilityButtonPane.add(Box.createRigidArea(new Dimension(5,0)));
            utilityButtonPane.add(Box.createVerticalGlue());
            utilityButtonPane.add(Box.createHorizontalGlue());
            utilityButtonPane.add(exitButton);

            //Add Panels to ClockSim
            setBorder(BorderFactory.createEmptyBorder());
            add(clockPanel);
            add(clockButtonPanel);
            add(multiCastPanel);
            add(utilityButtonPanel);
        }

        
     public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
	        UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
        
    }
     private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Clock Simulator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        try {
            Watch aWatch;
            aWatch = new Watch();            
            aWatch.setVisible(true);
            } catch (Throwable exception)
            {
            exception.printStackTrace(System.out);
            }
        
        //Add contents to the window.
        frame.add(new ClockSim());

        //Set size of Frame
        
        //Display the window.
        frame.pack();
        frame.setSize(900,450);
        frame.setVisible(true);
    }

    public void propertyChange(PropertyChangeEvent evt) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void run() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}

Timer code

public class Watch extends java.awt.Frame implements java.awt.event.ActionListener,
java.awt.event.WindowListener, Runnable {
  protected java.awt.Button ivjButtonReset = null;
  protected java.awt.Button ivjButtonStart = null;
  protected java.awt.Button ivjButtonStop = null;
  protected java.awt.Panel ivjContentsPane = null;
  protected java.awt.Panel ivjContentsPane1 = null;
  protected java.awt.Dialog ivjDialog = null;
  protected java.awt.Label ivjLabelTimeUp = null;
  protected java.awt.TextField ivjTextField = null;
  int seconds=5*60;
  Thread th=null;
  protected java.awt.Button ivjButtonResume = null;

public Watch() {
  super();
  initialize();
}

public Watch(String title) {
  super(title);
}


public void actionPerformed(java.awt.event.ActionEvent e) {
  if (e.getSource() == getButtonStart())
    this.buttonStart_ActionPerformed();
  if (e.getSource() == getButtonStop())
    this.buttonStop_ActionPerformed();
  if (e.getSource() == getButtonReset())
    this.buttonReset_ActionPerformed();
  if (e.getSource() == getButtonResume())
    this.buttonResume_ActionPerformed();
}

public void buttonReset_ActionPerformed() {
  getButtonStart().setEnabled(true);
  getButtonStop().setEnabled(false);
  getButtonResume().setEnabled(false);
  getButtonReset().setEnabled(false);
  th.stop();
  th=null;
  getTextField().setText("05"+":"+ "00");
}

public void buttonResume_ActionPerformed() {
  getButtonStart().setEnabled(false);
  getButtonStop().setEnabled(true);
  getButtonResume().setEnabled(false);
  getButtonReset().setEnabled(false);
  th.resume();
}

public void buttonStart_ActionPerformed() {
  th=new Thread(this);
  th.start();
}

public void buttonStop_ActionPerformed() {
  getButtonStart().setEnabled(false);
  getButtonStop().setEnabled(false);
  getButtonResume().setEnabled(true);
  getButtonReset().setEnabled(true);
  th.suspend();
}

private java.awt.Button getButtonReset() {
  if (ivjButtonReset == null) {
    ivjButtonReset = new java.awt.Button();
    ivjButtonReset.setName("ButtonReset");
    ivjButtonReset.setEnabled(false);
    ivjButtonReset.setLabel("Reset");
  }
  return ivjButtonReset;
}

private java.awt.Button getButtonResume() {
  if (ivjButtonResume == null) {
    ivjButtonResume = new java.awt.Button();
    ivjButtonResume.setName("ButtonResume");
    ivjButtonResume.setEnabled(false);
    ivjButtonResume.setLabel("Resume");
  }
  return ivjButtonResume;
}

private java.awt.Button getButtonStart() {
  if (ivjButtonStart == null) {
    ivjButtonStart = new java.awt.Button();
    ivjButtonStart.setName("ButtonStart");
    ivjButtonStart.setLabel("Start");
  }
  return ivjButtonStart;
}

private java.awt.Button getButtonStop() {
  if (ivjButtonStop == null) {
    ivjButtonStop = new java.awt.Button();
    ivjButtonStop.setName("ButtonStop");
    ivjButtonStop.setEnabled(false);
    ivjButtonStop.setLabel("Hold");
  }
  return ivjButtonStop;
}

public java.awt.Panel getContentsPane() {
  if (ivjContentsPane == null) {
    ivjContentsPane = new java.awt.Panel();
    ivjContentsPane.setName("ContentsPane");
    ivjContentsPane.setLayout(new java.awt.GridBagLayout());
    ivjContentsPane.setBackground(java.awt.Color.lightGray);

    java.awt.GridBagConstraints constraintsTextField = new java.awt.GridBagConstraints();
    constraintsTextField.gridx = 0; constraintsTextField.gridy = 0;
    constraintsTextField.gridwidth = 4;
    constraintsTextField.fill = java.awt.GridBagConstraints.HORIZONTAL;
    constraintsTextField.weightx = 1.0;
    constraintsTextField.insets = new java.awt.Insets(4, 4, 4, 4);
    getContentsPane().add(getTextField(), constraintsTextField);

    java.awt.GridBagConstraints constraintsButtonStart = new java.awt.GridBagConstraints();
    constraintsButtonStart.gridx = 0; constraintsButtonStart.gridy = 1;
    constraintsButtonStart.weightx = 1.0;
    constraintsButtonStart.insets = new java.awt.Insets(4, 4, 4, 4);
    getContentsPane().add(getButtonStart(), constraintsButtonStart);

    java.awt.GridBagConstraints constraintsButtonHold = new java.awt.GridBagConstraints();
    constraintsButtonHold.gridx = 1; constraintsButtonHold.gridy = 1;
    constraintsButtonHold.weightx = 1.0;
    constraintsButtonHold.insets = new java.awt.Insets(4, 4, 4, 4);
    getContentsPane().add(getButtonStop(), constraintsButtonHold);

    java.awt.GridBagConstraints constraintsButtonReset = new java.awt.GridBagConstraints();
    constraintsButtonReset.gridx = 3; constraintsButtonReset.gridy = 1;
    constraintsButtonReset.weightx = 1.0;
    constraintsButtonReset.insets = new java.awt.Insets(4, 4, 4, 4);
    getContentsPane().add(getButtonReset(), constraintsButtonReset);

    java.awt.GridBagConstraints constraintsButtonResume = new java.awt.GridBagConstraints();
    constraintsButtonResume.gridx = 2; constraintsButtonResume.gridy = 1;
    constraintsButtonResume.insets = new java.awt.Insets(4, 4, 4, 4);
    getContentsPane().add(getButtonResume(), constraintsButtonResume);
  }
  return ivjContentsPane;
}

private java.awt.Panel getContentsPane1() {
  if (ivjContentsPane1 == null) {
    ivjContentsPane1 = new java.awt.Panel();
    ivjContentsPane1.setName("ContentsPane1");
    ivjContentsPane1.setLayout(new java.awt.BorderLayout());
    getContentsPane1().add(getLabelTimeUp(), "Center");
  }
  return ivjContentsPane1;
}

private java.awt.Dialog getDialog() {
  if (ivjDialog == null) {
    ivjDialog = new java.awt.Dialog(this);
    ivjDialog.setName("Dialog");
    ivjDialog.setLayout(new java.awt.BorderLayout());
    ivjDialog.setBounds(340, 74, 189, 53);
    ivjDialog.setModal(true);
    getDialog().add(getContentsPane1(), "Center");
  }
  return ivjDialog;
}

private java.awt.Label getLabelTimeUp() {
  if (ivjLabelTimeUp == null) {
    ivjLabelTimeUp = new java.awt.Label();
    ivjLabelTimeUp.setName("LabelTimeUp");
    ivjLabelTimeUp.setAlignment(java.awt.Label.CENTER);
    ivjLabelTimeUp.setText("Time Up!");
  }
  return ivjLabelTimeUp;
}

private java.awt.TextField getTextField() {
  if (ivjTextField == null) {
    ivjTextField = new java.awt.TextField();
    ivjTextField.setName("TextField");
    ivjTextField.setText("05"+":"+ "00");
    ivjTextField.setBackground(java.awt.Color.white);
    ivjTextField.setEditable(false);
  }
  return ivjTextField;
}

private void handleException(java.lang.Throwable exception) {
  System.err.println(exception);
}

private void initConnections() {
  this.addWindowListener(this);
  getButtonStart().addActionListener(this);
  getButtonStop().addActionListener(this);
  getButtonReset().addActionListener(this);
  getButtonResume().addActionListener(this);
  getDialog().addWindowListener(this);
}

private void initialize() {

    //JFrame countDown = new JFrame();
  setName("Watch");
  setLayout(new java.awt.GridLayout(2,2,5,5));
  setSize(900, 425);
  add(getContentsPane(), "Center");
  
  initConnections();
}
/*
public static void main(java.lang.String[] args) {
  try {
    Watch aWatch;
    aWatch = new Watch();
    aWatch.addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent e) {
        System.exit(0);
      };
    });
    aWatch.setVisible(true);
  } catch (Throwable exception) {
    exception.printStackTrace(System.out);
  }
}
*/
public void run() {
  getButtonStart().setEnabled(false);
  getButtonStop().setEnabled(true);
  getButtonResume().setEnabled(false);
  getButtonReset().setEnabled(false);
  seconds=5*60;
  update();
  while (true){
    Thread th=Thread.currentThread();
    try {
      th.sleep(1000);
    } catch (Exception e){}
    seconds--;
    update();
    if (seconds==0)
      break;
  }
  getButtonStart().setEnabled(false);
  getButtonStop().setEnabled(false);
  getButtonResume().setEnabled(false);
  getButtonReset().setEnabled(true);
  getDialog().show();
}

public void update() {
  String str="";
  int h=seconds;
  int m=seconds/60;
  int s=seconds%60;
  if (m<10)
    str+="0";
  str+=m;
  str+=":";
  if (s<10)
    str+="0";
  str+=s;
  str+="";
  getTextField().setText(str);
}

public void windowActivated(java.awt.event.WindowEvent e) {}
public void windowClosed(java.awt.event.WindowEvent e) {}
public void windowClosing(java.awt.event.WindowEvent e) {
  if (e.getSource() == this)
    this.dispose();
  if (e.getSource() == getDialog())
    getDialog().setVisible(false);
}

public void windowDeactivated(java.awt.event.WindowEvent e) {}
public void windowDeiconified(java.awt.event.WindowEvent e) {}
public void windowIconified(java.awt.event.WindowEvent e) {}
public void windowOpened(java.awt.event.WindowEvent e) {}


}

Open in new window

Comment
Watch Question
CERTIFIED EXPERT
Distinguished Expert 2020
Commented:
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE