corejava第10版
This commit is contained in:
1 parent
2021c3c227
commit
6165543dd3
1088 files changed
+94411
No files matched your search
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,70 @@
|
||||
import java.awt.*;
|
||||
import java.io.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A program for viewing images.
|
||||
* @version 1.30 2014-02-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ImageViewer
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() -> {
|
||||
JFrame frame = new ImageViewerFrame();
|
||||
frame.setTitle("ImageViewer");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a label to show an image.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
private JLabel label;
|
||||
private JFileChooser chooser;
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// use a label to display the images
|
||||
label = new JLabel();
|
||||
add(label);
|
||||
|
||||
// set up the file chooser
|
||||
chooser = new JFileChooser();
|
||||
chooser.setCurrentDirectory(new File("."));
|
||||
|
||||
// set up the menu bar
|
||||
JMenuBar menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
JMenu menu = new JMenu("File");
|
||||
menuBar.add(menu);
|
||||
|
||||
JMenuItem openItem = new JMenuItem("Open");
|
||||
menu.add(openItem);
|
||||
openItem.addActionListener(event -> {
|
||||
// show file chooser dialog
|
||||
int result = chooser.showOpenDialog(null);
|
||||
|
||||
// if file selected, set it as icon of the label
|
||||
if (result == JFileChooser.APPROVE_OPTION)
|
||||
{
|
||||
String name = chooser.getSelectedFile().getPath();
|
||||
label.setIcon(new ImageIcon(name));
|
||||
}
|
||||
});
|
||||
|
||||
JMenuItem exitItem = new JMenuItem("Exit");
|
||||
menu.add(exitItem);
|
||||
exitItem.addActionListener(event -> System.exit(0));
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,60 @@
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>A Traffic Simulator Applet</title></head>
|
||||
<body>
|
||||
<h1>Traffic Simulator Applet</h1>
|
||||
|
||||
<p>I wrote this traffic simulation, following the article "Und nun die
|
||||
Stauvorhersage" of the German Magazine <i>Die Zeit</i>, June 7,
|
||||
1996. The article describes the work of Professor Michael Schreckenberger
|
||||
of the University of Duisburg and unnamed collaborators at the University
|
||||
of Cologne and Los Alamos National Laboratory. These researchers model
|
||||
traffic flow according to simple rules, such as the following: </p>
|
||||
<ul>
|
||||
<li>A freeway is modeled as a sequence of grid points. </li>
|
||||
<li>Every car occupies one grid point. Each grid point occupies at most
|
||||
one car. </li>
|
||||
<li>A car can have a speed of 0 - 5 grid points per time interval. </li>
|
||||
<li>A car with speed of less than 5 increases its speed by one unit in
|
||||
each time interval, until it reaches the maximum speed. </li>
|
||||
<li>If a car's distance to the car in front is <i>d</i> grid points, its
|
||||
speed is reduced to <i>d</i>-1 if necessary to avoid crashing into it.
|
||||
</li>
|
||||
<li>With a certain probability, in each time interval some cars slow down
|
||||
one unit for no good reason whatsoever. </li>
|
||||
</ul>
|
||||
|
||||
<p>This applet models these rules. Each line shows an image of the same
|
||||
stretch of road. Each square denotes one car. The first scrollbar lets you
|
||||
adjust the probability that some cars slow down. If the slider is all the
|
||||
way to the left, no car slows down. If it is all the way to the right,
|
||||
every car slows down one unit. A typical setting is that 10% - 20% of the
|
||||
cars slow down. The second slider controls the arrival rate of the cars.
|
||||
When it is all the way to the left, no new cars enter the freeway. If it
|
||||
is all the way to the right, a new car enters the freeway every time
|
||||
interval, provided the freeway entrance is not blocked. </p>
|
||||
|
||||
<p>Try out the following experiments. Decrease the probability of slowdown
|
||||
to 0. Crank up the arrival rate to 1. That means, every time unit, a new
|
||||
car enters the road. Note how the road can carry this load. </p>
|
||||
|
||||
<p>Now increase the probability that some cars slow down. Note how traffic
|
||||
jams occur almost immediately. </p>
|
||||
|
||||
<p>The moral is: If it wasn't for the rubberneckers, the cellular phone
|
||||
users, and the makeup-appliers who can't keep up a constant speed, we'd all
|
||||
get to work more quickly. </p>
|
||||
|
||||
<p>Notice how the traffic jam is stationary or even moves backwards, even
|
||||
though the individual cars are still moving. In fact, the first car
|
||||
causing the jam has long left the scene by the time the jam gets bad.
|
||||
(To make it easier to track cars, every tenth vehicle is colored red.) </p>
|
||||
|
||||
<p><applet code="RoadApplet.class" archive="RoadApplet.jar"
|
||||
width="400" height="400" alt="Traffic jam visualization">
|
||||
</applet></p>
|
||||
|
||||
<p>For more information about applets, graphics programming and
|
||||
multithreading in Java, see
|
||||
<a href="http://horstmann.com/corejava">Core Java</a>. </p>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
@@ -0,0 +1,46 @@
|
||||
import java.awt.*;
|
||||
import java.applet.*;
|
||||
import javax.swing.*;
|
||||
|
||||
public class RoadApplet extends JApplet
|
||||
{
|
||||
private RoadComponent roadComponent;
|
||||
private JSlider slowdown;
|
||||
private JSlider arrival;
|
||||
|
||||
public void init()
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
roadComponent = new RoadComponent();
|
||||
slowdown = new JSlider(0, 100, 10);
|
||||
arrival = new JSlider(0, 100, 50);
|
||||
|
||||
JPanel p = new JPanel();
|
||||
p.setLayout(new GridLayout(1, 6));
|
||||
p.add(new JLabel("Slowdown"));
|
||||
p.add(slowdown);
|
||||
p.add(new JLabel(""));
|
||||
p.add(new JLabel("Arrival"));
|
||||
p.add(arrival);
|
||||
p.add(new JLabel(""));
|
||||
setLayout(new BorderLayout());
|
||||
add(p, BorderLayout.NORTH);
|
||||
add(roadComponent, BorderLayout.CENTER);
|
||||
});
|
||||
}
|
||||
|
||||
public void start()
|
||||
{
|
||||
new Thread(() ->
|
||||
{
|
||||
for (;;)
|
||||
{
|
||||
roadComponent.update(
|
||||
0.01 * slowdown.getValue(),
|
||||
0.01 * arrival.getValue());
|
||||
try { Thread.sleep(50); } catch(InterruptedException e) {}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
Manifest-Version: 1.0
|
||||
Permissions: sandbox
|
||||
@@ -0,0 +1,123 @@
|
||||
import java.awt.*;
|
||||
import java.awt.image.*;
|
||||
import javax.swing.*;
|
||||
|
||||
public class RoadComponent extends JComponent
|
||||
{
|
||||
private final int DOTSIZE = 2;
|
||||
private final int XDOTDIST = 1;
|
||||
private Road freeway;
|
||||
private BufferedImage buffer;
|
||||
private int row;
|
||||
private int xsize;
|
||||
private int ysize;
|
||||
|
||||
public RoadComponent()
|
||||
{
|
||||
freeway = new Road();
|
||||
row = 0;
|
||||
}
|
||||
|
||||
public void update(double slowdown, double arrival)
|
||||
{
|
||||
freeway.update(slowdown, arrival);
|
||||
Graphics g;
|
||||
if (buffer == null)
|
||||
{
|
||||
xsize = getWidth();
|
||||
ysize = getHeight();
|
||||
if (xsize == 0 || ysize == 0) return;
|
||||
buffer = new BufferedImage(xsize, ysize, BufferedImage.TYPE_INT_ARGB);
|
||||
g = buffer.getGraphics();
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, xsize, ysize);
|
||||
}
|
||||
else
|
||||
g = buffer.getGraphics();
|
||||
|
||||
if (row < ysize - 2 * DOTSIZE)
|
||||
row += DOTSIZE;
|
||||
else
|
||||
{
|
||||
g.copyArea(0, DOTSIZE, xsize, ysize - DOTSIZE, 0, -DOTSIZE);
|
||||
}
|
||||
freeway.paint(g, row, XDOTDIST, DOTSIZE);
|
||||
g.dispose();
|
||||
repaint();
|
||||
}
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
if (buffer != null)
|
||||
g.drawImage(buffer, 0, 0, null);
|
||||
}
|
||||
}
|
||||
|
||||
class Road
|
||||
{
|
||||
public static final int LENGTH = 400;
|
||||
public static final int MAXSPEED = 5;
|
||||
|
||||
private int[] speed;
|
||||
private Color[] colors;
|
||||
private int count;
|
||||
|
||||
public Road()
|
||||
{
|
||||
speed = new int[LENGTH];
|
||||
colors = new Color[LENGTH];
|
||||
for (int i = 0; i < LENGTH; i++) speed[i] = -1;
|
||||
}
|
||||
|
||||
public void update(double prob_slowdown, double prob_create)
|
||||
{
|
||||
int i = 0;
|
||||
while(i < LENGTH && speed[i] == -1)
|
||||
i++;
|
||||
while (i < LENGTH)
|
||||
{
|
||||
if (Math.random() <= prob_slowdown && speed[i] > 0)
|
||||
speed[i]--;
|
||||
else if (speed[i] < MAXSPEED)
|
||||
speed[i]++;
|
||||
int inext = i + 1;
|
||||
while(inext < LENGTH && speed[inext] == -1)
|
||||
inext++;
|
||||
if (inext < LENGTH)
|
||||
{
|
||||
if (speed[i] >= inext - i)
|
||||
speed[i] = inext - i - 1;
|
||||
}
|
||||
if (speed[i] > 0)
|
||||
{
|
||||
if (i + speed[i] < LENGTH)
|
||||
{
|
||||
int ni = i + speed[i];
|
||||
speed[ni] = speed[i];
|
||||
colors[ni] = colors[i];
|
||||
}
|
||||
speed[i] = -1;
|
||||
}
|
||||
i = inext;
|
||||
}
|
||||
if (Math.random() <= prob_create && speed[0] == -1)
|
||||
{
|
||||
speed[0] = (int)(5.99 * Math.random());
|
||||
colors[0] = ++count % 10 == 0 ? Color.red : Color.black;
|
||||
}
|
||||
}
|
||||
|
||||
public void paint(Graphics g, int row, int dotdist, int dotsize)
|
||||
{
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, row, LENGTH * dotsize, dotsize);
|
||||
for (int i = 0; i < LENGTH; i++)
|
||||
{
|
||||
if (speed[i] >= 0)
|
||||
{
|
||||
g.setColor(colors[i]);
|
||||
g.fillRect(i * dotdist, row, dotsize, dotsize);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
javac RoadApplet.java
|
||||
jar cvfm RoadApplet.jar RoadApplet.mf *.class
|
||||
rm *.class
|
||||
File renamed without changes.
@@ -0,0 +1,33 @@
|
||||
import java.math.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program uses big numbers to compute the odds of winning the grand prize in a lottery.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class BigIntegerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How many numbers do you need to draw? ");
|
||||
int k = in.nextInt();
|
||||
|
||||
System.out.print("What is the highest number you can draw? ");
|
||||
int n = in.nextInt();
|
||||
|
||||
/*
|
||||
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
|
||||
*/
|
||||
|
||||
BigInteger lotteryOdds = BigInteger.valueOf(1);
|
||||
|
||||
for (int i = 1; i <= k; i++)
|
||||
lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1)).divide(
|
||||
BigInteger.valueOf(i));
|
||||
|
||||
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,35 @@
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* @version 1.5 2015-05-08
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
|
||||
public class CalendarTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
LocalDate date = LocalDate.now();
|
||||
int month = date.getMonthValue();
|
||||
int today = date.getDayOfMonth();
|
||||
|
||||
date = date.minusDays(today - 1); // Set to start of month
|
||||
DayOfWeek weekday = date.getDayOfWeek();
|
||||
int value = weekday.getValue(); // 1 = Monday, ... 7 = Sunday
|
||||
|
||||
System.out.println("Mon Tue Wed Thu Fri Sat Sun");
|
||||
for (int i = 1; i < value; i++)
|
||||
System.out.print(" ");
|
||||
while (date.getMonthValue() == month)
|
||||
{
|
||||
System.out.printf("%3d", date.getDayOfMonth());
|
||||
if (date.getDayOfMonth() == today)
|
||||
System.out.print("*");
|
||||
else
|
||||
System.out.print(" ");
|
||||
date = date.plusDays(1);
|
||||
if (date.getDayOfWeek().getValue() == 1) System.out.println();
|
||||
}
|
||||
if (date.getDayOfWeek().getValue() != 1) System.out.println();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates object construction.
|
||||
* @version 1.01 2004-02-19
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ConstructorTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array with three Employee objects
|
||||
Employee[] staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Harry", 40000);
|
||||
staff[1] = new Employee(60000);
|
||||
staff[2] = new Employee();
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary="
|
||||
+ e.getSalary());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
private static int nextId;
|
||||
|
||||
private int id;
|
||||
private String name = ""; // instance field initialization
|
||||
private double salary;
|
||||
|
||||
// static initialization block
|
||||
static
|
||||
{
|
||||
Random generator = new Random();
|
||||
// set nextId to a random number between 0 and 9999
|
||||
nextId = generator.nextInt(10000);
|
||||
}
|
||||
|
||||
// object initialization block
|
||||
{
|
||||
id = nextId;
|
||||
nextId++;
|
||||
}
|
||||
|
||||
// three overloaded constructors
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
}
|
||||
|
||||
public Employee(double s)
|
||||
{
|
||||
// calls the Employee(String, double) constructor
|
||||
this("Employee #" + nextId, s);
|
||||
}
|
||||
|
||||
// the default constructor
|
||||
public Employee()
|
||||
{
|
||||
// name initialized to ""--see above
|
||||
// salary not explicitly set--initialized to 0
|
||||
// id initialized in initialization block
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public int getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* This program tests the Employee class.
|
||||
* @version 1.12 2015-05-08
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EmployeeTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array with three Employee objects
|
||||
Employee[] staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
|
||||
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
|
||||
|
||||
// raise everyone's salary by 5%
|
||||
for (Employee e : staff)
|
||||
e.raiseSalary(5);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
|
||||
+ e.getHireDay());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
private LocalDate hireDay;
|
||||
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
hireDay = LocalDate.of(year, month, day);
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public LocalDate getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import com.horstmann.corejava.*;
|
||||
// the Employee class is defined in that package
|
||||
|
||||
import static java.lang.System.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of packages.
|
||||
* @version 1.11 2004-02-19
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PackageTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// because of the import statement, we don't have to use
|
||||
// com.horstmann.corejava.Employee here
|
||||
Employee harry = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
|
||||
harry.raiseSalary(5);
|
||||
|
||||
// because of the static import statement, we don't have to use System.out here
|
||||
out.println("name=" + harry.getName() + ",salary=" + harry.getSalary());
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* This program demonstrates parameter passing in Java.
|
||||
* @version 1.00 2000-01-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ParamTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
/*
|
||||
* Test 1: Methods can't modify numeric parameters
|
||||
*/
|
||||
System.out.println("Testing tripleValue:");
|
||||
double percent = 10;
|
||||
System.out.println("Before: percent=" + percent);
|
||||
tripleValue(percent);
|
||||
System.out.println("After: percent=" + percent);
|
||||
|
||||
/*
|
||||
* Test 2: Methods can change the state of object parameters
|
||||
*/
|
||||
System.out.println("\nTesting tripleSalary:");
|
||||
Employee harry = new Employee("Harry", 50000);
|
||||
System.out.println("Before: salary=" + harry.getSalary());
|
||||
tripleSalary(harry);
|
||||
System.out.println("After: salary=" + harry.getSalary());
|
||||
|
||||
/*
|
||||
* Test 3: Methods can't attach new objects to object parameters
|
||||
*/
|
||||
System.out.println("\nTesting swap:");
|
||||
Employee a = new Employee("Alice", 70000);
|
||||
Employee b = new Employee("Bob", 60000);
|
||||
System.out.println("Before: a=" + a.getName());
|
||||
System.out.println("Before: b=" + b.getName());
|
||||
swap(a, b);
|
||||
System.out.println("After: a=" + a.getName());
|
||||
System.out.println("After: b=" + b.getName());
|
||||
}
|
||||
|
||||
public static void tripleValue(double x) // doesn't work
|
||||
{
|
||||
x = 3 * x;
|
||||
System.out.println("End of method: x=" + x);
|
||||
}
|
||||
|
||||
public static void tripleSalary(Employee x) // works
|
||||
{
|
||||
x.raiseSalary(200);
|
||||
System.out.println("End of method: salary=" + x.getSalary());
|
||||
}
|
||||
|
||||
public static void swap(Employee x, Employee y)
|
||||
{
|
||||
Employee temp = x;
|
||||
x = y;
|
||||
y = temp;
|
||||
System.out.println("End of method: x=" + x.getName());
|
||||
System.out.println("End of method: y=" + y.getName());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee // simplified Employee class
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* This program demonstrates static methods.
|
||||
* @version 1.01 2004-02-19
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class StaticTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array with three Employee objects
|
||||
Employee[] staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Tom", 40000);
|
||||
staff[1] = new Employee("Dick", 60000);
|
||||
staff[2] = new Employee("Harry", 65000);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
{
|
||||
e.setId();
|
||||
System.out.println("name=" + e.getName() + ",id=" + e.getId() + ",salary="
|
||||
+ e.getSalary());
|
||||
}
|
||||
|
||||
int n = Employee.getNextId(); // calls static method
|
||||
System.out.println("Next available id=" + n);
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
private static int nextId = 1;
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private int id;
|
||||
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
id = 0;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public int getId()
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId()
|
||||
{
|
||||
id = nextId; // set id to next available id
|
||||
nextId++;
|
||||
}
|
||||
|
||||
public static int getNextId()
|
||||
{
|
||||
return nextId; // returns static field
|
||||
}
|
||||
|
||||
public static void main(String[] args) // unit test
|
||||
{
|
||||
Employee e = new Employee("Harry", 50000);
|
||||
System.out.println(e.getName() + " " + e.getSalary());
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,22 @@
|
||||
package abstractClasses;
|
||||
|
||||
/**
|
||||
* This program demonstrates abstract classes.
|
||||
* @version 1.01 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PersonTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Person[] people = new Person[2];
|
||||
|
||||
// fill the people array with Student and Employee objects
|
||||
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
people[1] = new Student("Maria Morris", "computer science");
|
||||
|
||||
// print out names and descriptions of all Person objects
|
||||
for (Person p : people)
|
||||
System.out.println(p.getName() + ", " + p.getDescription());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package abstractClasses;
|
||||
|
||||
public class Student extends Person
|
||||
{
|
||||
private String major;
|
||||
|
||||
/**
|
||||
* @param nama the student's name
|
||||
* @param major the student's major
|
||||
*/
|
||||
public Student(String name, String major)
|
||||
{
|
||||
// pass n to superclass constructor
|
||||
super(name);
|
||||
this.major = major;
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return "a student majoring in " + major;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package arrayList;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the ArrayList class.
|
||||
* @version 1.11 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ArrayListTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// fill the staff array list with three Employee objects
|
||||
ArrayList<Employee> staff = new ArrayList<>();
|
||||
|
||||
staff.add(new Employee("Carl Cracker", 75000, 1987, 12, 15));
|
||||
staff.add(new Employee("Harry Hacker", 50000, 1989, 10, 1));
|
||||
staff.add(new Employee("Tony Tester", 40000, 1990, 3, 15));
|
||||
|
||||
// raise everyone's salary by 5%
|
||||
for (Employee e : staff)
|
||||
e.raiseSalary(5);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay="
|
||||
+ e.getHireDay());
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,58 @@
|
||||
package arrays;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of reflection for manipulating arrays.
|
||||
* @version 1.2 2012-05-04
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CopyOfTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int[] a = { 1, 2, 3 };
|
||||
a = (int[]) goodCopyOf(a, 10);
|
||||
System.out.println(Arrays.toString(a));
|
||||
|
||||
String[] b = { "Tom", "Dick", "Harry" };
|
||||
b = (String[]) goodCopyOf(b, 10);
|
||||
System.out.println(Arrays.toString(b));
|
||||
|
||||
System.out.println("The following call will generate an exception.");
|
||||
b = (String[]) badCopyOf(b, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method attempts to grow an array by allocating a new array and copying all elements.
|
||||
* @param a the array to grow
|
||||
* @param newLength the new length
|
||||
* @return a larger array that contains all elements of a. However, the returned array has
|
||||
* type Object[], not the same type as a
|
||||
*/
|
||||
public static Object[] badCopyOf(Object[] a, int newLength) // not useful
|
||||
{
|
||||
Object[] newArray = new Object[newLength];
|
||||
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
|
||||
return newArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method grows an array by allocating a new array of the same type and
|
||||
* copying all elements.
|
||||
* @param a the array to grow. This can be an object array or a primitive
|
||||
* type array
|
||||
* @return a larger array that contains all elements of a.
|
||||
*/
|
||||
public static Object goodCopyOf(Object a, int newLength)
|
||||
{
|
||||
Class cl = a.getClass();
|
||||
if (!cl.isArray()) return null;
|
||||
Class componentType = cl.getComponentType();
|
||||
int length = Array.getLength(a);
|
||||
Object newArray = Array.newInstance(componentType, newLength);
|
||||
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
|
||||
return newArray;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package enums;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates enumerated types.
|
||||
* @version 1.0 2004-05-24
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EnumTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
|
||||
String input = in.next().toUpperCase();
|
||||
Size size = Enum.valueOf(Size.class, input);
|
||||
System.out.println("size=" + size);
|
||||
System.out.println("abbreviation=" + size.getAbbreviation());
|
||||
if (size == Size.EXTRA_LARGE)
|
||||
System.out.println("Good job--you paid attention to the _.");
|
||||
}
|
||||
}
|
||||
|
||||
enum Size
|
||||
{
|
||||
SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
|
||||
|
||||
private Size(String abbreviation) { this.abbreviation = abbreviation; }
|
||||
public String getAbbreviation() { return abbreviation; }
|
||||
|
||||
private String abbreviation;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package equals;
|
||||
|
||||
import java.time.*;
|
||||
import java.util.Objects;
|
||||
|
||||
public class Employee
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
private LocalDate hireDay;
|
||||
|
||||
public Employee(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
this.name = name;
|
||||
this.salary = salary;
|
||||
hireDay = LocalDate.of(year, month, day);
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public LocalDate getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
public boolean equals(Object otherObject)
|
||||
{
|
||||
// a quick test to see if the objects are identical
|
||||
if (this == otherObject) return true;
|
||||
|
||||
// must return false if the explicit parameter is null
|
||||
if (otherObject == null) return false;
|
||||
|
||||
// if the classes don't match, they can't be equal
|
||||
if (getClass() != otherObject.getClass()) return false;
|
||||
|
||||
// now we know otherObject is a non-null Employee
|
||||
Employee other = (Employee) otherObject;
|
||||
|
||||
// test whether the fields have identical values
|
||||
return Objects.equals(name, other.name) && salary == other.salary && Objects.equals(hireDay, other.hireDay);
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return Objects.hash(name, salary, hireDay);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
|
||||
+ "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package equals;
|
||||
|
||||
/**
|
||||
* This program demonstrates the equals method.
|
||||
* @version 1.12 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EqualsTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15);
|
||||
Employee alice2 = alice1;
|
||||
Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15);
|
||||
Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1);
|
||||
|
||||
System.out.println("alice1 == alice2: " + (alice1 == alice2));
|
||||
|
||||
System.out.println("alice1 == alice3: " + (alice1 == alice3));
|
||||
|
||||
System.out.println("alice1.equals(alice3): " + alice1.equals(alice3));
|
||||
|
||||
System.out.println("alice1.equals(bob): " + alice1.equals(bob));
|
||||
|
||||
System.out.println("bob.toString(): " + bob);
|
||||
|
||||
Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15);
|
||||
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
|
||||
boss.setBonus(5000);
|
||||
System.out.println("boss.toString(): " + boss);
|
||||
System.out.println("carl.equals(boss): " + carl.equals(boss));
|
||||
System.out.println("alice1.hashCode(): " + alice1.hashCode());
|
||||
System.out.println("alice3.hashCode(): " + alice3.hashCode());
|
||||
System.out.println("bob.hashCode(): " + bob.hashCode());
|
||||
System.out.println("carl.hashCode(): " + carl.hashCode());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package equals;
|
||||
|
||||
public class Manager extends Employee
|
||||
{
|
||||
private double bonus;
|
||||
|
||||
public Manager(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name, salary, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double bonus)
|
||||
{
|
||||
this.bonus = bonus;
|
||||
}
|
||||
|
||||
public boolean equals(Object otherObject)
|
||||
{
|
||||
if (!super.equals(otherObject)) return false;
|
||||
Manager other = (Manager) otherObject;
|
||||
// super.equals checked that this and other belong to the same class
|
||||
return bonus == other.bonus;
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return java.util.Objects.hash(super.hashCode(), bonus);
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return super.toString() + "[bonus=" + bonus + "]";
|
||||
}
|
||||
}
|
||||
|
||||
File renamed without changes.
@@ -0,0 +1,30 @@
|
||||
package inheritance;
|
||||
|
||||
public class Manager extends Employee
|
||||
{
|
||||
private double bonus;
|
||||
|
||||
/**
|
||||
* @param name the employee's name
|
||||
* @param salary the salary
|
||||
* @param year the hire year
|
||||
* @param month the hire month
|
||||
* @param day the hire day
|
||||
*/
|
||||
public Manager(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name, salary, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double b)
|
||||
{
|
||||
bonus = b;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package inheritance;
|
||||
|
||||
/**
|
||||
* This program demonstrates inheritance.
|
||||
* @version 1.21 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ManagerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// construct a Manager object
|
||||
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
|
||||
boss.setBonus(5000);
|
||||
|
||||
Employee[] staff = new Employee[3];
|
||||
|
||||
// fill the staff array with Manager and Employee objects
|
||||
|
||||
staff[0] = boss;
|
||||
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
|
||||
staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package methods;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
|
||||
/**
|
||||
* This program shows how to invoke methods through reflection.
|
||||
* @version 1.2 2012-05-04
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MethodTableTest
|
||||
{
|
||||
public static void main(String[] args) throws Exception
|
||||
{
|
||||
// get method pointers to the square and sqrt methods
|
||||
Method square = MethodTableTest.class.getMethod("square", double.class);
|
||||
Method sqrt = Math.class.getMethod("sqrt", double.class);
|
||||
|
||||
// print tables of x- and y-values
|
||||
|
||||
printTable(1, 10, 10, square);
|
||||
printTable(1, 10, 10, sqrt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the square of a number
|
||||
* @param x a number
|
||||
* @return x squared
|
||||
*/
|
||||
public static double square(double x)
|
||||
{
|
||||
return x * x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints a table with x- and y-values for a method
|
||||
* @param from the lower bound for the x-values
|
||||
* @param to the upper bound for the x-values
|
||||
* @param n the number of rows in the table
|
||||
* @param f a method with a double parameter and double return value
|
||||
*/
|
||||
public static void printTable(double from, double to, int n, Method f)
|
||||
{
|
||||
// print out the method as table header
|
||||
System.out.println(f);
|
||||
|
||||
double dx = (to - from) / (n - 1);
|
||||
|
||||
for (double x = from; x <= to; x += dx)
|
||||
{
|
||||
try
|
||||
{
|
||||
double y = (Double) f.invoke(null, x);
|
||||
System.out.printf("%10.4f | %10.4f%n", x, y);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package objectAnalyzer;
|
||||
|
||||
import java.lang.reflect.AccessibleObject;
|
||||
import java.lang.reflect.Array;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class ObjectAnalyzer
|
||||
{
|
||||
private ArrayList<Object> visited = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Converts an object to a string representation that lists all fields.
|
||||
* @param obj an object
|
||||
* @return a string with the object's class name and all field names and
|
||||
* values
|
||||
*/
|
||||
public String toString(Object obj)
|
||||
{
|
||||
if (obj == null) return "null";
|
||||
if (visited.contains(obj)) return "...";
|
||||
visited.add(obj);
|
||||
Class cl = obj.getClass();
|
||||
if (cl == String.class) return (String) obj;
|
||||
if (cl.isArray())
|
||||
{
|
||||
String r = cl.getComponentType() + "[]{";
|
||||
for (int i = 0; i < Array.getLength(obj); i++)
|
||||
{
|
||||
if (i > 0) r += ",";
|
||||
Object val = Array.get(obj, i);
|
||||
if (cl.getComponentType().isPrimitive()) r += val;
|
||||
else r += toString(val);
|
||||
}
|
||||
return r + "}";
|
||||
}
|
||||
|
||||
String r = cl.getName();
|
||||
// inspect the fields of this class and all superclasses
|
||||
do
|
||||
{
|
||||
r += "[";
|
||||
Field[] fields = cl.getDeclaredFields();
|
||||
AccessibleObject.setAccessible(fields, true);
|
||||
// get the names and values of all fields
|
||||
for (Field f : fields)
|
||||
{
|
||||
if (!Modifier.isStatic(f.getModifiers()))
|
||||
{
|
||||
if (!r.endsWith("[")) r += ",";
|
||||
r += f.getName() + "=";
|
||||
try
|
||||
{
|
||||
Class t = f.getType();
|
||||
Object val = f.get(obj);
|
||||
if (t.isPrimitive()) r += val;
|
||||
else r += toString(val);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
r += "]";
|
||||
cl = cl.getSuperclass();
|
||||
}
|
||||
while (cl != null);
|
||||
|
||||
return r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package objectAnalyzer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* This program uses reflection to spy on objects.
|
||||
* @version 1.12 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ObjectAnalyzerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
ArrayList<Integer> squares = new ArrayList<>();
|
||||
for (int i = 1; i <= 5; i++)
|
||||
squares.add(i * i);
|
||||
System.out.println(new ObjectAnalyzer().toString(squares));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package reflection;
|
||||
|
||||
import java.util.*;
|
||||
import java.lang.reflect.*;
|
||||
|
||||
/**
|
||||
* This program uses reflection to print all features of a class.
|
||||
* @version 1.1 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ReflectionTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// read class name from command line args or user input
|
||||
String name;
|
||||
if (args.length > 0) name = args[0];
|
||||
else
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Enter class name (e.g. java.util.Date): ");
|
||||
name = in.next();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// print class name and superclass name (if != Object)
|
||||
Class cl = Class.forName(name);
|
||||
Class supercl = cl.getSuperclass();
|
||||
String modifiers = Modifier.toString(cl.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.print("class " + name);
|
||||
if (supercl != null && supercl != Object.class) System.out.print(" extends "
|
||||
+ supercl.getName());
|
||||
|
||||
System.out.print("\n{\n");
|
||||
printConstructors(cl);
|
||||
System.out.println();
|
||||
printMethods(cl);
|
||||
System.out.println();
|
||||
printFields(cl);
|
||||
System.out.println("}");
|
||||
}
|
||||
catch (ClassNotFoundException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints all constructors of a class
|
||||
* @param cl a class
|
||||
*/
|
||||
public static void printConstructors(Class cl)
|
||||
{
|
||||
Constructor[] constructors = cl.getDeclaredConstructors();
|
||||
|
||||
for (Constructor c : constructors)
|
||||
{
|
||||
String name = c.getName();
|
||||
System.out.print(" ");
|
||||
String modifiers = Modifier.toString(c.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.print(name + "(");
|
||||
|
||||
// print parameter types
|
||||
Class[] paramTypes = c.getParameterTypes();
|
||||
for (int j = 0; j < paramTypes.length; j++)
|
||||
{
|
||||
if (j > 0) System.out.print(", ");
|
||||
System.out.print(paramTypes[j].getName());
|
||||
}
|
||||
System.out.println(");");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints all methods of a class
|
||||
* @param cl a class
|
||||
*/
|
||||
public static void printMethods(Class cl)
|
||||
{
|
||||
Method[] methods = cl.getDeclaredMethods();
|
||||
|
||||
for (Method m : methods)
|
||||
{
|
||||
Class retType = m.getReturnType();
|
||||
String name = m.getName();
|
||||
|
||||
System.out.print(" ");
|
||||
// print modifiers, return type and method name
|
||||
String modifiers = Modifier.toString(m.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.print(retType.getName() + " " + name + "(");
|
||||
|
||||
// print parameter types
|
||||
Class[] paramTypes = m.getParameterTypes();
|
||||
for (int j = 0; j < paramTypes.length; j++)
|
||||
{
|
||||
if (j > 0) System.out.print(", ");
|
||||
System.out.print(paramTypes[j].getName());
|
||||
}
|
||||
System.out.println(");");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints all fields of a class
|
||||
* @param cl a class
|
||||
*/
|
||||
public static void printFields(Class cl)
|
||||
{
|
||||
Field[] fields = cl.getDeclaredFields();
|
||||
|
||||
for (Field f : fields)
|
||||
{
|
||||
Class type = f.getType();
|
||||
String name = f.getName();
|
||||
System.out.print(" ");
|
||||
String modifiers = Modifier.toString(f.getModifiers());
|
||||
if (modifiers.length() > 0) System.out.print(modifiers + " ");
|
||||
System.out.println(type.getName() + " " + name + ";");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package anonymousInnerClass;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.Timer;
|
||||
|
||||
/**
|
||||
* This program demonstrates anonymous inner classes.
|
||||
* @version 1.11 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class AnonymousInnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
TalkingClock clock = new TalkingClock();
|
||||
clock.start(1000, true);
|
||||
|
||||
// keep program running until user selects "Ok"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A clock that prints the time in regular intervals.
|
||||
*/
|
||||
class TalkingClock
|
||||
{
|
||||
/**
|
||||
* Starts the clock.
|
||||
* @param interval the interval between messages (in milliseconds)
|
||||
* @param beep true if the clock should beep
|
||||
*/
|
||||
public void start(int interval, boolean beep)
|
||||
{
|
||||
ActionListener listener = new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is " + new Date());
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
};
|
||||
Timer t = new Timer(interval, listener);
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package clone;
|
||||
|
||||
/**
|
||||
* This program demonstrates cloning.
|
||||
* @version 1.10 2002-07-01
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CloneTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
try
|
||||
{
|
||||
Employee original = new Employee("John Q. Public", 50000);
|
||||
original.setHireDay(2000, 1, 1);
|
||||
Employee copy = original.clone();
|
||||
copy.raiseSalary(10);
|
||||
copy.setHireDay(2002, 12, 31);
|
||||
System.out.println("original=" + original);
|
||||
System.out.println("copy=" + copy);
|
||||
}
|
||||
catch (CloneNotSupportedException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package clone;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
public class Employee implements Cloneable
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
|
||||
public Employee(String name, double salary)
|
||||
{
|
||||
this.name = name;
|
||||
this.salary = salary;
|
||||
hireDay = new Date();
|
||||
}
|
||||
|
||||
public Employee clone() throws CloneNotSupportedException
|
||||
{
|
||||
// call Object.clone()
|
||||
Employee cloned = (Employee) super.clone();
|
||||
|
||||
// clone mutable fields
|
||||
cloned.hireDay = (Date) hireDay.clone();
|
||||
|
||||
return cloned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the hire day to a given date.
|
||||
* @param year the year of the hire day
|
||||
* @param month the month of the hire day
|
||||
* @param day the day of the hire day
|
||||
*/
|
||||
public void setHireDay(int year, int month, int day)
|
||||
{
|
||||
Date newHireDay = new GregorianCalendar(year, month - 1, day).getTime();
|
||||
|
||||
// Example of instance field mutation
|
||||
hireDay.setTime(newHireDay.getTime());
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package innerClass;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.Timer;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of inner classes.
|
||||
* @version 1.11 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class InnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
TalkingClock clock = new TalkingClock(1000, true);
|
||||
clock.start();
|
||||
|
||||
// keep program running until user selects "Ok"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A clock that prints the time in regular intervals.
|
||||
*/
|
||||
class TalkingClock
|
||||
{
|
||||
private int interval;
|
||||
private boolean beep;
|
||||
|
||||
/**
|
||||
* Constructs a talking clock
|
||||
* @param interval the interval between messages (in milliseconds)
|
||||
* @param beep true if the clock should beep
|
||||
*/
|
||||
public TalkingClock(int interval, boolean beep)
|
||||
{
|
||||
this.interval = interval;
|
||||
this.beep = beep;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the clock.
|
||||
*/
|
||||
public void start()
|
||||
{
|
||||
ActionListener listener = new TimePrinter();
|
||||
Timer t = new Timer(interval, listener);
|
||||
t.start();
|
||||
}
|
||||
|
||||
public class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is " + new Date());
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package interfaces;
|
||||
|
||||
public class Employee implements Comparable<Employee>
|
||||
{
|
||||
private String name;
|
||||
private double salary;
|
||||
|
||||
public Employee(String name, double salary)
|
||||
{
|
||||
this.name = name;
|
||||
this.salary = salary;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares employees by salary
|
||||
* @param other another Employee object
|
||||
* @return a negative value if this employee has a lower salary than
|
||||
* otherObject, 0 if the salaries are the same, a positive value otherwise
|
||||
*/
|
||||
public int compareTo(Employee other)
|
||||
{
|
||||
return Double.compare(salary, other.salary);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package interfaces;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of the Comparable interface.
|
||||
* @version 1.30 2004-02-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class EmployeeSortTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Employee[] staff = new Employee[3];
|
||||
|
||||
staff[0] = new Employee("Harry Hacker", 35000);
|
||||
staff[1] = new Employee("Carl Cracker", 75000);
|
||||
staff[2] = new Employee("Tony Tester", 38000);
|
||||
|
||||
Arrays.sort(staff);
|
||||
|
||||
// print out information about all Employee objects
|
||||
for (Employee e : staff)
|
||||
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package lambda;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.swing.Timer;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of lambda expressions.
|
||||
* @version 1.0 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LambdaTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
|
||||
"Jupiter", "Saturn", "Uranus", "Neptune" };
|
||||
System.out.println(Arrays.toString(planets));
|
||||
System.out.println("Sorted in dictionary order:");
|
||||
Arrays.sort(planets);
|
||||
System.out.println(Arrays.toString(planets));
|
||||
System.out.println("Sorted by length:");
|
||||
Arrays.sort(planets, (first, second) -> first.length() - second.length());
|
||||
System.out.println(Arrays.toString(planets));
|
||||
|
||||
Timer t = new Timer(1000, event ->
|
||||
System.out.println("The time is " + new Date()));
|
||||
t.start();
|
||||
|
||||
// keep program running until user selects "Ok"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package localInnerClass;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.Timer;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of local inner classes.
|
||||
* @version 1.01 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LocalInnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
TalkingClock clock = new TalkingClock();
|
||||
clock.start(1000, true);
|
||||
|
||||
// keep program running until user selects "Ok"
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A clock that prints the time in regular intervals.
|
||||
*/
|
||||
class TalkingClock
|
||||
{
|
||||
/**
|
||||
* Starts the clock.
|
||||
* @param interval the interval between messages (in milliseconds)
|
||||
* @param beep true if the clock should beep
|
||||
*/
|
||||
public void start(int interval, boolean beep)
|
||||
{
|
||||
class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is " + new Date());
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
ActionListener listener = new TimePrinter();
|
||||
Timer t = new Timer(interval, listener);
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package proxy;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of proxies.
|
||||
* @version 1.00 2000-04-13
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ProxyTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Object[] elements = new Object[1000];
|
||||
|
||||
// fill elements with proxies for the integers 1 ... 1000
|
||||
for (int i = 0; i < elements.length; i++)
|
||||
{
|
||||
Integer value = i + 1;
|
||||
InvocationHandler handler = new TraceHandler(value);
|
||||
Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class } , handler);
|
||||
elements[i] = proxy;
|
||||
}
|
||||
|
||||
// construct a random integer
|
||||
Integer key = new Random().nextInt(elements.length) + 1;
|
||||
|
||||
// search for the key
|
||||
int result = Arrays.binarySearch(elements, key);
|
||||
|
||||
// print match if found
|
||||
if (result >= 0) System.out.println(elements[result]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An invocation handler that prints out the method name and parameters, then
|
||||
* invokes the original method
|
||||
*/
|
||||
class TraceHandler implements InvocationHandler
|
||||
{
|
||||
private Object target;
|
||||
|
||||
/**
|
||||
* Constructs a TraceHandler
|
||||
* @param t the implicit parameter of the method call
|
||||
*/
|
||||
public TraceHandler(Object t)
|
||||
{
|
||||
target = t;
|
||||
}
|
||||
|
||||
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
|
||||
{
|
||||
// print implicit argument
|
||||
System.out.print(target);
|
||||
// print method name
|
||||
System.out.print("." + m.getName() + "(");
|
||||
// print explicit arguments
|
||||
if (args != null)
|
||||
{
|
||||
for (int i = 0; i < args.length; i++)
|
||||
{
|
||||
System.out.print(args[i]);
|
||||
if (i < args.length - 1) System.out.print(", ");
|
||||
}
|
||||
}
|
||||
System.out.println(")");
|
||||
|
||||
// invoke actual method
|
||||
return m.invoke(target, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package staticInnerClass;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of static inner classes.
|
||||
* @version 1.02 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class StaticInnerClassTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
double[] d = new double[20];
|
||||
for (int i = 0; i < d.length; i++)
|
||||
d[i] = 100 * Math.random();
|
||||
ArrayAlg.Pair p = ArrayAlg.minmax(d);
|
||||
System.out.println("min = " + p.getFirst());
|
||||
System.out.println("max = " + p.getSecond());
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
/**
|
||||
* A pair of floating-point numbers
|
||||
*/
|
||||
public static class Pair
|
||||
{
|
||||
private double first;
|
||||
private double second;
|
||||
|
||||
/**
|
||||
* Constructs a pair from two floating-point numbers
|
||||
* @param f the first number
|
||||
* @param s the second number
|
||||
*/
|
||||
public Pair(double f, double s)
|
||||
{
|
||||
first = f;
|
||||
second = s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first number of the pair
|
||||
* @return the first number
|
||||
*/
|
||||
public double getFirst()
|
||||
{
|
||||
return first;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the second number of the pair
|
||||
* @return the second number
|
||||
*/
|
||||
public double getSecond()
|
||||
{
|
||||
return second;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Computes both the minimum and the maximum of an array
|
||||
* @param values an array of floating-point numbers
|
||||
* @return a pair whose first element is the minimum and whose second element
|
||||
* is the maximum
|
||||
*/
|
||||
public static Pair minmax(double[] values)
|
||||
{
|
||||
double min = Double.POSITIVE_INFINITY;
|
||||
double max = Double.NEGATIVE_INFINITY;
|
||||
for (double v : values)
|
||||
{
|
||||
if (min > v) min = v;
|
||||
if (max < v) max = v;
|
||||
}
|
||||
return new Pair(min, max);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package timer;
|
||||
|
||||
/**
|
||||
@version 1.01 2015-05-12
|
||||
@author Cay Horstmann
|
||||
*/
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.Timer;
|
||||
// to resolve conflict with java.util.Timer
|
||||
|
||||
public class TimerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
ActionListener listener = new TimePrinter();
|
||||
|
||||
// construct a timer that calls the listener
|
||||
// once every 10 seconds
|
||||
Timer t = new Timer(10000, listener);
|
||||
t.start();
|
||||
|
||||
JOptionPane.showMessageDialog(null, "Quit program?");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println("At the tone, the time is " + new Date());
|
||||
Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package except;
|
||||
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.*;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.34 2015-08-20
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ExceptTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
JFrame frame = new ExceptTestFrame();
|
||||
frame.setTitle("ExceptTest");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a panel for testing various exceptions
|
||||
*/
|
||||
class ExceptTestFrame extends JFrame
|
||||
{
|
||||
public ExceptTestFrame()
|
||||
{
|
||||
ExceptTestPanel panel = new ExceptTestPanel();
|
||||
add(panel);
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel with radio buttons for running code snippets and studying their exception behavior
|
||||
*/
|
||||
class ExceptTestPanel extends Box
|
||||
{
|
||||
private ButtonGroup group;
|
||||
private JTextField textField;
|
||||
private double[] a = new double[10];
|
||||
|
||||
public ExceptTestPanel()
|
||||
{
|
||||
super(BoxLayout.Y_AXIS);
|
||||
group = new ButtonGroup();
|
||||
|
||||
// add radio buttons for code snippets
|
||||
|
||||
addRadioButton("Integer divide by zero", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
a[1] = 1 / (a.length - a.length);
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("Floating point divide by zero", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
a[1] = a[2] / (a[3] - a[3]);
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("Array bounds", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
a[1] = a[10];
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("Bad cast", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
a = (double[]) event.getSource();
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("Null pointer", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println(textField.getAction().toString());
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("sqrt(-1)", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
a[1] = Math.sqrt(-1);
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("Overflow", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
a[1] = 1000 * 1000 * 1000 * 1000;
|
||||
int n = (int) a[1];
|
||||
System.out.println(n);
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("No such file", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
try
|
||||
{
|
||||
System.out.println(
|
||||
new Scanner(Paths.get("woozle.txt"), "UTF-8").next());
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
textField.setText(e.toString());
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
addRadioButton("Throw unknown", new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
throw new UnknownError();
|
||||
}
|
||||
});
|
||||
|
||||
// add the text field for exception display
|
||||
textField = new JTextField(30);
|
||||
add(textField);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a radio button with a given listener to the panel. Traps any exceptions in the
|
||||
* actionPerformed method of the listener.
|
||||
* @param s the label of the radio button
|
||||
* @param listener the action listener for the radio button
|
||||
*/
|
||||
private void addRadioButton(String s, ActionListener listener)
|
||||
{
|
||||
JRadioButton button = new JRadioButton(s, false)
|
||||
{
|
||||
// the button calls this method to fire an
|
||||
// action event. We override it to trap exceptions
|
||||
protected void fireActionPerformed(ActionEvent event)
|
||||
{
|
||||
try
|
||||
{
|
||||
textField.setText("No exception");
|
||||
super.fireActionPerformed(event);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
textField.setText(e.toString());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
button.addActionListener(listener);
|
||||
add(button);
|
||||
group.add(button);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
Manifest-Version: 1.0
|
||||
X-COMMENT: Main-Class will be added automatically by build
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package exceptional;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @version 1.11 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ExceptionalTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int i = 0;
|
||||
int ntry = 10000000;
|
||||
Stack<String> s = new Stack<>();
|
||||
long s1;
|
||||
long s2;
|
||||
|
||||
// test a stack for emptiness ntry times
|
||||
System.out.println("Testing for empty stack");
|
||||
s1 = new Date().getTime();
|
||||
for (i = 0; i <= ntry; i++)
|
||||
if (!s.empty()) s.pop();
|
||||
s2 = new Date().getTime();
|
||||
System.out.println((s2 - s1) + " milliseconds");
|
||||
|
||||
// pop an empty stack ntry times and catch the resulting exception
|
||||
System.out.println("Catching EmptyStackException");
|
||||
s1 = new Date().getTime();
|
||||
for (i = 0; i <= ntry; i++)
|
||||
{
|
||||
try
|
||||
{
|
||||
s.pop();
|
||||
}
|
||||
catch (EmptyStackException e)
|
||||
{
|
||||
}
|
||||
}
|
||||
s2 = new Date().getTime();
|
||||
System.out.println((s2 - s1) + " milliseconds");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package logging;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.io.*;
|
||||
import java.util.logging.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A modification of the image viewer program that logs various events.
|
||||
* @version 1.03 2015-08-20
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LoggingImageViewer
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
if (System.getProperty("java.util.logging.config.class") == null
|
||||
&& System.getProperty("java.util.logging.config.file") == null)
|
||||
{
|
||||
try
|
||||
{
|
||||
Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);
|
||||
final int LOG_ROTATION_COUNT = 10;
|
||||
Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT);
|
||||
Logger.getLogger("com.horstmann.corejava").addHandler(handler);
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE,
|
||||
"Can't create log file handler", e);
|
||||
}
|
||||
}
|
||||
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
Handler windowHandler = new WindowHandler();
|
||||
windowHandler.setLevel(Level.ALL);
|
||||
Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler);
|
||||
|
||||
JFrame frame = new ImageViewerFrame();
|
||||
frame.setTitle("LoggingImageViewer");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
|
||||
Logger.getLogger("com.horstmann.corejava").fine("Showing frame");
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame that shows the image.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
private JLabel label;
|
||||
private static Logger logger = Logger.getLogger("com.horstmann.corejava");
|
||||
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
logger.entering("ImageViewerFrame", "<init>");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// set up menu bar
|
||||
JMenuBar menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
JMenu menu = new JMenu("File");
|
||||
menuBar.add(menu);
|
||||
|
||||
JMenuItem openItem = new JMenuItem("Open");
|
||||
menu.add(openItem);
|
||||
openItem.addActionListener(new FileOpenListener());
|
||||
|
||||
JMenuItem exitItem = new JMenuItem("Exit");
|
||||
menu.add(exitItem);
|
||||
exitItem.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
logger.fine("Exiting.");
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
// use a label to display the images
|
||||
label = new JLabel();
|
||||
add(label);
|
||||
logger.exiting("ImageViewerFrame", "<init>");
|
||||
}
|
||||
|
||||
private class FileOpenListener implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event);
|
||||
|
||||
// set up file chooser
|
||||
JFileChooser chooser = new JFileChooser();
|
||||
chooser.setCurrentDirectory(new File("."));
|
||||
|
||||
// accept all files ending with .gif
|
||||
chooser.setFileFilter(new javax.swing.filechooser.FileFilter()
|
||||
{
|
||||
public boolean accept(File f)
|
||||
{
|
||||
return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory();
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return "GIF Images";
|
||||
}
|
||||
});
|
||||
|
||||
// show file chooser dialog
|
||||
int r = chooser.showOpenDialog(ImageViewerFrame.this);
|
||||
|
||||
// if image file accepted, set it as icon of the label
|
||||
if (r == JFileChooser.APPROVE_OPTION)
|
||||
{
|
||||
String name = chooser.getSelectedFile().getPath();
|
||||
logger.log(Level.FINE, "Reading file {0}", name);
|
||||
label.setIcon(new ImageIcon(name));
|
||||
}
|
||||
else logger.fine("File open dialog canceled.");
|
||||
logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A handler for displaying log records in a window.
|
||||
*/
|
||||
class WindowHandler extends StreamHandler
|
||||
{
|
||||
private JFrame frame;
|
||||
|
||||
public WindowHandler()
|
||||
{
|
||||
frame = new JFrame();
|
||||
final JTextArea output = new JTextArea();
|
||||
output.setEditable(false);
|
||||
frame.setSize(200, 200);
|
||||
frame.add(new JScrollPane(output));
|
||||
frame.setFocusableWindowState(false);
|
||||
frame.setVisible(true);
|
||||
setOutputStream(new OutputStream()
|
||||
{
|
||||
public void write(int b)
|
||||
{
|
||||
} // not called
|
||||
|
||||
public void write(byte[] b, int off, int len)
|
||||
{
|
||||
output.append(new String(b, off, len));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void publish(LogRecord record)
|
||||
{
|
||||
if (!frame.isVisible()) return;
|
||||
super.publish(record);
|
||||
flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package stackTrace;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A program that displays a trace feature of a recursive method call.
|
||||
* @version 1.01 2004-05-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class StackTraceTest
|
||||
{
|
||||
/**
|
||||
* Computes the factorial of a number
|
||||
* @param n a non-negative integer
|
||||
* @return n! = 1 * 2 * . . . * n
|
||||
*/
|
||||
public static int factorial(int n)
|
||||
{
|
||||
System.out.println("factorial(" + n + "):");
|
||||
Throwable t = new Throwable();
|
||||
StackTraceElement[] frames = t.getStackTrace();
|
||||
for (StackTraceElement f : frames)
|
||||
System.out.println(f);
|
||||
int r;
|
||||
if (n <= 1) r = 1;
|
||||
else r = n * factorial(n - 1);
|
||||
System.out.println("return " + r);
|
||||
return r;
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.print("Enter n: ");
|
||||
int n = in.nextInt();
|
||||
factorial(n);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,35 @@
|
||||
package genericAlgorithms;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* @version 1.00 2004-05-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Pair<T>
|
||||
{
|
||||
private T first;
|
||||
private T second;
|
||||
|
||||
public Pair() { first = null; second = null; }
|
||||
public Pair(T first, T second) { this.first = first; this.second = second; }
|
||||
|
||||
public T getFirst() { return first; }
|
||||
public T getSecond() { return second; }
|
||||
|
||||
public void setFirst(T newValue) { first = newValue; }
|
||||
public void setSecond(T newValue) { second = newValue; }
|
||||
|
||||
public String toString() { return "(" + first + ", " + second + ")"; }
|
||||
|
||||
public static <T> Pair<T> makePair(Supplier<T> constr)
|
||||
{
|
||||
return new Pair<>(constr.get(), constr.get());
|
||||
}
|
||||
|
||||
public static <T> Pair<T> makePair(Class<T> cl)
|
||||
{
|
||||
try { return new Pair<>(cl.newInstance(), cl.newInstance()); }
|
||||
catch (Exception ex) { return null; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package genericReflection;
|
||||
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @version 1.10 2007-05-15
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class GenericReflectionTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// read class name from command line args or user input
|
||||
String name;
|
||||
if (args.length > 0) name = args[0];
|
||||
else
|
||||
{
|
||||
try (Scanner in = new Scanner(System.in))
|
||||
{
|
||||
System.out.println("Enter class name (e.g. java.util.Collections): ");
|
||||
name = in.next();
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// print generic info for class and public methods
|
||||
Class<?> cl = Class.forName(name);
|
||||
printClass(cl);
|
||||
for (Method m : cl.getDeclaredMethods())
|
||||
printMethod(m);
|
||||
}
|
||||
catch (ClassNotFoundException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void printClass(Class<?> cl)
|
||||
{
|
||||
System.out.print(cl);
|
||||
printTypes(cl.getTypeParameters(), "<", ", ", ">", true);
|
||||
Type sc = cl.getGenericSuperclass();
|
||||
if (sc != null)
|
||||
{
|
||||
System.out.print(" extends ");
|
||||
printType(sc, false);
|
||||
}
|
||||
printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false);
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static void printMethod(Method m)
|
||||
{
|
||||
String name = m.getName();
|
||||
System.out.print(Modifier.toString(m.getModifiers()));
|
||||
System.out.print(" ");
|
||||
printTypes(m.getTypeParameters(), "<", ", ", "> ", true);
|
||||
|
||||
printType(m.getGenericReturnType(), false);
|
||||
System.out.print(" ");
|
||||
System.out.print(name);
|
||||
System.out.print("(");
|
||||
printTypes(m.getGenericParameterTypes(), "", ", ", "", false);
|
||||
System.out.println(")");
|
||||
}
|
||||
|
||||
public static void printTypes(Type[] types, String pre, String sep, String suf,
|
||||
boolean isDefinition)
|
||||
{
|
||||
if (pre.equals(" extends ") && Arrays.equals(types, new Type[] { Object.class })) return;
|
||||
if (types.length > 0) System.out.print(pre);
|
||||
for (int i = 0; i < types.length; i++)
|
||||
{
|
||||
if (i > 0) System.out.print(sep);
|
||||
printType(types[i], isDefinition);
|
||||
}
|
||||
if (types.length > 0) System.out.print(suf);
|
||||
}
|
||||
|
||||
public static void printType(Type type, boolean isDefinition)
|
||||
{
|
||||
if (type instanceof Class)
|
||||
{
|
||||
Class<?> t = (Class<?>) type;
|
||||
System.out.print(t.getName());
|
||||
}
|
||||
else if (type instanceof TypeVariable)
|
||||
{
|
||||
TypeVariable<?> t = (TypeVariable<?>) type;
|
||||
System.out.print(t.getName());
|
||||
if (isDefinition)
|
||||
printTypes(t.getBounds(), " extends ", " & ", "", false);
|
||||
}
|
||||
else if (type instanceof WildcardType)
|
||||
{
|
||||
WildcardType t = (WildcardType) type;
|
||||
System.out.print("?");
|
||||
printTypes(t.getUpperBounds(), " extends ", " & ", "", false);
|
||||
printTypes(t.getLowerBounds(), " super ", " & ", "", false);
|
||||
}
|
||||
else if (type instanceof ParameterizedType)
|
||||
{
|
||||
ParameterizedType t = (ParameterizedType) type;
|
||||
Type owner = t.getOwnerType();
|
||||
if (owner != null)
|
||||
{
|
||||
printType(owner, false);
|
||||
System.out.print(".");
|
||||
}
|
||||
printType(t.getRawType(), false);
|
||||
printTypes(t.getActualTypeArguments(), "<", ", ", ">", false);
|
||||
}
|
||||
else if (type instanceof GenericArrayType)
|
||||
{
|
||||
GenericArrayType t = (GenericArrayType) type;
|
||||
System.out.print("");
|
||||
printType(t.getGenericComponentType(), isDefinition);
|
||||
System.out.print("[]");
|
||||
}
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,37 @@
|
||||
package pair1;
|
||||
|
||||
/**
|
||||
* @version 1.01 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PairTest1
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String[] words = { "Mary", "had", "a", "little", "lamb" };
|
||||
Pair<String> mm = ArrayAlg.minmax(words);
|
||||
System.out.println("min = " + mm.getFirst());
|
||||
System.out.println("max = " + mm.getSecond());
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
/**
|
||||
* Gets the minimum and maximum of an array of strings.
|
||||
* @param a an array of strings
|
||||
* @return a pair with the min and max value, or null if a is null or empty
|
||||
*/
|
||||
public static Pair<String> minmax(String[] a)
|
||||
{
|
||||
if (a == null || a.length == 0) return null;
|
||||
String min = a[0];
|
||||
String max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
return new Pair<>(min, max);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,46 @@
|
||||
package pair2;
|
||||
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* @version 1.02 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PairTest2
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
LocalDate[] birthdays =
|
||||
{
|
||||
LocalDate.of(1906, 12, 9), // G. Hopper
|
||||
LocalDate.of(1815, 12, 10), // A. Lovelace
|
||||
LocalDate.of(1903, 12, 3), // J. von Neumann
|
||||
LocalDate.of(1910, 6, 22), // K. Zuse
|
||||
};
|
||||
Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
|
||||
System.out.println("min = " + mm.getFirst());
|
||||
System.out.println("max = " + mm.getSecond());
|
||||
}
|
||||
}
|
||||
|
||||
class ArrayAlg
|
||||
{
|
||||
/**
|
||||
Gets the minimum and maximum of an array of objects of type T.
|
||||
@param a an array of objects of type T
|
||||
@return a pair with the min and max value, or null if a is
|
||||
null or empty
|
||||
*/
|
||||
public static <T extends Comparable> Pair<T> minmax(T[] a)
|
||||
{
|
||||
if (a == null || a.length == 0) return null;
|
||||
T min = a[0];
|
||||
T max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.compareTo(a[i]) > 0) min = a[i];
|
||||
if (max.compareTo(a[i]) < 0) max = a[i];
|
||||
}
|
||||
return new Pair<>(min, max);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,35 @@
|
||||
package pair3;
|
||||
|
||||
public class Manager extends Employee
|
||||
{
|
||||
private double bonus;
|
||||
|
||||
/**
|
||||
@param name the employee's name
|
||||
@param salary the salary
|
||||
@param year the hire year
|
||||
@param month the hire month
|
||||
@param day the hire day
|
||||
*/
|
||||
public Manager(String name, double salary, int year, int month, int day)
|
||||
{
|
||||
super(name, salary, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double b)
|
||||
{
|
||||
bonus = b;
|
||||
}
|
||||
|
||||
public double getBonus()
|
||||
{
|
||||
return bonus;
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,75 @@
|
||||
package pair3;
|
||||
|
||||
/**
|
||||
* @version 1.01 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PairTest3
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
|
||||
Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
|
||||
Pair<Manager> buddies = new Pair<>(ceo, cfo);
|
||||
printBuddies(buddies);
|
||||
|
||||
ceo.setBonus(1000000);
|
||||
cfo.setBonus(500000);
|
||||
Manager[] managers = { ceo, cfo };
|
||||
|
||||
Pair<Employee> result = new Pair<>();
|
||||
minmaxBonus(managers, result);
|
||||
System.out.println("first: " + result.getFirst().getName()
|
||||
+ ", second: " + result.getSecond().getName());
|
||||
maxminBonus(managers, result);
|
||||
System.out.println("first: " + result.getFirst().getName()
|
||||
+ ", second: " + result.getSecond().getName());
|
||||
}
|
||||
|
||||
public static void printBuddies(Pair<? extends Employee> p)
|
||||
{
|
||||
Employee first = p.getFirst();
|
||||
Employee second = p.getSecond();
|
||||
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
|
||||
}
|
||||
|
||||
public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
|
||||
{
|
||||
if (a.length == 0) return;
|
||||
Manager min = a[0];
|
||||
Manager max = a[0];
|
||||
for (int i = 1; i < a.length; i++)
|
||||
{
|
||||
if (min.getBonus() > a[i].getBonus()) min = a[i];
|
||||
if (max.getBonus() < a[i].getBonus()) max = a[i];
|
||||
}
|
||||
result.setFirst(min);
|
||||
result.setSecond(max);
|
||||
}
|
||||
|
||||
public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
|
||||
{
|
||||
minmaxBonus(a, result);
|
||||
PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
|
||||
}
|
||||
// Can't write public static <T super manager> ...
|
||||
}
|
||||
|
||||
class PairAlg
|
||||
{
|
||||
public static boolean hasNulls(Pair<?> p)
|
||||
{
|
||||
return p.getFirst() == null || p.getSecond() == null;
|
||||
}
|
||||
|
||||
public static void swap(Pair<?> p) { swapHelper(p); }
|
||||
|
||||
public static <T> void swapHelper(Pair<T> p)
|
||||
{
|
||||
T t = p.getFirst();
|
||||
p.setFirst(p.getSecond());
|
||||
p.setSecond(t);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package circularArrayQueue;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates how to extend the collections framework.
|
||||
* @version 1.21 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CircularArrayQueueTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Queue<String> q = new CircularArrayQueue<>(5);
|
||||
q.add("Amy");
|
||||
q.add("Bob");
|
||||
q.add("Carl");
|
||||
q.add("Deedee");
|
||||
q.add("Emile");
|
||||
q.remove();
|
||||
q.add("Fifi");
|
||||
q.remove();
|
||||
for (String s : q) System.out.println(s);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
A first-in, first-out bounded collection.
|
||||
*/
|
||||
class CircularArrayQueue<E> extends AbstractQueue<E>
|
||||
{
|
||||
private Object[] elements;
|
||||
private int head;
|
||||
private int tail;
|
||||
private int count;
|
||||
private int modcount;
|
||||
|
||||
/**
|
||||
Constructs an empty queue.
|
||||
@param capacity the maximum capacity of the queue
|
||||
*/
|
||||
public CircularArrayQueue(int capacity)
|
||||
{
|
||||
elements = new Object[capacity];
|
||||
count = 0;
|
||||
head = 0;
|
||||
tail = 0;
|
||||
}
|
||||
|
||||
public boolean offer(E newElement)
|
||||
{
|
||||
assert newElement != null;
|
||||
if (count < elements.length)
|
||||
{
|
||||
elements[tail] = newElement;
|
||||
tail = (tail + 1) % elements.length;
|
||||
count++;
|
||||
modcount++;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
public E poll()
|
||||
{
|
||||
if (count == 0) return null;
|
||||
E r = peek();
|
||||
head = (head + 1) % elements.length;
|
||||
count--;
|
||||
modcount++;
|
||||
return r;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public E peek()
|
||||
{
|
||||
if (count == 0) return null;
|
||||
return (E) elements[head];
|
||||
}
|
||||
|
||||
public int size()
|
||||
{
|
||||
return count;
|
||||
}
|
||||
|
||||
public Iterator<E> iterator()
|
||||
{
|
||||
return new QueueIterator();
|
||||
|
||||
}
|
||||
|
||||
private class QueueIterator implements Iterator<E>
|
||||
{
|
||||
private int offset;
|
||||
private int modcountAtConstruction;
|
||||
|
||||
public QueueIterator()
|
||||
{
|
||||
modcountAtConstruction = modcount;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public E next()
|
||||
{
|
||||
if (!hasNext()) throw new NoSuchElementException();
|
||||
E r = (E) elements[(head + offset) % elements.length];
|
||||
offset++;
|
||||
return r;
|
||||
}
|
||||
|
||||
public boolean hasNext()
|
||||
{
|
||||
if (modcount != modcountAtConstruction)
|
||||
throw new ConcurrentModificationException();
|
||||
return offset < count;
|
||||
}
|
||||
|
||||
public void remove()
|
||||
{
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package linkedList;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates operations on linked lists.
|
||||
* @version 1.11 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LinkedListTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
List<String> a = new LinkedList<>();
|
||||
a.add("Amy");
|
||||
a.add("Carl");
|
||||
a.add("Erica");
|
||||
|
||||
List<String> b = new LinkedList<>();
|
||||
b.add("Bob");
|
||||
b.add("Doug");
|
||||
b.add("Frances");
|
||||
b.add("Gloria");
|
||||
|
||||
// merge the words from b into a
|
||||
|
||||
ListIterator<String> aIter = a.listIterator();
|
||||
Iterator<String> bIter = b.iterator();
|
||||
|
||||
while (bIter.hasNext())
|
||||
{
|
||||
if (aIter.hasNext()) aIter.next();
|
||||
aIter.add(bIter.next());
|
||||
}
|
||||
|
||||
System.out.println(a);
|
||||
|
||||
// remove every second word from b
|
||||
|
||||
bIter = b.iterator();
|
||||
while (bIter.hasNext())
|
||||
{
|
||||
bIter.next(); // skip one element
|
||||
if (bIter.hasNext())
|
||||
{
|
||||
bIter.next(); // skip next element
|
||||
bIter.remove(); // remove that element
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(b);
|
||||
|
||||
// bulk operation: remove all words in b from a
|
||||
|
||||
a.removeAll(b);
|
||||
|
||||
System.out.println(a);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,42 @@
|
||||
package map;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of a map with key type String and value type Employee.
|
||||
* @version 1.12 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MapTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Map<String, Employee> staff = new HashMap<>();
|
||||
staff.put("144-25-5464", new Employee("Amy Lee"));
|
||||
staff.put("567-24-2546", new Employee("Harry Hacker"));
|
||||
staff.put("157-62-7935", new Employee("Gary Cooper"));
|
||||
staff.put("456-62-5527", new Employee("Francesca Cruz"));
|
||||
|
||||
// print all entries
|
||||
|
||||
System.out.println(staff);
|
||||
|
||||
// remove an entry
|
||||
|
||||
staff.remove("567-24-2546");
|
||||
|
||||
// replace an entry
|
||||
|
||||
staff.put("456-62-5527", new Employee("Francesca Miller"));
|
||||
|
||||
// look up a value
|
||||
|
||||
System.out.println(staff.get("157-62-7935"));
|
||||
|
||||
// iterate through all entries
|
||||
|
||||
staff.forEach((k, v) ->
|
||||
System.out.println("key=" + k + ", value=" + v));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package priorityQueue;
|
||||
|
||||
import java.util.*;
|
||||
import java.time.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of a priority queue.
|
||||
* @version 1.02 2015-06-20
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PriorityQueueTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
PriorityQueue<LocalDate> pq = new PriorityQueue<>();
|
||||
pq.add(LocalDate.of(1906, 12, 9)); // G. Hopper
|
||||
pq.add(LocalDate.of(1815, 12, 10)); // A. Lovelace
|
||||
pq.add(LocalDate.of(1903, 12, 3)); // J. von Neumann
|
||||
pq.add(LocalDate.of(1910, 6, 22)); // K. Zuse
|
||||
|
||||
System.out.println("Iterating over elements...");
|
||||
for (LocalDate date : pq)
|
||||
System.out.println(date);
|
||||
System.out.println("Removing elements...");
|
||||
while (!pq.isEmpty())
|
||||
System.out.println(pq.remove());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package set;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program uses a set to print all unique words in System.in.
|
||||
* @version 1.12 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SetTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Set<String> words = new HashSet<>(); // HashSet implements Set
|
||||
long totalTime = 0;
|
||||
|
||||
try (Scanner in = new Scanner(System.in))
|
||||
{
|
||||
while (in.hasNext())
|
||||
{
|
||||
String word = in.next();
|
||||
long callTime = System.currentTimeMillis();
|
||||
words.add(word);
|
||||
callTime = System.currentTimeMillis() - callTime;
|
||||
totalTime += callTime;
|
||||
}
|
||||
}
|
||||
|
||||
Iterator<String> iter = words.iterator();
|
||||
for (int i = 1; i <= 20 && iter.hasNext(); i++)
|
||||
System.out.println(iter.next());
|
||||
System.out.println(". . .");
|
||||
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package shuffle;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the random shuffle and sort algorithms.
|
||||
* @version 1.11 2012-01-26
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ShuffleTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
List<Integer> numbers = new ArrayList<>();
|
||||
for (int i = 1; i <= 49; i++)
|
||||
numbers.add(i);
|
||||
Collections.shuffle(numbers);
|
||||
List<Integer> winningCombination = numbers.subList(0, 6);
|
||||
Collections.sort(winningCombination);
|
||||
System.out.println(winningCombination);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package sieve;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program runs the Sieve of Erathostenes benchmark. It computes all primes up to 2,000,000.
|
||||
* @version 1.21 2004-08-03
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Sieve
|
||||
{
|
||||
public static void main(String[] s)
|
||||
{
|
||||
int n = 2000000;
|
||||
long start = System.currentTimeMillis();
|
||||
BitSet b = new BitSet(n + 1);
|
||||
int count = 0;
|
||||
int i;
|
||||
for (i = 2; i <= n; i++)
|
||||
b.set(i);
|
||||
i = 2;
|
||||
while (i * i <= n)
|
||||
{
|
||||
if (b.get(i))
|
||||
{
|
||||
count++;
|
||||
int k = 2 * i;
|
||||
while (k <= n)
|
||||
{
|
||||
b.clear(k);
|
||||
k += i;
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
while (i <= n)
|
||||
{
|
||||
if (b.get(i)) count++;
|
||||
i++;
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println(count + " primes");
|
||||
System.out.println((end - start) + " milliseconds");
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,61 @@
|
||||
package treeSet;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* An item with a description and a part number.
|
||||
*/
|
||||
public class Item implements Comparable<Item>
|
||||
{
|
||||
private String description;
|
||||
private int partNumber;
|
||||
|
||||
/**
|
||||
* Constructs an item.
|
||||
*
|
||||
* @param aDescription
|
||||
* the item's description
|
||||
* @param aPartNumber
|
||||
* the item's part number
|
||||
*/
|
||||
public Item(String aDescription, int aPartNumber)
|
||||
{
|
||||
description = aDescription;
|
||||
partNumber = aPartNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the description of this item.
|
||||
*
|
||||
* @return the description
|
||||
*/
|
||||
public String getDescription()
|
||||
{
|
||||
return description;
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return "[description=" + description + ", partNumber=" + partNumber + "]";
|
||||
}
|
||||
|
||||
public boolean equals(Object otherObject)
|
||||
{
|
||||
if (this == otherObject) return true;
|
||||
if (otherObject == null) return false;
|
||||
if (getClass() != otherObject.getClass()) return false;
|
||||
Item other = (Item) otherObject;
|
||||
return Objects.equals(description, other.description) && partNumber == other.partNumber;
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return Objects.hash(description, partNumber);
|
||||
}
|
||||
|
||||
public int compareTo(Item other)
|
||||
{
|
||||
int diff = Integer.compare(partNumber, other.partNumber);
|
||||
return diff != 0 ? diff : description.compareTo(other.description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package treeSet;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program sorts a set of item by comparing their descriptions.
|
||||
* @version 1.12 2015-06-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class TreeSetTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
SortedSet<Item> parts = new TreeSet<>();
|
||||
parts.add(new Item("Toaster", 1234));
|
||||
parts.add(new Item("Widget", 4562));
|
||||
parts.add(new Item("Modem", 9912));
|
||||
System.out.println(parts);
|
||||
|
||||
NavigableSet<Item> sortByDescription = new TreeSet<>(
|
||||
Comparator.comparing(Item::getDescription));
|
||||
|
||||
sortByDescription.addAll(parts);
|
||||
System.out.println(sortByDescription);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,81 @@
|
||||
package draw;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class DrawTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
JFrame frame = new DrawFrame();
|
||||
frame.setTitle("DrawTest");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains a panel with drawings
|
||||
*/
|
||||
class DrawFrame extends JFrame
|
||||
{
|
||||
public DrawFrame()
|
||||
{
|
||||
add(new DrawComponent());
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays rectangles and ellipses.
|
||||
*/
|
||||
class DrawComponent extends JComponent
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 400;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
Graphics2D g2 = (Graphics2D) g;
|
||||
|
||||
// draw a rectangle
|
||||
|
||||
double leftX = 100;
|
||||
double topY = 100;
|
||||
double width = 200;
|
||||
double height = 150;
|
||||
|
||||
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
|
||||
g2.draw(rect);
|
||||
|
||||
// draw the enclosed ellipse
|
||||
|
||||
Ellipse2D ellipse = new Ellipse2D.Double();
|
||||
ellipse.setFrame(rect);
|
||||
g2.draw(ellipse);
|
||||
|
||||
// draw a diagonal line
|
||||
|
||||
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
|
||||
|
||||
// draw a circle with the same center
|
||||
|
||||
double centerX = rect.getCenterX();
|
||||
double centerY = rect.getCenterY();
|
||||
double radius = 150;
|
||||
|
||||
Ellipse2D circle = new Ellipse2D.Double();
|
||||
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
|
||||
g2.draw(circle);
|
||||
}
|
||||
|
||||
public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package fill;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.34 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class FillTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
JFrame frame = new FillFrame();
|
||||
frame.setTitle("FillTest");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains a component with drawings
|
||||
*/
|
||||
class FillFrame extends JFrame
|
||||
{
|
||||
public FillFrame()
|
||||
{
|
||||
add(new FillComponent());
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays filled rectangles and ellipses
|
||||
*/
|
||||
class FillComponent extends JComponent
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 400;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
Graphics2D g2 = (Graphics2D) g;
|
||||
|
||||
// draw a rectangle
|
||||
|
||||
double leftX = 100;
|
||||
double topY = 100;
|
||||
double width = 200;
|
||||
double height = 150;
|
||||
|
||||
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
|
||||
g2.setPaint(Color.BLACK);
|
||||
g2.draw(rect);
|
||||
g2.setPaint(Color.RED);
|
||||
g2.fill(rect); // Note that the right and bottom edge are not painted over
|
||||
|
||||
// draw the enclosed ellipse
|
||||
|
||||
Ellipse2D ellipse = new Ellipse2D.Double();
|
||||
ellipse.setFrame(rect);
|
||||
g2.setPaint(new Color(0, 128, 128)); // a dull blue-green
|
||||
g2.fill(ellipse);
|
||||
}
|
||||
|
||||
public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package font;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.font.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.34 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class FontTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
JFrame frame = new FontFrame();
|
||||
frame.setTitle("FontTest");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a text message component
|
||||
*/
|
||||
class FontFrame extends JFrame
|
||||
{
|
||||
public FontFrame()
|
||||
{
|
||||
add(new FontComponent());
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that shows a centered message in a box.
|
||||
*/
|
||||
class FontComponent extends JComponent
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
Graphics2D g2 = (Graphics2D) g;
|
||||
|
||||
String message = "Hello, World!";
|
||||
|
||||
Font f = new Font("Serif", Font.BOLD, 36);
|
||||
g2.setFont(f);
|
||||
|
||||
// measure the size of the message
|
||||
|
||||
FontRenderContext context = g2.getFontRenderContext();
|
||||
Rectangle2D bounds = f.getStringBounds(message, context);
|
||||
|
||||
// set (x,y) = top left corner of text
|
||||
|
||||
double x = (getWidth() - bounds.getWidth()) / 2;
|
||||
double y = (getHeight() - bounds.getHeight()) / 2;
|
||||
|
||||
// add ascent to y to reach the baseline
|
||||
|
||||
double ascent = -bounds.getY();
|
||||
double baseY = y + ascent;
|
||||
|
||||
// draw the message
|
||||
|
||||
g2.drawString(message, (int) x, (int) baseY);
|
||||
|
||||
g2.setPaint(Color.LIGHT_GRAY);
|
||||
|
||||
// draw the baseline
|
||||
|
||||
g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY));
|
||||
|
||||
// draw the enclosing rectangle
|
||||
|
||||
Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight());
|
||||
g2.draw(rect);
|
||||
}
|
||||
|
||||
public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,53 @@
|
||||
package notHelloWorld;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class NotHelloWorld
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
JFrame frame = new NotHelloWorldFrame();
|
||||
frame.setTitle("NotHelloWorld");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains a message panel
|
||||
*/
|
||||
class NotHelloWorldFrame extends JFrame
|
||||
{
|
||||
public NotHelloWorldFrame()
|
||||
{
|
||||
add(new NotHelloWorldComponent());
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays a message.
|
||||
*/
|
||||
class NotHelloWorldComponent extends JComponent
|
||||
{
|
||||
public static final int MESSAGE_X = 75;
|
||||
public static final int MESSAGE_Y = 100;
|
||||
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
|
||||
}
|
||||
|
||||
public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package simpleFrame;
|
||||
|
||||
import java.awt.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2015-05-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SimpleFrameTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
SimpleFrame frame = new SimpleFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleFrame extends JFrame
|
||||
{
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
public SimpleFrame()
|
||||
{
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package sizedFrame;
|
||||
|
||||
import java.awt.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.34 2015-06-16
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SizedFrameTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() ->
|
||||
{
|
||||
JFrame frame = new SizedFrame();
|
||||
frame.setTitle("SizedFrame");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class SizedFrame extends JFrame
|
||||
{
|
||||
public SizedFrame()
|
||||
{
|
||||
// get screen dimensions
|
||||
|
||||
Toolkit kit = Toolkit.getDefaultToolkit();
|
||||
Dimension screenSize = kit.getScreenSize();
|
||||
int screenHeight = screenSize.height;
|
||||
int screenWidth = screenSize.width;
|
||||
|
||||
// set frame width, height and let platform pick screen location
|
||||
|
||||
setSize(screenWidth / 2, screenHeight / 2);
|
||||
setLocationByPlatform(true);
|
||||
|
||||
// set frame icon
|
||||
|
||||
Image img = new ImageIcon("icon.gif").getImage();
|
||||
setIconImage(img);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package action;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A frame with a panel that demonstrates color change actions.
|
||||
*/
|
||||
public class ActionFrame extends JFrame
|
||||
{
|
||||
private JPanel buttonPanel;
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
public ActionFrame()
|
||||
{
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
buttonPanel = new JPanel();
|
||||
|
||||
// define actions
|
||||
Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
|
||||
Color.YELLOW);
|
||||
Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
|
||||
Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
|
||||
|
||||
// add buttons for these actions
|
||||
buttonPanel.add(new JButton(yellowAction));
|
||||
buttonPanel.add(new JButton(blueAction));
|
||||
buttonPanel.add(new JButton(redAction));
|
||||
|
||||
// add panel to frame
|
||||
add(buttonPanel);
|
||||
|
||||
// associate the Y, B, and R keys with names
|
||||
InputMap imap = buttonPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
|
||||
imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
|
||||
imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
|
||||
imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
|
||||
|
||||
// associate the names with actions
|
||||
ActionMap amap = buttonPanel.getActionMap();
|
||||
amap.put("panel.yellow", yellowAction);
|
||||
amap.put("panel.blue", blueAction);
|
||||
amap.put("panel.red", redAction);
|
||||
}
|
||||
|
||||
public class ColorAction extends AbstractAction
|
||||
{
|
||||
/**
|
||||
* Constructs a color action.
|
||||
* @param name the name to show on the button
|
||||
* @param icon the icon to display on the button
|
||||
* @param c the background color
|
||||
*/
|
||||
public ColorAction(String name, Icon icon, Color c)
|
||||
{
|
||||
putValue(Action.NAME, name);
|
||||
putValue(Action.SMALL_ICON, icon);
|
||||
putValue(Action.SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
|
||||
putValue("color", c);
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
Color c = (Color) getValue("color");
|
||||
buttonPanel.setBackground(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package action;
|
||||
|
||||
import java.awt.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.34 2015-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ActionTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() -> {
|
||||
JFrame frame = new ActionFrame();
|
||||
frame.setTitle("ActionTest");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,63 @@
|
||||
package button;
|
||||
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A frame with a button panel
|
||||
*/
|
||||
public class ButtonFrame extends JFrame
|
||||
{
|
||||
private JPanel buttonPanel;
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
public ButtonFrame()
|
||||
{
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// create buttons
|
||||
JButton yellowButton = new JButton("Yellow");
|
||||
JButton blueButton = new JButton("Blue");
|
||||
JButton redButton = new JButton("Red");
|
||||
|
||||
buttonPanel = new JPanel();
|
||||
|
||||
// add buttons to panel
|
||||
buttonPanel.add(yellowButton);
|
||||
buttonPanel.add(blueButton);
|
||||
buttonPanel.add(redButton);
|
||||
|
||||
// add panel to frame
|
||||
add(buttonPanel);
|
||||
|
||||
// create button actions
|
||||
ColorAction yellowAction = new ColorAction(Color.YELLOW);
|
||||
ColorAction blueAction = new ColorAction(Color.BLUE);
|
||||
ColorAction redAction = new ColorAction(Color.RED);
|
||||
|
||||
// associate actions with buttons
|
||||
yellowButton.addActionListener(yellowAction);
|
||||
blueButton.addActionListener(blueAction);
|
||||
redButton.addActionListener(redAction);
|
||||
}
|
||||
|
||||
/**
|
||||
* An action listener that sets the panel's background color.
|
||||
*/
|
||||
private class ColorAction implements ActionListener
|
||||
{
|
||||
private Color backgroundColor;
|
||||
|
||||
public ColorAction(Color c)
|
||||
{
|
||||
backgroundColor = c;
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
buttonPanel.setBackground(backgroundColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package button;
|
||||
|
||||
import java.awt.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.34 2015-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ButtonTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(() -> {
|
||||
JFrame frame = new ButtonFrame();
|
||||
frame.setTitle("ButtonTest");
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1088 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user