Java Swing timer app

Again, quite simple app for Swing exercise.

The application should be run in OS system tray. By clicking on the tray icon, a popup menu appears with two options: Settings and Close.
By clicking Close, the application closes. By clicking Settings, the first window opens, which should contain all the controls. 
After a defined time or at a defined time, it is necessary for another window to appear, whose background will change color, with the background color and the change rate depending on the settings in the first window. 
The second window should appear after the expiration timer defined waiting time. In the first case (onTime) - at the right time, or in the second case (countdown) - after the selected number of minutes. Of course, one option disables the other one. 
The Choose color button displays a dialog with the color palette, where after selection, the color will be displayed in the label next to it. 
It is only important that the chosen color should be replaced with white or some other color to achieve the "blinking" effect. 
A slider control is used to select the color change speed in another window. For the minimum can be taken 100 milliseconds, and for a maximum of 3 seconds. 
The Start button is used to start the timer, with all controls in the first window becoming inactive, except the Stop button.  
The first window should disappear if the Close (x) button is selected. The application is only possible to close from popup menu tray icon.
By pressing the Stop button, the timer is switched off, the other window disappears and controls in the first window again become available.  
First window is made with NetBeans design tool, as shown on picture below.




Main.java

1:  import javax.swing.*;  
2:  import java.awt.*;  
3:  import java.awt.event.*;  
4:  import java.io.File;  
5:  import javax.imageio.ImageIO;  
6:    
7:  /*  
8:   * Djordje Gavrilovic  
9:   */  
10:    
11:  public class Main {  
12:    public static void main(String[] args) {  
13:      SwingUtilities.invokeLater(new Runnable() {  
14:        public void run() {  
15:          stMenu();  
16:        }  
17:      });  
18:    }  
19:      
20:    private static void stMenu() {  
21:      if (!SystemTray.isSupported()) {  
22:        System.out.println("SystemTray is not supported");  
23:        return;  
24:      }  
25:      PopupMenu pm = new PopupMenu();  
26:      MenuItem pmClose = new MenuItem("Close");  
27:      MenuItem pmSet = new MenuItem("Settings");  
28:        
29:      pmClose.addActionListener(new ActionListener() {  
30:        @Override  
31:        public void actionPerformed(ActionEvent e) {  
32:          System.exit(0);  
33:        }  
34:      });  
35:      pmSet.addActionListener(new ActionListener() {  
36:        @Override  
37:        public void actionPerformed(ActionEvent e) {  
38:          SetFrame frame = new SetFrame();  
39:          frame.setSize(500, 400);  
40:          frame.setLocation(100, 200);  
41:          ImageIcon ii = new ImageIcon("rgb.png");  
42:          frame.setIconImage(ii.getImage());  
43:          frame.getContentPane().setBackground(new Color(44, 62, 80));  
44:          frame.setVisible(true);  
45:        }  
46:      });  
47:        
48:      pm.add(pmClose);  
49:      pm.add(pmSet);  
50:        
51:      SystemTray st = SystemTray.getSystemTray();  
52:      try {  
53:        Image img = ImageIO.read(new File("rgb.png"));  
54:        TrayIcon ico = new TrayIcon(img);  
55:        ico.setImageAutoSize(true);  
56:        ico.setToolTip("Assignment");  
57:        ico.setPopupMenu(pm);  
58:        st.add(ico);  
59:      } catch (Exception e) {  
60:        JOptionPane.showMessageDialog(null,"Error: " + e.getMessage());  
61:      }  
62:    }  
63:      
64:  }  
65:    

Data.java

1:  import java.awt.Color;  
2:    
3:  public class Data {  
4:    
5:    private int time1;  
6:    private int time2;  
7:    private Color color;   
8:    private int speed;  
9:      
10:    public void setTime1(int time1) {  
11:      this.time1 = time1;  
12:    }  
13:    public int getTime1() {  
14:      return time1;  
15:    }  
16:      
17:    public void setTime2(int time2){  
18:      this.time2 = time2;  
19:    }  
20:    public int getTime2() {  
21:      return time2;  
22:    }  
23:      
24:    public void setColor (Color color) {  
25:      this.color = color;  
26:    }  
27:    public Color getColor() {  
28:      return color;  
29:    }  
30:      
31:    public void setSpeed (int speed) {  
32:      this.speed = speed;  
33:    }  
34:    public int getSpeed() {  
35:      return speed;  
36:    }  
37:    
38:  }  
39:    
40:    

