Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Creating Your Own Component 181

The first step in creating your own user interface component is to decide
the existing component from which to inherit. The ClockPanelcomponent
is a subclass of JPanel.


The ClockPanelclass is defined in Listing 13.3. This class represents panel
components that include a label displaying the current date and time.
Enter the text from Listing 13.3 into a new empty Java file and save the file.


LISTING 13.3 The Full Text of ClockPanel.java
1: importjavax.swing.;
2: importjava.awt.
;
3: importjava.util.*;
4:
5: public classClockPanel extendsJPanel {
6: publicClockPanel() {
7: super();
8: String currentTime = getTime();
9: JLabel time = new JLabel(“Time:“);
10: JLabel current = newJLabel(currentTime);
11: add(time);
12: add(current);
13: }
14:
15: finalString getTime() {
16: String time;
17: // get current time and date
18: Calendar now = Calendar.getInstance();
19: int hour = now.get(Calendar.HOUR_OF_DAY);
20: intminute = now.get(Calendar.MINUTE);
21: intmonth = now.get(Calendar.MONTH) + 1;
22: intday = now.get(Calendar.DAY_OF_MONTH);
23: int year = now.get(Calendar.YEAR);
24:
25: String monthName = “”;
26: switch(month) {
27: case(1):
28: monthName = “January”;
29: break;
30: case(2):
31: monthName = “February”;
32: break;
33: case(3):
34: monthName = “March”;
35: break;
36: case(4):
37: monthName = “April”;
38: break;
39: case(5):
40: monthName = “May”;
41: break;
42: case(6):

Free download pdf