Java Project
CodeZip/ButtonDemo.java
CodeZip/ButtonDemo.java
// Demonstrate a push button and handle action events.
import
java
.
awt
.
*
;
import
java
.
awt
.
event
.
*
;
import
javax
.
swing
.
*
;
public
class
ButtonDemo
implements
ActionListener
{
JLabel
jlab
;
JTextField
jtf
;
ButtonDemo
()
{
// Create a new JFrame container.
JFrame
jfrm
=
new
JFrame
(
"A Button Example"
);
// Specify FlowLayout for the layout manager.
jfrm
.
setLayout
(
new
FlowLayout
());
// Give the frame an initial size.
jfrm
.
setSize
(
220
,
90
);
// Terminate the program when the user closes the application.
jfrm
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// Make two buttons.
JButton
jbtnUp
=
new
JButton
(
"Up"
);
JButton
jbtnDown
=
new
JButton
(
"Down"
);
// Create a text field.
jtf
=
new
JTextField
(
10
);
// Add action listeners.
jbtnUp
.
addActionListener
(
this
);
jbtnDown
.
addActionListener
(
this
);
// Add the buttons to the content pane.
jfrm
.
add
(
jbtnUp
);
jfrm
.
add
(
jbtnDown
);
jfrm
.
add
(
jtf
);
// Create a label.
jlab
=
new
JLabel
(
"Press a button."
);
// Add the label to the frame.
jfrm
.
add
(
jlab
);
// Display the frame.
jfrm
.
setVisible
(
true
);
}
// Handle button events.
public
void
actionPerformed
(
ActionEvent
ae
)
{
if
(
ae
.
getActionCommand
().
equals
(
"Up"
))
{
jlab
.
setText
(
"You pressed Up."
);
FileClock
clock1
=
new
FileClock
(
jtf
);
Thread
thread1
=
new
Thread
(
clock1
);
thread1
.
start
();
}
else
jlab
.
setText
(
"You pressed down. "
);
}
public
static
void
main
(
String
args
[])
{
// Create the frame on the event dispatching thread.
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
public
void
run
()
{
new
ButtonDemo
();
}
});
}
}
CodeZip/CBDemo.java
CodeZip/CBDemo.java
// Demonstrate check boxes.
import
java
.
awt
.
*
;
import
java
.
awt
.
event
.
*
;
import
javax
.
swing
.
*
;
public
class
CBDemo
implements
ItemListener
{
JLabel
jlabSelected
;
JLabel
jlabChanged
;
JCheckBox
jcbAlpha
;
JCheckBox
jcbBeta
;
JCheckBox
jcbGamma
;
CBDemo
()
{
// Create a new JFrame container.
JFrame
jfrm
=
new
JFrame
(
"Demonstrate Check Boxes"
);
// Specify FlowLayout for the layout manager.
jfrm
.
setLayout
(
new
FlowLayout
());
// Give the frame an initial size.
jfrm
.
setSize
(
280
,
120
);
// Terminate the program when the user closes the application.
jfrm
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// Create empty labels.
jlabSelected
=
new
JLabel
(
""
);
jlabChanged
=
new
JLabel
(
""
);
// Make check boxes.
jcbAlpha
=
new
JCheckBox
(
"Alpha"
);
jcbBeta
=
new
JCheckBox
(
"Beta"
);
jcbGamma
=
new
JCheckBox
(
"Gamma"
);
// Events generated by the check boxes
// are handled in common by the itemStateChanged()
// method implemented by CBDemo.
jcbAlpha
.
addItemListener
(
this
);
jcbBeta
.
addItemListener
(
this
);
jcbGamma
.
addItemListener
(
this
);
// Add checkboxes and labels to the content pane.
jfrm
.
add
(
jcbAlpha
);
jfrm
.
add
(
jcbBeta
);
jfrm
.
add
(
jcbGamma
);
jfrm
.
add
(
jlabChanged
);
jfrm
.
add
(
jlabSelected
);
// Display the frame.
jfrm
.
setVisible
(
true
);
}
// This is the handler for the check boxes.
public
void
itemStateChanged
(
ItemEvent
ie
)
{
String
str
=
""
;
// Obtain a reference to the check box that
// caused the event.
JCheckBox
cb
=
(
JCheckBox
)
ie
.
getItem
();
// Report what check box changed.
if
(
cb
.
isSelected
())
jlabChanged
.
setText
(
cb
.
getText
()
+
" was just selected."
);
else
jlabChanged
.
setText
(
cb
.
getText
()
+
" was just cleared."
);
// Report all selected boxes.
if
(
jcbAlpha
.
isSelected
())
{
str
+=
"Alpha "
;
}
if
(
jcbBeta
.
isSelected
())
{
str
+=
"Beta "
;
}
if
(
jcbGamma
.
isSelected
())
{
str
+=
"Gamma"
;
}
jlabSelected
.
setText
(
"Selected check boxes: "
+
str
);
}
public
static
void
main
(
String
args
[])
{
// Create the frame on the event dispatching thread.
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
public
void
run
()
{
new
CBDemo
();
}
});
}
}
CodeZip/CurrentThreadDemo.java
CodeZip/CurrentThreadDemo.java
// Controlling the main Thread.
class
CurrentThreadDemo
{
public
static
void
main
(
String
args
[])
{
Thread
t
=
Thread
.
currentThread
();
System
.
out
.
println
(
"Current thread: "
+
t
);
// change the name of the thread
t
.
setName
(
"My Thread"
);
System
.
out
.
println
(
"After name change: "
+
t
);
try
{
for
(
int
n
=
5
;
n
>
0
;
n
--
)
{
System
.
out
.
println
(
n
);
Thread
.
sleep
(
1000
);
}
}
catch
(
InterruptedException
e
)
{
System
.
out
.
println
(
"Main thread interrupted"
);
}
}
}
CodeZip/FileMain.java
CodeZip/FileMain.java
import
java
.
util
.
Date
;
import
javax
.
swing
.
*
;
class
FileClock
implements
Runnable
{
JTextField
jtf
;
public
FileClock
(
JTextField
jtf
){
this
.
jtf
=
jtf
;
}
@
Override
public
void
run
()
{
for
(
int
i
=
0
;
i
<
10
;
i
++
)
{
System
.
out
.
printf
(
"%s\n"
,
new
Date
());
Date
d1
=
new
Date
();
jtf
.
setText
(
d1
.
toString
());
try
{
Thread
.
sleep
(
1000
);
}
catch
(
InterruptedException
e
)
{
System
.
out
.
printf
(
"The FileClock has been interrupted"
);
}
}
}
}
public
class
FileMain
{
public
static
void
main
(
String
[]
args
)
{
JTextField
jtf
=
new
JTextField
();
FileClock
clock1
=
new
FileClock
(
jtf
);
FileClock
clock2
=
new
FileClock
(
jtf
);
Thread
thread1
=
new
Thread
(
clock1
);
thread1
.
start
();
Thread
thread2
=
new
Thread
(
clock2
);
thread2
.
start
();
NewThread
nt1
=
new
NewThread
(
"One"
);
NewThread
nt2
=
new
NewThread
(
"Two"
);
NewThread
nt3
=
new
NewThread
(
"Three"
);
// Start the threads.
nt1
.
t
.
start
();
nt2
.
t
.
start
();
nt3
.
t
.
start
();
try
{
Thread
.
sleep
(
5000
);
}
catch
(
InterruptedException
e
)
{
e
.
printStackTrace
();
};
thread1
.
interrupt
();
thread2
.
interrupt
();
}
}
CodeZip/ListDemo.java
CodeZip/ListDemo.java
// Demonstrate a simple JList.
import
javax
.
swing
.
*
;
import
javax
.
swing
.
event
.
*
;
import
java
.
awt
.
*
;
import
java
.
awt
.
event
.
*
;
public
class
ListDemo
implements
ListSelectionListener
{
JList
<
String
>
jlst
;
JLabel
jlab
;
JScrollPane
jscrlp
;
// Create an array of names.
String
names
[]
=
{
"Sherry"
,
"Jon"
,
"Rachel"
,
"Sasha"
,
"Josselyn"
,
"Randy"
,
"Tom"
,
"Mary"
,
"Ken"
,
"Andrew"
,
"Matt"
,
"Todd"
};
ListDemo
()
{
// Create a new JFrame container.
JFrame
jfrm
=
new
JFrame
(
"JList Demo"
);
// Specify a flow Layout.
jfrm
.
setLayout
(
new
FlowLayout
());
// Give the frame an initial size.
jfrm
.
setSize
(
200
,
160
);
// Terminate the program when the user closes the application.
jfrm
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// Create a JList.
jlst
=
new
JList
<
String
>
(
names
);
// Set the list selection mode to single-selection.
jlst
.
setSelectionMode
(
ListSelectionModel
.
SINGLE_SELECTION
);
// Add list to a scroll pane.
jscrlp
=
new
JScrollPane
(
jlst
);
// Set the preferred size of the scroll pane.
jscrlp
.
setPreferredSize
(
new
Dimension
(
120
,
90
));
// Make a label that displays the selection.
jlab
=
new
JLabel
(
"Please choose a name"
);
// Add list selection handler.
jlst
.
addListSelectionListener
(
this
);
// Add the list and label to the content pane.
jfrm
.
add
(
jscrlp
);
jfrm
.
add
(
jlab
);
// Display the frame.
jfrm
.
setVisible
(
true
);
}
// Handle list selection events.
public
void
valueChanged
(
ListSelectionEvent
le
)
{
// Get the index of the changed item.
int
idx
=
jlst
.
getSelectedIndex
();
// Display selection, if item was selected.
if
(
idx
!=
-
1
)
jlab
.
setText
(
"Current selection: "
+
names
[
idx
]);
else
// Othewise, reprompt.
jlab
.
setText
(
"Please choose an name"
);
}
public
static
void
main
(
String
args
[])
{
// Create the frame on the event dispatching thread.
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
public
void
run
()
{
new
ListDemo
();
}
});
}
}
CodeZip/Main.java
CodeZip/Main.java
class
Calculator
implements
Runnable
{
private
int
number
;
public
Calculator
(
int
number
)
{
this
.
number
=
number
;
}
@
Override
public
void
run
()
{
for
(
int
i
=
1
;
i
<=
10
;
i
++
){
System
.
out
.
printf
(
"%s: %d * %d = %d\n"
,
Thread
.
currentThread
().
getName
(),
number
,
i
,
i
*
number
);
}
}
}
public
class
Main
{
public
static
void
main
(
String
[]
args
)
{
for
(
int
i
=
1
;
i
<=
10
;
i
++
){
Calculator
calculator
=
new
Calculator
(
i
);
Thread
thread
=
new
Thread
(
calculator
);
thread
.
start
();
}
}
}
CodeZip/MultiThreadDemo.java
CodeZip/MultiThreadDemo.java
class
MultiThreadDemo
{
public
static
void
main
(
String
args
[])
{
NewThread
nt1
=
new
NewThread
(
"One"
);
NewThread
nt2
=
new
NewThread
(
"Two"
);
NewThread
nt3
=
new
NewThread
(
"Three"
);
// Start the threads.
nt1
.
t
.
start
();
nt2
.
t
.
start
();
nt3
.
t
.
start
();
try
{
// wait for other threads to end
Thread
.
sleep
(
10000
);
}
catch
(
InterruptedException
e
)
{
System
.
out
.
println
(
"Main thread Interrupted"
);
}
System
.
out
.
println
(
"Main thread exiting."
);
}
}
// Create multiple threads.
class
NewThread
implements
Runnable
{
String
name
;
// name of thread
Thread
t
;
NewThread
(
String
threadname
)
{
name
=
threadname
;
t
=
new
Thread
(
this
,
name
);
System
.
out
.
println
(
"New thread: "
+
t
);
}
// This is the entry point for thread.
public
void
run
()
{
try
{
for
(
int
i
=
5
;
i
>
0
;
i
--
)
{
System
.
out
.
println
(
name
+
": "
+
i
);
Thread
.
sleep
(
1000
);
}
}
catch
(
InterruptedException
e
)
{
System
.
out
.
println
(
name
+
"Interrupted"
);
}
System
.
out
.
println
(
name
+
" exiting."
);
}
}
CodeZip/SwingDemo.java
CodeZip/SwingDemo.java
// A simple Swing program.
import
javax
.
swing
.
*
;
public
class
SwingDemo
{
SwingDemo
()
{
// Create a new JFrame container.
JFrame
jfrm
=
new
JFrame
(
"A Simple Swing Application"
);
// Give the frame an initial size.
jfrm
.
setSize
(
275
,
100
);
// Terminate the program when the user closes the application.
jfrm
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// Create a text-based label.
JLabel
jlab
=
new
JLabel
(
" GUI programming is easy with Swing."
);
// Add the label to the content pane.
jfrm
.
add
(
jlab
);
// Display the frame.
jfrm
.
setVisible
(
true
);
}
public
static
void
main
(
String
args
[])
{
// Create the frame on the event dispatching thread.
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
public
void
run
()
{
new
SwingDemo
();
}
});
}
}
CodeZip/SwingFC.java
CodeZip/SwingFC.java
/*
Try This 16-1
A Swing-based file comparison utility.
*/
import
java
.
awt
.
*
;
import
java
.
awt
.
event
.
*
;
import
javax
.
swing
.
*
;
import
java
.
io
.
*
;
public
class
SwingFC
implements
ActionListener
{
JTextField
jtfFirst
;
// holds the first file name
JTextField
jtfSecond
;
// holds the second file name
JButton
jbtnComp
;
// button to compare the files
JLabel
jlabFirst
,
jlabSecond
;
// displays prompts
JLabel
jlabResult
;
// displays results and error messages
SwingFC
()
{
// Create a new JFrame container.
JFrame
jfrm
=
new
JFrame
(
"Compare Files"
);
// Specify FlowLayout for the layout manager.
jfrm
.
setLayout
(
new
FlowLayout
());
// Give the frame an initial size.
jfrm
.
setSize
(
200
,
190
);
// Terminate the program when the user closes the application.
jfrm
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// Create the text fields for the file names..
jtfFirst
=
new
JTextField
(
14
);
jtfSecond
=
new
JTextField
(
14
);
// Set the action commands for the text fields.
jtfFirst
.
setActionCommand
(
"fileA"
);
jtfSecond
.
setActionCommand
(
"fileB"
);
// Create the Compare button.
JButton
jbtnComp
=
new
JButton
(
"Compare"
);
// Add action listener for the Compare button.
jbtnComp
.
addActionListener
(
this
);
// Create the labels.
jlabFirst
=
new
JLabel
(
"First file: "
);
jlabSecond
=
new
JLabel
(
"Second file: "
);
jlabResult
=
new
JLabel
(
""
);
// Add the components to the content pane.
jfrm
.
add
(
jlabFirst
);
jfrm
.
add
(
jtfFirst
);
jfrm
.
add
(
jlabSecond
);
jfrm
.
add
(
jtfSecond
);
jfrm
.
add
(
jbtnComp
);
jfrm
.
add
(
jlabResult
);
// Display the frame.
jfrm
.
setVisible
(
true
);
}
// Compare the files when the Compare button is pressed.
public
void
actionPerformed
(
ActionEvent
ae
)
{
int
i
=
0
,
j
=
0
;
// First, confirm that both file names have
// been entered.
if
(
jtfFirst
.
getText
().
equals
(
""
))
{
jlabResult
.
setText
(
"First file name missing."
);
return
;
}
if
(
jtfSecond
.
getText
().
equals
(
""
))
{
jlabResult
.
setText
(
"Second file name missing."
);
return
;
}
// Compare files. Use try-with-resources to manage the files.
try
(
FileInputStream
f1
=
new
FileInputStream
(
jtfFirst
.
getText
());
FileInputStream
f2
=
new
FileInputStream
(
jtfSecond
.
getText
()))
{
// Check the contents of each file.
do
{
i
=
f1
.
read
();
j
=
f2
.
read
();
if
(
i
!=
j
)
break
;
}
while
(
i
!=
-
1
&&
j
!=
-
1
);
if
(
i
!=
j
)
jlabResult
.
setText
(
"Files are not the same."
);
else
jlabResult
.
setText
(
"Files compare equal."
);
}
catch
(
IOException
exc
)
{
jlabResult
.
setText
(
"File Error"
);
}
}
public
static
void
main
(
String
args
[])
{
// Create the frame on the event dispatching thread.
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
public
void
run
()
{
new
SwingFC
();
}
});
}
}
CodeZip/TFDemo.java
CodeZip/TFDemo.java
// Use a text field.
import
java
.
awt
.
*
;
import
java
.
awt
.
event
.
*
;
import
javax
.
swing
.
*
;
public
class
TFDemo
implements
ActionListener
{
JTextField
jtf
;
JButton
jbtnRev
;
JLabel
jlabPrompt
,
jlabContents
;
TFDemo
()
{
// Create a new JFrame container.
JFrame
jfrm
=
new
JFrame
(
"Use a Text Field"
);
// Specify FlowLayout for the layout manager.
jfrm
.
setLayout
(
new
FlowLayout
());
// Give the frame an initial size.
jfrm
.
setSize
(
240
,
120
);
// Terminate the program when the user closes the application.
jfrm
.
setDefaultCloseOperation
(
JFrame
.
EXIT_ON_CLOSE
);
// Create a text field.
jtf
=
new
JTextField
(
10
);
// Set the action commands for the text field.
jtf
.
setActionCommand
(
"myTF"
);
// Create the Reverse button.
JButton
jbtnRev
=
new
JButton
(
"Reverse"
);
// Add action listeners.
jtf
.
addActionListener
(
this
);
jbtnRev
.
addActionListener
(
this
);
// Create the labels.
jlabPrompt
=
new
JLabel
(
"Enter text: "
);
jlabContents
=
new
JLabel
(
""
);
// Add the components to the content pane.
jfrm
.
add
(
jlabPrompt
);
jfrm
.
add
(
jtf
);
jfrm
.
add
(
jbtnRev
);
jfrm
.
add
(
jlabContents
);
// Display the frame.
jfrm
.
setVisible
(
true
);
}
// Handle action events.
public
void
actionPerformed
(
ActionEvent
ae
)
{
if
(
ae
.
getActionCommand
().
equals
(
"Reverse"
))
{
// The Reverse button was pressed.
String
orgStr
=
jtf
.
getText
();
String
resStr
=
""
;
// Reverse the string in the text field.
for
(
int
i
=
orgStr
.
length
()
-
1
;
i
>=
0
;
i
--
)
resStr
+=
orgStr
.
charAt
(
i
);
// Store the reversed string in the text field.
jtf
.
setText
(
resStr
);
}
else
// Enter was pressed while focus was in the
// text field.
jlabContents
.
setText
(
"You pressed ENTER. Text is: "
+
jtf
.
getText
());
}
public
static
void
main
(
String
args
[])
{
// Create the frame on the event dispatching thread.
SwingUtilities
.
invokeLater
(
new
Runnable
()
{
public
void
run
()
{
new
TFDemo
();
new
ButtonDemo
();
new
FileMain
();
}
});
}
}
CodeZip/TrafficLightDemo.java
CodeZip/TrafficLightDemo.java
// Try This 12-1
// A simulation of a traffic light that uses
// an enumeration to describe the light's color.
// An enumeration of the colors of a traffic light.
enum
TrafficLightColor
{
RED
,
GREEN
,
YELLOW
}
// A computerized traffic light.
class
TrafficLightSimulator
implements
Runnable
{
private
TrafficLightColor
tlc
;
// holds the current traffic light color
private
boolean
stop
=
false
;
// set to true to stop the simulation
private
boolean
changed
=
false
;
// true when the light has changed
TrafficLightSimulator
(
TrafficLightColor
init
)
{
tlc
=
init
;
}
TrafficLightSimulator
()
{
tlc
=
TrafficLightColor
.
RED
;
}
// Start up the light.
public
void
run
()
{
while
(
!
stop
)
{
try
{
switch
(
tlc
)
{
case
GREEN
:
Thread
.
sleep
(
10000
);
// green for 10 seconds
break
;
case
YELLOW
:
Thread
.
sleep
(
2000
);
// yellow for 2 seconds
break
;
case
RED
:
Thread
.
sleep
(
12000
);
// red for 12 seconds
break
;
}
}
catch
(
InterruptedException
exc
)
{
System
.
out
.
println
(
exc
);
}
changeColor
();
}
}
// Change color.
synchronized
void
changeColor
()
{
switch
(
tlc
)
{
case
RED
:
tlc
=
TrafficLightColor
.
GREEN
;
break
;
case
YELLOW
:
tlc
=
TrafficLightColor
.
RED
;
break
;
case
GREEN
:
tlc
=
TrafficLightColor
.
YELLOW
;
}
changed
=
true
;
notify
();
// signal that the light has changed
}
// Wait until a light change occurs.
synchronized
void
waitForChange
()
{
try
{
while
(
!
changed
)
wait
();
// wait for light to change
changed
=
false
;
}
catch
(
InterruptedException
exc
)
{
System
.
out
.
println
(
exc
);
}
}
// Return current color.
synchronized
TrafficLightColor
getColor
()
{
return
tlc
;
}
// Stop the traffic light.
synchronized
void
cancel
()
{
stop
=
true
;
}
}
class
TrafficLightDemo
{
public
static
void
main
(
String
args
[])
{
TrafficLightSimulator
tl
=
new
TrafficLightSimulator
(
TrafficLightColor
.
GREEN
);
Thread
thrd
=
new
Thread
(
tl
);
thrd
.
start
();
for
(
int
i
=
0
;
i
<
9
;
i
++
)
{
System
.
out
.
println
(
tl
.
getColor
());
tl
.
waitForChange
();
}
tl
.
cancel
();
}
}