SetFrame.java

1:  import java.awt.Color;  
2:  import java.awt.event.ActionEvent;  
3:  import java.awt.event.ActionListener;  
4:  import java.text.SimpleDateFormat;  
5:  import java.util.Date;  
6:  import javax.swing.JColorChooser;  
7:  import javax.swing.JDialog;  
8:  import javax.swing.JOptionPane;  
9:  import javax.swing.SwingWorker;  
10:    
11:  public class SetFrame extends javax.swing.JFrame {  
12:      
13:    SwingWorker sw;  
14:    boolean start;  
15:    Object appTime;  
16:    long razlika;  
17:    
18:    public SetFrame() {  
19:      initComponents();  
20:      //this.appTime = new java.util.Date();  
21:      this.appTime = jSpinner1.getValue();  
22:    }  
23:    
24:    /**  
25:     * This method is called from within the constructor to initialize the form.  
26:     * WARNING: Do NOT modify this code. The content of this method is always  
27:     * regenerated by the Form Editor.  
28:     */  
29:    @SuppressWarnings("unchecked")  
30:    // <editor-fold defaultstate="collapsed" desc="Generated Code">               
31:    private void initComponents() {  
32:    
33:      jCheckBox1 = new javax.swing.JCheckBox();  
34:      jCheckBox2 = new javax.swing.JCheckBox();  
35:      jSpinner1 = new javax.swing.JSpinner();  
36:      jSpinner2 = new javax.swing.JSpinner();  
37:      chooseButton = new javax.swing.JButton();  
38:      colorLabel = new javax.swing.JLabel();  
39:      speedLabel = new javax.swing.JLabel();  
40:      jSlider1 = new javax.swing.JSlider();  
41:      stopButton = new javax.swing.JButton();  
42:      startButton = new javax.swing.JButton();  
43:    
44:      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);  
45:      setTitle("TA \\ Settings");  
46:      setBackground(new java.awt.Color(44, 62, 80));  
47:      setSize(new java.awt.Dimension(500, 400));  
48:    
49:      jCheckBox1.setBackground(new Color (44,62,80));  
50:      jCheckBox1.setForeground(java.awt.Color.white);  
51:      jCheckBox1.setText("On time:");  
52:      jCheckBox1.addItemListener(new java.awt.event.ItemListener() {  
53:        public void itemStateChanged(java.awt.event.ItemEvent evt) {  
54:          jCheckBox1ItemStateChanged(evt);  
55:        }  
56:      });  
57:      jCheckBox1.addActionListener(new java.awt.event.ActionListener() {  
58:        public void actionPerformed(java.awt.event.ActionEvent evt) {  
59:          jCheckBox1ActionPerformed(evt);  
60:        }  
61:      });  
62:    
63:      jCheckBox2.setBackground(new Color (44,62,80));  
64:      jCheckBox2.setForeground(java.awt.Color.white);  
65:      jCheckBox2.setText("Countdown (mins):");  
66:      jCheckBox2.addItemListener(new java.awt.event.ItemListener() {  
67:        public void itemStateChanged(java.awt.event.ItemEvent evt) {  
68:          jCheckBox2ItemStateChanged(evt);  
69:        }  
70:      });  
71:    
72:      jSpinner1.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));  
73:      jSpinner1.setEditor(new javax.swing.JSpinner.DateEditor(jSpinner1, "HH:mm:ss"));  
74:    
75:      jSpinner2.setModel(new javax.swing.SpinnerNumberModel());  
76:    
77:      chooseButton.setText("Choose color");  
78:      chooseButton.addActionListener(new java.awt.event.ActionListener() {  
79:        public void actionPerformed(java.awt.event.ActionEvent evt) {  
80:          chooseButtonActionPerformed(evt);  
81:        }  
82:      });  
83:    
84:      colorLabel.setForeground(java.awt.Color.white);  
85:      colorLabel.setText("No color selected");  
86:    
87:      speedLabel.setForeground(java.awt.Color.white);  
88:      speedLabel.setText("Speed (ms):");  
89:    
90:      jSlider1.setBackground(new Color (44,62,80));  
91:      jSlider1.setForeground(java.awt.Color.white);  
92:      jSlider1.setMajorTickSpacing(400);  
93:      jSlider1.setMaximum(3000);  
94:      jSlider1.setMinimum(100);  
95:      jSlider1.setMinorTickSpacing(200);  
96:      jSlider1.setPaintLabels(true);  
97:      jSlider1.setPaintTicks(true);  
98:      jSlider1.setValue(1550);  
99:    
100:      stopButton.setText("Stop");  
101:      stopButton.addActionListener(new java.awt.event.ActionListener() {  
102:        public void actionPerformed(java.awt.event.ActionEvent evt) {  
103:          stopButtonActionPerformed(evt);  
104:        }  
105:      });  
106:    
107:      startButton.setText("Start");  
108:      startButton.addActionListener(new java.awt.event.ActionListener() {  
109:        public void actionPerformed(java.awt.event.ActionEvent evt) {  
110:          startButtonActionPerformed(evt);  
111:        }  
112:      });  
113:    
114:      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
115:      getContentPane().setLayout(layout);  
116:      layout.setHorizontalGroup(  
117:        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
118:        .addGroup(layout.createSequentialGroup()  
119:          .addGap(56, 56, 56)  
120:          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)  
121:            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()  
122:              .addComponent(speedLabel)  
123:              .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))  
124:            .addGroup(layout.createSequentialGroup()  
125:              .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)  
126:                .addGroup(layout.createSequentialGroup()  
127:                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)  
128:                    .addComponent(chooseButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)  
129:                    .addComponent(jCheckBox1)  
130:                    .addComponent(jCheckBox2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))  
131:                  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 170, Short.MAX_VALUE)  
132:                  .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
133:                    .addComponent(jSpinner2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)  
134:                    .addComponent(jSpinner1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)  
135:                    .addComponent(colorLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))  
136:                .addComponent(jSlider1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)  
137:                .addGroup(layout.createSequentialGroup()  
138:                  .addGap(0, 0, Short.MAX_VALUE)  
139:                  .addComponent(startButton)  
140:                  .addGap(18, 18, 18)  
141:                  .addComponent(stopButton)))  
142:              .addGap(57, 57, 57))))  
143:      );  
144:      layout.setVerticalGroup(  
145:        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
146:        .addGroup(layout.createSequentialGroup()  
147:          .addGap(50, 50, 50)  
148:          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
149:            .addComponent(jCheckBox1)  
150:            .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))  
151:          .addGap(18, 18, 18)  
152:          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
153:            .addComponent(jCheckBox2)  
154:            .addComponent(jSpinner2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))  
155:          .addGap(36, 36, 36)  
156:          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
157:            .addComponent(chooseButton)  
158:            .addComponent(colorLabel))  
159:          .addGap(35, 35, 35)  
160:          .addComponent(speedLabel)  
161:          .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
162:          .addComponent(jSlider1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)  
163:          .addGap(38, 38, 38)  
164:          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
165:            .addComponent(stopButton)  
166:            .addComponent(startButton))  
167:          .addContainerGap(66, Short.MAX_VALUE))  
168:      );  
169:    
170:      pack();  
171:    }// </editor-fold>              
172:    
173:    private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {                        
174:      jCheckBox2.setEnabled(false);  
175:      jSpinner2.setEnabled(false);  
176:    }                        
177:    
178:    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {                        
179:      // TODO add your handling code here:  
180:    }                       
181:    
182:    private void jCheckBox2ItemStateChanged(java.awt.event.ItemEvent evt) {                        
183:      jCheckBox1.setEnabled(false);  
184:      jSpinner1.setEnabled(false);  
185:    }                        
186:    
187:    private void chooseButtonActionPerformed(java.awt.event.ActionEvent evt) {                         
188:      JColorChooser jcc = new JColorChooser();  
189:      JDialog dialog = JColorChooser.createDialog(jcc, "Choose color", true, jcc, new ActionListener() {  
190:        @Override  
191:        public void actionPerformed(ActionEvent ae) {  
192:          Color c = jcc.getColor();  
193:          colorLabel.setText("Color selected");  
194:          colorLabel.setOpaque(true);  
195:          colorLabel.setBackground(c);  
196:        }  
197:      },null);  
198:      dialog.setVisible(true);  
199:    }                        
200:    
201:    private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {                        
202:        
203:      jCheckBox1.setEnabled(false);  
204:      jCheckBox2.setEnabled(false);  
205:      jSpinner1.setEnabled(false);  
206:      jSpinner2.setEnabled(false);  
207:      chooseButton.setEnabled(false);  
208:      speedLabel.setEnabled(false);  
209:      jSlider1.setEnabled(false);  
210:      startButton.setEnabled(false);  
211:        
212:      Data d = new Data();  
213:        
214:      d.setColor(colorLabel.getBackground());  
215:      d.setSpeed(jSlider1.getValue());  
216:        
217:      if (jCheckBox1.isSelected()){  
218:        start = true;  
219:        Object set = jSpinner1.getValue();  
220:        String setTime = new SimpleDateFormat("HH:mm:ss").format(set);  
221:        String appTime1 = new SimpleDateFormat("HH:mm:ss").format(appTime);  
222:        try {  
223:          SimpleDateFormat form = new SimpleDateFormat("HH:mm:ss");  
224:          Date d1 = form.parse(setTime);  
225:          Date d2 = form.parse(appTime1);  
226:          razlika = d1.getTime() - d2.getTime();  
227:        } catch (Exception e) {  
228:          JOptionPane.showMessageDialog(null, e.getMessage());  
229:        }           
230:          
231:        sw = new SwingWorker() {  
232:          @Override  
233:          protected Object doInBackground() throws Exception {  
234:            Thread.sleep(razlika);  
235:            ColorFrame.startTheShow();  
236:            while(start){  
237:              ColorFrame.cf.getContentPane().setBackground(d.getColor());  
238:              Thread.sleep(d.getSpeed());  
239:              ColorFrame.cf.getContentPane().setBackground(new Color (44,62,80));  
240:              Thread.sleep(d.getSpeed());  
241:            }     
242:            return null;   
243:          }  
244:          @Override  
245:          protected void done () {  
246:            JOptionPane.showMessageDialog(null,"Thanks for watching!");  
247:            ColorFrame.cf.dispose();  
248:            d.setColor(null);  
249:            jSpinner1.setValue(new java.util.Date());  
250:            start = false;  
251:          }  
252:        };  
253:        sw.execute();  
254:      }  
255:        
256:      else if (jCheckBox2.isSelected()) {  
257:        d.setTime2((Integer)jSpinner2.getValue());  
258:        start = true;  
259:        sw = new SwingWorker() {         
260:          @Override  
261:          protected Object doInBackground() throws Exception {  
262:            Thread.sleep(d.getTime2()*60000);  
263:            ColorFrame.startTheShow();  
264:            while(start){  
265:              ColorFrame.cf.getContentPane().setBackground(d.getColor());  
266:              Thread.sleep(d.getSpeed());  
267:              ColorFrame.cf.getContentPane().setBackground(new Color (44,62,80));  
268:              Thread.sleep(d.getSpeed());  
269:            }   
270:            return null;  
271:          }  
272:          @Override  
273:          protected void done () {  
274:            JOptionPane.showMessageDialog(null,"Thanks for watching!");  
275:            ColorFrame.cf.dispose();  
276:            d.setColor(null);  
277:            start = false;  
278:          }  
279:        };  
280:        sw.execute();  
281:      }  
282:      else {  
283:        JOptionPane.showMessageDialog(this, "No checkbox selected!");  
284:      }  
285:        
286:    }                        
287:    
288:    private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {                        
289:      sw.cancel(false);  
290:      jCheckBox1.setEnabled(true);  
291:      jCheckBox2.setEnabled(true);  
292:      jSpinner1.setEnabled(true);  
293:      jSpinner2.setEnabled(true);  
294:      chooseButton.setEnabled(true);  
295:      speedLabel.setEnabled(true);  
296:      jSlider1.setEnabled(true);  
297:      startButton.setEnabled(true);  
298:      colorLabel.setBackground(null);  
299:      colorLabel.setText("No color selected");  
300:    }                       
301:    
302:    /**  
303:     * @param args the command line arguments  
304:     */  
305:    public static void main(String args[]) {  
306:      /* Set the Nimbus look and feel */  
307:      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">  
308:      /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.  
309:       * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html   
310:       */  
311:      try {  
312:        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {  
313:          if ("Nimbus".equals(info.getName())) {  
314:            javax.swing.UIManager.setLookAndFeel(info.getClassName());  
315:            break;  
316:          }  
317:        }  
318:      } catch (ClassNotFoundException ex) {  
319:        java.util.logging.Logger.getLogger(SetFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
320:      } catch (InstantiationException ex) {  
321:        java.util.logging.Logger.getLogger(SetFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
322:      } catch (IllegalAccessException ex) {  
323:        java.util.logging.Logger.getLogger(SetFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
324:      } catch (javax.swing.UnsupportedLookAndFeelException ex) {  
325:        java.util.logging.Logger.getLogger(SetFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
326:      }  
327:      //</editor-fold>  
328:    
329:      /* Create and display the form */  
330:      java.awt.EventQueue.invokeLater(new Runnable() {  
331:        public void run() {  
332:          new SetFrame().setVisible(true);  
333:        }  
334:      });  
335:    }  
336:    
337:    // Variables declaration - do not modify             
338:    private javax.swing.JButton chooseButton;  
339:    private javax.swing.JLabel colorLabel;  
340:    private javax.swing.JCheckBox jCheckBox1;  
341:    private javax.swing.JCheckBox jCheckBox2;  
342:    private javax.swing.JSlider jSlider1;  
343:    private javax.swing.JSpinner jSpinner1;  
344:    private javax.swing.JSpinner jSpinner2;  
345:    private javax.swing.JLabel speedLabel;  
346:    private javax.swing.JButton startButton;  
347:    private javax.swing.JButton stopButton;  
348:    // End of variables declaration            
349:  }  
350:    

ColorFrame.java

1:  import java.awt.*;  
2:  import javax.swing.*;  
3:    
4:    
5:  public class ColorFrame {  
6:    static JFrame cf;  
7:    static ImageIcon ii;  
8:      
9:    static void startTheShow(){  
10:      cf = new JFrame();  
11:      cf.setSize(500,200);  
12:      cf.setLocation(605, 190);  
13:      cf.getContentPane().setBackground(new Color(44,62,80));  
14:      ii = new ImageIcon("rgb.png");  
15:      cf.setIconImage(ii.getImage());  
16:      cf.setTitle("TA Color Frame");  
17:        
18:      cf.setVisible(true);  
19:    }  
20:      
21:  }  

Comments

  1. Buna ziua domnule. Am nevoie de o aplicatie asemanatoare. Ma puteti ajuta modificand codul actual? In loc de slider trebuie sa fie un combobox si totodata sa fie posibila selectarea simultana a ambelor sectiuni radiobox. Am mare nevoie de ajutor.

    ReplyDelete
  2. Hello sir. I need a similar application. Can you help me by changing the current code? Instead of a slider, it must be a combobox and at the same time it must be possible to select both radiobox sections simultaneously. I really need help.

    ReplyDelete

Post a Comment