corejava第8版
No files matched your search
|
After Width: | Height: | Size: 45 KiB |
@@ -0,0 +1,85 @@
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.*;
|
||||
import java.io.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* A program for viewing images.
|
||||
* @version 1.22 2007-05-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ImageViewer
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
JFrame frame = new ImageViewerFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a label to show an image.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
setTitle("ImageViewer");
|
||||
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(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent 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(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private JLabel label;
|
||||
private JFileChooser chooser;
|
||||
private static final int DEFAULT_WIDTH = 300;
|
||||
private static final int DEFAULT_HEIGHT = 400;
|
||||
}
|
||||
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 21 KiB |
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* This program displays a greeting from the authors.
|
||||
* @version 1.20 2004-02-28
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Welcome
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String[] greeting = new String[3];
|
||||
greeting[0] = "Welcome to Core Java";
|
||||
greeting[1] = "by Cay Horstmann";
|
||||
greeting[2] = "and Gary Cornell";
|
||||
|
||||
for (String g : greeting)
|
||||
System.out.println(g);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<html>
|
||||
<head>
|
||||
<title>WelcomeApplet</title>
|
||||
</head>
|
||||
<body>
|
||||
<hr/>
|
||||
<p>
|
||||
This applet is from the book
|
||||
<a href="http://www.horstmann.com/corejava.html">Core Java</a>
|
||||
by <em>Cay Horstmann</em> and <em>Gary Cornell</em>,
|
||||
published by Sun Microsystems Press.
|
||||
</p>
|
||||
<applet code="WelcomeApplet.class" width="400" height="200">
|
||||
<param name="greeting" value ="Welcome to Core Java!"/>
|
||||
</applet>
|
||||
<hr/>
|
||||
<p><a href="WelcomeApplet.java">The source.</a></p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,57 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.net.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* This applet displays a greeting from the authors.
|
||||
* @version 1.22 2007-04-08
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class WelcomeApplet extends JApplet
|
||||
{
|
||||
public void init()
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
setLayout(new BorderLayout());
|
||||
|
||||
JLabel label = new JLabel(getParameter("greeting"), SwingConstants.CENTER);
|
||||
label.setFont(new Font("Serif", Font.BOLD, 18));
|
||||
add(label, BorderLayout.CENTER);
|
||||
|
||||
JPanel panel = new JPanel();
|
||||
|
||||
JButton cayButton = new JButton("Cay Horstmann");
|
||||
cayButton.addActionListener(makeAction("http://www.horstmann.com"));
|
||||
panel.add(cayButton);
|
||||
|
||||
JButton garyButton = new JButton("Gary Cornell");
|
||||
garyButton.addActionListener(makeAction("mailto:gary_cornell@apress.com"));
|
||||
panel.add(garyButton);
|
||||
|
||||
add(panel, BorderLayout.SOUTH);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private ActionListener makeAction(final String urlString)
|
||||
{
|
||||
return new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
try
|
||||
{
|
||||
getAppletContext().showDocument(new URL(urlString));
|
||||
}
|
||||
catch (MalformedURLException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/* AUTOMATICALLY GENERATED ON Tue Apr 16 17:20:59 EDT 2002*/
|
||||
/* DO NOT EDIT */
|
||||
|
||||
grant {
|
||||
permission java.security.AllPermission;
|
||||
};
|
||||
|
||||
@@ -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!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* This program shows how to store tabular data in a 2D array.
|
||||
* @version 1.40 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CompoundInterest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
final double STARTRATE = 10;
|
||||
final int NRATES = 6;
|
||||
final int NYEARS = 10;
|
||||
|
||||
// set interest rates to 10 . . . 15%
|
||||
double[] interestRate = new double[NRATES];
|
||||
for (int j = 0; j < interestRate.length; j++)
|
||||
interestRate[j] = (STARTRATE + j) / 100.0;
|
||||
|
||||
double[][] balances = new double[NYEARS][NRATES];
|
||||
|
||||
// set initial balances to 10000
|
||||
for (int j = 0; j < balances[0].length; j++)
|
||||
balances[0][j] = 10000;
|
||||
|
||||
// compute interest for future years
|
||||
for (int i = 1; i < balances.length; i++)
|
||||
{
|
||||
for (int j = 0; j < balances[i].length; j++)
|
||||
{
|
||||
// get last year's balances from previous row
|
||||
double oldBalance = balances[i - 1][j];
|
||||
|
||||
// compute interest
|
||||
double interest = oldBalance * interestRate[j];
|
||||
|
||||
// compute this year's balances
|
||||
balances[i][j] = oldBalance + interest;
|
||||
}
|
||||
}
|
||||
|
||||
// print one row of interest rates
|
||||
for (int j = 0; j < interestRate.length; j++)
|
||||
System.out.printf("%9.0f%%", 100 * interestRate[j]);
|
||||
|
||||
System.out.println();
|
||||
|
||||
// print balance table
|
||||
for (double[] row : balances)
|
||||
{
|
||||
// print table row
|
||||
for (double b : row)
|
||||
System.out.printf("%10.2f", b);
|
||||
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* This is the first sample program in Core Java Chapter 3
|
||||
* @version 1.01 1997-03-22
|
||||
* @author Gary Cornell
|
||||
*/
|
||||
public class FirstSample
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
System.out.println("We will not use 'Hello, World!'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates console input.
|
||||
* @version 1.10 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class InputTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
// get first input
|
||||
System.out.print("What is your name? ");
|
||||
String name = in.nextLine();
|
||||
|
||||
// get second input
|
||||
System.out.print("How old are you? ");
|
||||
int age = in.nextInt();
|
||||
|
||||
// display output on console
|
||||
System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* This program demonstrates a triangular array.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LotteryArray
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
final int NMAX = 10;
|
||||
|
||||
// allocate triangular array
|
||||
int[][] odds = new int[NMAX + 1][];
|
||||
for (int n = 0; n <= NMAX; n++)
|
||||
odds[n] = new int[n + 1];
|
||||
|
||||
// fill triangular array
|
||||
for (int n = 0; n < odds.length; n++)
|
||||
for (int k = 0; k < odds[n].length; k++)
|
||||
{
|
||||
/*
|
||||
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
|
||||
*/
|
||||
int lotteryOdds = 1;
|
||||
for (int i = 1; i <= k; i++)
|
||||
lotteryOdds = lotteryOdds * (n - i + 1) / i;
|
||||
|
||||
odds[n][k] = lotteryOdds;
|
||||
}
|
||||
|
||||
// print triangular array
|
||||
for (int[] row : odds)
|
||||
{
|
||||
for (int odd : row)
|
||||
System.out.printf("%4d", odd);
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates array manipulation.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LotteryDrawing
|
||||
{
|
||||
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();
|
||||
|
||||
// fill an array with numbers 1 2 3 . . . n
|
||||
int[] numbers = new int[n];
|
||||
for (int i = 0; i < numbers.length; i++)
|
||||
numbers[i] = i + 1;
|
||||
|
||||
// draw k numbers and put them into a second array
|
||||
int[] result = new int[k];
|
||||
for (int i = 0; i < result.length; i++)
|
||||
{
|
||||
// make a random index between 0 and n - 1
|
||||
int r = (int) (Math.random() * n);
|
||||
|
||||
// pick the element at the random location
|
||||
result[i] = numbers[r];
|
||||
|
||||
// move the last element into the random location
|
||||
numbers[r] = numbers[n - 1];
|
||||
n--;
|
||||
}
|
||||
|
||||
// print the sorted array
|
||||
Arrays.sort(result);
|
||||
System.out.println("Bet the following combination. It'll make you rich!");
|
||||
for (int r : result)
|
||||
System.out.println(r);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates a <code>for</code> loop.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class LotteryOdds
|
||||
{
|
||||
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)
|
||||
*/
|
||||
|
||||
int lotteryOdds = 1;
|
||||
for (int i = 1; i <= k; i++)
|
||||
lotteryOdds = lotteryOdds * (n - i + 1) / i;
|
||||
|
||||
System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates a <code>while</code> loop.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Retirement
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// read inputs
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How much money do you need to retire? ");
|
||||
double goal = in.nextDouble();
|
||||
|
||||
System.out.print("How much money will you contribute every year? ");
|
||||
double payment = in.nextDouble();
|
||||
|
||||
System.out.print("Interest rate in %: ");
|
||||
double interestRate = in.nextDouble();
|
||||
|
||||
double balance = 0;
|
||||
int years = 0;
|
||||
|
||||
// update account balance while goal isn't reached
|
||||
while (balance < goal)
|
||||
{
|
||||
// add this year's payment and interest
|
||||
balance += payment;
|
||||
double interest = balance * interestRate / 100;
|
||||
balance += interest;
|
||||
years++;
|
||||
}
|
||||
|
||||
System.out.println("You can retire in " + years + " years.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates a <code>do/while</code> loop.
|
||||
* @version 1.20 2004-02-10
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Retirement2
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Scanner in = new Scanner(System.in);
|
||||
|
||||
System.out.print("How much money will you contribute every year? ");
|
||||
double payment = in.nextDouble();
|
||||
|
||||
System.out.print("Interest rate in %: ");
|
||||
double interestRate = in.nextDouble();
|
||||
|
||||
double balance = 0;
|
||||
int year = 0;
|
||||
|
||||
String input;
|
||||
|
||||
// update account balance while user isn't ready to retire
|
||||
do
|
||||
{
|
||||
// add this year's payment and interest
|
||||
balance += payment;
|
||||
double interest = balance * interestRate / 100;
|
||||
balance += interest;
|
||||
|
||||
year++;
|
||||
|
||||
// print current balance
|
||||
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
|
||||
|
||||
// ask if ready to retire and get input
|
||||
System.out.print("Ready to retire? (Y/N) ");
|
||||
input = in.next();
|
||||
}
|
||||
while (input.equals("N"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import java.text.DateFormatSymbols;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @version 1.4 2007-04-07
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
|
||||
public class CalendarTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
// construct d as current date
|
||||
GregorianCalendar d = new GregorianCalendar();
|
||||
|
||||
int today = d.get(Calendar.DAY_OF_MONTH);
|
||||
int month = d.get(Calendar.MONTH);
|
||||
|
||||
// set d to start date of the month
|
||||
d.set(Calendar.DAY_OF_MONTH, 1);
|
||||
|
||||
int weekday = d.get(Calendar.DAY_OF_WEEK);
|
||||
|
||||
// get first day of week (Sunday in the U.S.)
|
||||
int firstDayOfWeek = d.getFirstDayOfWeek();
|
||||
|
||||
// determine the required indentation for the first line
|
||||
int indent = 0;
|
||||
while (weekday != firstDayOfWeek)
|
||||
{
|
||||
indent++;
|
||||
d.add(Calendar.DAY_OF_MONTH, -1);
|
||||
weekday = d.get(Calendar.DAY_OF_WEEK);
|
||||
}
|
||||
|
||||
// print weekday names
|
||||
String[] weekdayNames = new DateFormatSymbols().getShortWeekdays();
|
||||
do
|
||||
{
|
||||
System.out.printf("%4s", weekdayNames[weekday]);
|
||||
d.add(Calendar.DAY_OF_MONTH, 1);
|
||||
weekday = d.get(Calendar.DAY_OF_WEEK);
|
||||
}
|
||||
while (weekday != firstDayOfWeek);
|
||||
System.out.println();
|
||||
|
||||
for (int i = 1; i <= indent; i++)
|
||||
System.out.print(" ");
|
||||
|
||||
d.set(Calendar.DAY_OF_MONTH, 1);
|
||||
do
|
||||
{
|
||||
// print day
|
||||
int day = d.get(Calendar.DAY_OF_MONTH);
|
||||
System.out.printf("%3d", day);
|
||||
|
||||
// mark current day with *
|
||||
if (day == today) System.out.print("*");
|
||||
else System.out.print(" ");
|
||||
|
||||
// advance d to the next day
|
||||
d.add(Calendar.DAY_OF_MONTH, 1);
|
||||
weekday = d.get(Calendar.DAY_OF_WEEK);
|
||||
|
||||
// start a new line at the start of the week
|
||||
if (weekday == firstDayOfWeek) System.out.println();
|
||||
}
|
||||
while (d.get(Calendar.MONTH) == month);
|
||||
// the loop exits when d is day 1 of the next month
|
||||
|
||||
// print final end of line if necessary
|
||||
if (weekday != firstDayOfWeek) 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
|
||||
{
|
||||
// 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 below
|
||||
// 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;
|
||||
}
|
||||
|
||||
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++;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program tests the Employee class.
|
||||
* @version 1.11 2004-02-19
|
||||
* @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
|
||||
{
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
|
||||
// GregorianCalendar uses 0 for January
|
||||
hireDay = calendar.getTime();
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public Date getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
@@ -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.
|
||||
* @author cay
|
||||
* @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());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.horstmann.corejava;
|
||||
|
||||
// the classes in this file are part of this package
|
||||
|
||||
import java.util.*;
|
||||
|
||||
// import statements come after the package statement
|
||||
|
||||
/**
|
||||
* @version 1.10 1999-12-18
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Employee
|
||||
{
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
|
||||
// GregorianCalendar uses 0 for January
|
||||
hireDay = calendar.getTime();
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public Date getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 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
|
||||
{
|
||||
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());
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private int id;
|
||||
private static int nextId = 1;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import java.lang.reflect.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the use of reflection for manipulating arrays.
|
||||
* @version 1.01 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ArrayGrowTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
int[] a = { 1, 2, 3 };
|
||||
a = (int[]) goodArrayGrow(a);
|
||||
arrayPrint(a);
|
||||
|
||||
String[] b = { "Tom", "Dick", "Harry" };
|
||||
b = (String[]) goodArrayGrow(b);
|
||||
arrayPrint(b);
|
||||
|
||||
System.out.println("The following call will generate an exception.");
|
||||
b = (String[]) badArrayGrow(b);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method attempts to grow an array by allocating a new array and copying all elements.
|
||||
* @param a the array to grow
|
||||
* @return a larger array that contains all elements of a. However, the returned array has
|
||||
* type Object[], not the same type as a
|
||||
*/
|
||||
static Object[] badArrayGrow(Object[] a)
|
||||
{
|
||||
int newLength = a.length * 11 / 10 + 10;
|
||||
Object[] newArray = new Object[newLength];
|
||||
System.arraycopy(a, 0, newArray, 0, a.length);
|
||||
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.
|
||||
*/
|
||||
static Object goodArrayGrow(Object a)
|
||||
{
|
||||
Class cl = a.getClass();
|
||||
if (!cl.isArray()) return null;
|
||||
Class componentType = cl.getComponentType();
|
||||
int length = Array.getLength(a);
|
||||
int newLength = length * 11 / 10 + 10;
|
||||
|
||||
Object newArray = Array.newInstance(componentType, newLength);
|
||||
System.arraycopy(a, 0, newArray, 0, length);
|
||||
return newArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* A convenience method to print all elements in an array
|
||||
* @param a the array to print. It can be an object array or a primitive type array
|
||||
*/
|
||||
static void arrayPrint(Object a)
|
||||
{
|
||||
Class cl = a.getClass();
|
||||
if (!cl.isArray()) return;
|
||||
Class componentType = cl.getComponentType();
|
||||
int length = Array.getLength(a);
|
||||
System.out.print(componentType.getName() + "[" + length + "] = { ");
|
||||
for (int i = 0; i < Array.getLength(a); i++)
|
||||
System.out.print(Array.get(a, i) + " ");
|
||||
System.out.println("}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the ArrayList class.
|
||||
* @version 1.1 2004-02-21
|
||||
* @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<Employee>();
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
|
||||
hireDay = calendar.getTime();
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public Date getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
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,142 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program demonstrates the equals method.
|
||||
* @version 1.11 2004-02-21
|
||||
* @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());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
|
||||
hireDay = calendar.getTime();
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public Date 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 name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay);
|
||||
}
|
||||
|
||||
public int hashCode()
|
||||
{
|
||||
return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13 * hireDay.hashCode();
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay
|
||||
+ "]";
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
|
||||
class Manager extends Employee
|
||||
{
|
||||
public Manager(String n, double s, int year, int month, int day)
|
||||
{
|
||||
super(n, s, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double b)
|
||||
{
|
||||
bonus = b;
|
||||
}
|
||||
|
||||
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 super.hashCode() + 17 * new Double(bonus).hashCode();
|
||||
}
|
||||
|
||||
public String toString()
|
||||
{
|
||||
return super.toString() + "[bonus=" + bonus + "]";
|
||||
}
|
||||
|
||||
private double bonus;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee
|
||||
{
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
|
||||
hireDay = calendar.getTime();
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public Date getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
|
||||
class Manager extends Employee
|
||||
{
|
||||
/**
|
||||
* @param n the employee's name
|
||||
* @param s the salary
|
||||
* @param year the hire year
|
||||
* @param month the hire month
|
||||
* @param day the hire day
|
||||
*/
|
||||
public Manager(String n, double s, int year, int month, int day)
|
||||
{
|
||||
super(n, s, year, month, day);
|
||||
bonus = 0;
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
double baseSalary = super.getSalary();
|
||||
return baseSalary + bonus;
|
||||
}
|
||||
|
||||
public void setBonus(double b)
|
||||
{
|
||||
bonus = b;
|
||||
}
|
||||
|
||||
private double bonus;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import java.lang.reflect.*;
|
||||
|
||||
/**
|
||||
* This program shows how to invoke methods through reflection.
|
||||
* @version 1.1 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MethodPointerTest
|
||||
{
|
||||
public static void main(String[] args) throws Exception
|
||||
{
|
||||
// get method pointers to the square and sqrt methods
|
||||
Method square = MethodPointerTest.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,84 @@
|
||||
import java.lang.reflect.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* This program uses reflection to spy on objects.
|
||||
* @version 1.11 2004-02-21
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ObjectAnalyzerTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
ArrayList<Integer> squares = new ArrayList<Integer>();
|
||||
for (int i = 1; i <= 5; i++)
|
||||
squares.add(i * i);
|
||||
System.out.println(new ObjectAnalyzer().toString(squares));
|
||||
}
|
||||
}
|
||||
|
||||
class ObjectAnalyzer
|
||||
{
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
private ArrayList<Object> visited = new ArrayList<Object>();
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
|
||||
abstract class Person
|
||||
{
|
||||
public Person(String n)
|
||||
{
|
||||
name = n;
|
||||
}
|
||||
|
||||
public abstract String getDescription();
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
private String name;
|
||||
}
|
||||
|
||||
class Employee extends Person
|
||||
{
|
||||
public Employee(String n, double s, int year, int month, int day)
|
||||
{
|
||||
super(n);
|
||||
salary = s;
|
||||
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
|
||||
hireDay = calendar.getTime();
|
||||
}
|
||||
|
||||
public double getSalary()
|
||||
{
|
||||
return salary;
|
||||
}
|
||||
|
||||
public Date getHireDay()
|
||||
{
|
||||
return hireDay;
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return String.format("an employee with a salary of $%.2f", salary);
|
||||
}
|
||||
|
||||
public void raiseSalary(double byPercent)
|
||||
{
|
||||
double raise = salary * byPercent / 100;
|
||||
salary += raise;
|
||||
}
|
||||
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
|
||||
class Student extends Person
|
||||
{
|
||||
/**
|
||||
* @param n the student's name
|
||||
* @param m the student's major
|
||||
*/
|
||||
public Student(String n, String m)
|
||||
{
|
||||
// pass n to superclass constructor
|
||||
super(n);
|
||||
major = m;
|
||||
}
|
||||
|
||||
public String getDescription()
|
||||
{
|
||||
return "a student majoring in " + major;
|
||||
}
|
||||
|
||||
private String major;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
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,49 @@
|
||||
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.10 2004-02-27
|
||||
* @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, final boolean beep)
|
||||
{
|
||||
ActionListener listener = new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
Date now = new Date();
|
||||
System.out.println("At the tone, the time is " + now);
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
};
|
||||
Timer t = new Timer(interval, listener);
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Employee implements Cloneable
|
||||
{
|
||||
public Employee(String n, double s)
|
||||
{
|
||||
name = n;
|
||||
salary = s;
|
||||
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 + "]";
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
private Date hireDay;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
class Employee implements Comparable<Employee>
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
{
|
||||
if (salary < other.salary) return -1;
|
||||
if (salary > other.salary) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private double salary;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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.10 2004-02-27
|
||||
* @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
|
||||
{
|
||||
/**
|
||||
* 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();
|
||||
}
|
||||
|
||||
private int interval;
|
||||
private boolean beep;
|
||||
|
||||
public class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
Date now = new Date();
|
||||
System.out.println("At the tone, the time is " + now);
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
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.00 2004-02-27
|
||||
* @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, final boolean beep)
|
||||
{
|
||||
class TimePrinter implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
Date now = new Date();
|
||||
System.out.println("At the tone, the time is " + now);
|
||||
if (beep) Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
ActionListener listener = new TimePrinter();
|
||||
Timer t = new Timer(interval, listener);
|
||||
t.start();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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
|
||||
{
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
private Object target;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* This program demonstrates the use of static inner classes.
|
||||
* @version 1.01 2004-02-27
|
||||
* @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
|
||||
{
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
private double first;
|
||||
private double 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.MAX_VALUE;
|
||||
double max = Double.MIN_VALUE;
|
||||
for (double v : values)
|
||||
{
|
||||
if (min > v) min = v;
|
||||
if (max < v) max = v;
|
||||
}
|
||||
return new Pair(min, max);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
@version 1.00 2000-04-13
|
||||
@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)
|
||||
{
|
||||
Date now = new Date();
|
||||
System.out.println("At the tone, the time is " + now);
|
||||
Toolkit.getDefaultToolkit().beep();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import java.awt.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-04-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class DrawTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
DrawFrame frame = new DrawFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains a panel with drawings
|
||||
*/
|
||||
class DrawFrame extends JFrame
|
||||
{
|
||||
public DrawFrame()
|
||||
{
|
||||
setTitle("DrawTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add panel to frame
|
||||
|
||||
DrawComponent component = new DrawComponent();
|
||||
add(component);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 400;
|
||||
public static final int DEFAULT_HEIGHT = 400;
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays rectangles and ellipses.
|
||||
*/
|
||||
class DrawComponent extends JComponent
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import java.awt.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-04-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class FillTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
FillFrame frame = new FillFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains a component with drawings
|
||||
*/
|
||||
class FillFrame extends JFrame
|
||||
{
|
||||
public FillFrame()
|
||||
{
|
||||
setTitle("FillTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add component to frame
|
||||
|
||||
FillComponent component = new FillComponent();
|
||||
add(component);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 400;
|
||||
public static final int DEFAULT_HEIGHT = 400;
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays filled rectangles and ellipses
|
||||
*/
|
||||
class FillComponent extends JComponent
|
||||
{
|
||||
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.RED);
|
||||
g2.fill(rect);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import java.awt.*;
|
||||
import java.awt.font.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-04-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class FontTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
FontFrame frame = new FontFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a text message component
|
||||
*/
|
||||
class FontFrame extends JFrame
|
||||
{
|
||||
public FontFrame()
|
||||
{
|
||||
setTitle("FontTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add component to frame
|
||||
|
||||
FontComponent component = new FontComponent();
|
||||
add(component);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that shows a centered message in a box.
|
||||
*/
|
||||
class FontComponent extends JComponent
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import java.awt.*;
|
||||
import java.io.*;
|
||||
import javax.imageio.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-04-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ImageTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
ImageFrame frame = new ImageFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with an image component
|
||||
*/
|
||||
class ImageFrame extends JFrame
|
||||
{
|
||||
public ImageFrame()
|
||||
{
|
||||
setTitle("ImageTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add component to frame
|
||||
|
||||
ImageComponent component = new ImageComponent();
|
||||
add(component);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays a tiled image
|
||||
*/
|
||||
class ImageComponent extends JComponent
|
||||
{
|
||||
public ImageComponent()
|
||||
{
|
||||
// acquire the image
|
||||
try
|
||||
{
|
||||
image = ImageIO.read(new File("blue-ball.gif"));
|
||||
}
|
||||
catch (IOException e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
if (image == null) return;
|
||||
|
||||
int imageWidth = image.getWidth(this);
|
||||
int imageHeight = image.getHeight(this);
|
||||
|
||||
// draw the image in the upper-left corner
|
||||
|
||||
g.drawImage(image, 0, 0, null);
|
||||
// tile the image across the component
|
||||
|
||||
for (int i = 0; i * imageWidth <= getWidth(); i++)
|
||||
for (int j = 0; j * imageHeight <= getHeight(); j++)
|
||||
if (i + j > 0) g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j
|
||||
* imageHeight);
|
||||
}
|
||||
|
||||
private Image image;
|
||||
}
|
||||
|
After Width: | Height: | Size: 925 B |
@@ -0,0 +1,17 @@
|
||||
import java.awt.*;
|
||||
|
||||
/**
|
||||
* @version 1.11 2004-06-05
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ListFonts
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment()
|
||||
.getAvailableFontFamilyNames();
|
||||
|
||||
for (String fontName : fontNames)
|
||||
System.out.println(fontName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class NotHelloWorld
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
NotHelloWorldFrame frame = new NotHelloWorldFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains a message panel
|
||||
*/
|
||||
class NotHelloWorldFrame extends JFrame
|
||||
{
|
||||
public NotHelloWorldFrame()
|
||||
{
|
||||
setTitle("NotHelloWorld");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add panel to frame
|
||||
|
||||
NotHelloWorldComponent comp = new NotHelloWorldComponent();
|
||||
add(comp);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* A component that displays a message.
|
||||
*/
|
||||
class NotHelloWorldComponent extends JComponent
|
||||
{
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
|
||||
}
|
||||
|
||||
public static final int MESSAGE_X = 75;
|
||||
public static final int MESSAGE_Y = 100;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import java.awt.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SimpleFrameTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
SimpleFrame frame = new SimpleFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleFrame extends JFrame
|
||||
{
|
||||
public SimpleFrame()
|
||||
{
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import java.awt.*;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-04-14
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SizedFrameTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
SizedFrame frame = new 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 and title
|
||||
|
||||
Image img = kit.getImage("icon.gif");
|
||||
setIconImage(img);
|
||||
setTitle("SizedFrame");
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,91 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ActionTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
ActionFrame frame = new ActionFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a panel that demonstrates color change actions.
|
||||
*/
|
||||
class ActionFrame extends JFrame
|
||||
{
|
||||
public ActionFrame()
|
||||
{
|
||||
setTitle("ActionTest");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
private JPanel buttonPanel;
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
|
After Width: | Height: | Size: 925 B |
|
After Width: | Height: | Size: 527 B |
|
After Width: | Height: | Size: 925 B |
@@ -0,0 +1,83 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ButtonTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
ButtonFrame frame = new ButtonFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a button panel
|
||||
*/
|
||||
class ButtonFrame extends JFrame
|
||||
{
|
||||
public ButtonFrame()
|
||||
{
|
||||
setTitle("ButtonTest");
|
||||
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
|
||||
{
|
||||
public ColorAction(Color c)
|
||||
{
|
||||
backgroundColor = c;
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
buttonPanel.setBackground(backgroundColor);
|
||||
}
|
||||
|
||||
private Color backgroundColor;
|
||||
}
|
||||
|
||||
private JPanel buttonPanel;
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.util.*;
|
||||
import java.awt.geom.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MouseTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
MouseFrame frame = new MouseFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame containing a panel for testing mouse operations
|
||||
*/
|
||||
class MouseFrame extends JFrame
|
||||
{
|
||||
public MouseFrame()
|
||||
{
|
||||
setTitle("MouseTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add component to frame
|
||||
|
||||
MouseComponent component = new MouseComponent();
|
||||
add(component);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* A component with mouse operations for adding and removing squares.
|
||||
*/
|
||||
class MouseComponent extends JComponent
|
||||
{
|
||||
public MouseComponent()
|
||||
{
|
||||
squares = new ArrayList<Rectangle2D>();
|
||||
current = null;
|
||||
|
||||
addMouseListener(new MouseHandler());
|
||||
addMouseMotionListener(new MouseMotionHandler());
|
||||
}
|
||||
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
Graphics2D g2 = (Graphics2D) g;
|
||||
|
||||
// draw all squares
|
||||
for (Rectangle2D r : squares)
|
||||
g2.draw(r);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the first square containing a point.
|
||||
* @param p a point
|
||||
* @return the first square that contains p
|
||||
*/
|
||||
public Rectangle2D find(Point2D p)
|
||||
{
|
||||
for (Rectangle2D r : squares)
|
||||
{
|
||||
if (r.contains(p)) return r;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a square to the collection.
|
||||
* @param p the center of the square
|
||||
*/
|
||||
public void add(Point2D p)
|
||||
{
|
||||
double x = p.getX();
|
||||
double y = p.getY();
|
||||
|
||||
current = new Rectangle2D.Double(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH,
|
||||
SIDELENGTH);
|
||||
squares.add(current);
|
||||
repaint();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a square from the collection.
|
||||
* @param s the square to remove
|
||||
*/
|
||||
public void remove(Rectangle2D s)
|
||||
{
|
||||
if (s == null) return;
|
||||
if (s == current) current = null;
|
||||
squares.remove(s);
|
||||
repaint();
|
||||
}
|
||||
|
||||
private static final int SIDELENGTH = 10;
|
||||
private ArrayList<Rectangle2D> squares;
|
||||
private Rectangle2D current;
|
||||
|
||||
// the square containing the mouse cursor
|
||||
|
||||
private class MouseHandler extends MouseAdapter
|
||||
{
|
||||
public void mousePressed(MouseEvent event)
|
||||
{
|
||||
// add a new square if the cursor isn't inside a square
|
||||
current = find(event.getPoint());
|
||||
if (current == null) add(event.getPoint());
|
||||
}
|
||||
|
||||
public void mouseClicked(MouseEvent event)
|
||||
{
|
||||
// remove the current square if double clicked
|
||||
current = find(event.getPoint());
|
||||
if (current != null && event.getClickCount() >= 2) remove(current);
|
||||
}
|
||||
}
|
||||
|
||||
private class MouseMotionHandler implements MouseMotionListener
|
||||
{
|
||||
public void mouseMoved(MouseEvent event)
|
||||
{
|
||||
// set the mouse cursor to cross hairs if it is inside
|
||||
// a rectangle
|
||||
|
||||
if (find(event.getPoint()) == null) setCursor(Cursor.getDefaultCursor());
|
||||
else setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
|
||||
}
|
||||
|
||||
public void mouseDragged(MouseEvent event)
|
||||
{
|
||||
if (current != null)
|
||||
{
|
||||
int x = event.getX();
|
||||
int y = event.getY();
|
||||
|
||||
// drag the current rectangle to center it at (x, y)
|
||||
current.setFrame(x - SIDELENGTH / 2, y - SIDELENGTH / 2, SIDELENGTH, SIDELENGTH);
|
||||
repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class PlafTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
PlafFrame frame = new PlafFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a button panel for changing look and feel
|
||||
*/
|
||||
class PlafFrame extends JFrame
|
||||
{
|
||||
public PlafFrame()
|
||||
{
|
||||
setTitle("PlafTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
buttonPanel = new JPanel();
|
||||
|
||||
UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels();
|
||||
for (UIManager.LookAndFeelInfo info : infos)
|
||||
makeButton(info.getName(), info.getClassName());
|
||||
|
||||
add(buttonPanel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes a button to change the pluggable look and feel.
|
||||
* @param name the button name
|
||||
* @param plafName the name of the look and feel class
|
||||
*/
|
||||
void makeButton(String name, final String plafName)
|
||||
{
|
||||
// add button to panel
|
||||
|
||||
JButton button = new JButton(name);
|
||||
buttonPanel.add(button);
|
||||
|
||||
// set button action
|
||||
|
||||
button.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
// button action: switch to the new look and feel
|
||||
try
|
||||
{
|
||||
UIManager.setLookAndFeel(plafName);
|
||||
SwingUtilities.updateComponentTreeUI(PlafFrame.this);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private JPanel buttonPanel;
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.border.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class BorderTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
BorderFrame frame = new BorderFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with radio buttons to pick a border style.
|
||||
*/
|
||||
class BorderFrame extends JFrame
|
||||
{
|
||||
public BorderFrame()
|
||||
{
|
||||
setTitle("BorderTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
demoPanel = new JPanel();
|
||||
buttonPanel = new JPanel();
|
||||
group = new ButtonGroup();
|
||||
|
||||
addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder());
|
||||
addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder());
|
||||
addRadioButton("Etched", BorderFactory.createEtchedBorder());
|
||||
addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));
|
||||
addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10, 10, Color.BLUE));
|
||||
addRadioButton("Empty", BorderFactory.createEmptyBorder());
|
||||
|
||||
Border etched = BorderFactory.createEtchedBorder();
|
||||
Border titled = BorderFactory.createTitledBorder(etched, "Border types");
|
||||
buttonPanel.setBorder(titled);
|
||||
|
||||
setLayout(new GridLayout(2, 1));
|
||||
add(buttonPanel);
|
||||
add(demoPanel);
|
||||
}
|
||||
|
||||
public void addRadioButton(String buttonName, final Border b)
|
||||
{
|
||||
JRadioButton button = new JRadioButton(buttonName);
|
||||
button.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
demoPanel.setBorder(b);
|
||||
}
|
||||
});
|
||||
group.add(button);
|
||||
buttonPanel.add(button);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 600;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JPanel demoPanel;
|
||||
private JPanel buttonPanel;
|
||||
private ButtonGroup group;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class Calculator
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
CalculatorFrame frame = new CalculatorFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a calculator panel.
|
||||
*/
|
||||
class CalculatorFrame extends JFrame
|
||||
{
|
||||
public CalculatorFrame()
|
||||
{
|
||||
setTitle("Calculator");
|
||||
CalculatorPanel panel = new CalculatorPanel();
|
||||
add(panel);
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel with calculator buttons and a result display.
|
||||
*/
|
||||
class CalculatorPanel extends JPanel
|
||||
{
|
||||
public CalculatorPanel()
|
||||
{
|
||||
setLayout(new BorderLayout());
|
||||
|
||||
result = 0;
|
||||
lastCommand = "=";
|
||||
start = true;
|
||||
|
||||
// add the display
|
||||
|
||||
display = new JButton("0");
|
||||
display.setEnabled(false);
|
||||
add(display, BorderLayout.NORTH);
|
||||
|
||||
ActionListener insert = new InsertAction();
|
||||
ActionListener command = new CommandAction();
|
||||
|
||||
// add the buttons in a 4 x 4 grid
|
||||
|
||||
panel = new JPanel();
|
||||
panel.setLayout(new GridLayout(4, 4));
|
||||
|
||||
addButton("7", insert);
|
||||
addButton("8", insert);
|
||||
addButton("9", insert);
|
||||
addButton("/", command);
|
||||
|
||||
addButton("4", insert);
|
||||
addButton("5", insert);
|
||||
addButton("6", insert);
|
||||
addButton("*", command);
|
||||
|
||||
addButton("1", insert);
|
||||
addButton("2", insert);
|
||||
addButton("3", insert);
|
||||
addButton("-", command);
|
||||
|
||||
addButton("0", insert);
|
||||
addButton(".", insert);
|
||||
addButton("=", command);
|
||||
addButton("+", command);
|
||||
|
||||
add(panel, BorderLayout.CENTER);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a button to the center panel.
|
||||
* @param label the button label
|
||||
* @param listener the button listener
|
||||
*/
|
||||
private void addButton(String label, ActionListener listener)
|
||||
{
|
||||
JButton button = new JButton(label);
|
||||
button.addActionListener(listener);
|
||||
panel.add(button);
|
||||
}
|
||||
|
||||
/**
|
||||
* This action inserts the button action string to the end of the display text.
|
||||
*/
|
||||
private class InsertAction implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
String input = event.getActionCommand();
|
||||
if (start)
|
||||
{
|
||||
display.setText("");
|
||||
start = false;
|
||||
}
|
||||
display.setText(display.getText() + input);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This action executes the command that the button action string denotes.
|
||||
*/
|
||||
private class CommandAction implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
String command = event.getActionCommand();
|
||||
|
||||
if (start)
|
||||
{
|
||||
if (command.equals("-"))
|
||||
{
|
||||
display.setText(command);
|
||||
start = false;
|
||||
}
|
||||
else lastCommand = command;
|
||||
}
|
||||
else
|
||||
{
|
||||
calculate(Double.parseDouble(display.getText()));
|
||||
lastCommand = command;
|
||||
start = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Carries out the pending calculation.
|
||||
* @param x the value to be accumulated with the prior result.
|
||||
*/
|
||||
public void calculate(double x)
|
||||
{
|
||||
if (lastCommand.equals("+")) result += x;
|
||||
else if (lastCommand.equals("-")) result -= x;
|
||||
else if (lastCommand.equals("*")) result *= x;
|
||||
else if (lastCommand.equals("/")) result /= x;
|
||||
else if (lastCommand.equals("=")) result = x;
|
||||
display.setText("" + result);
|
||||
}
|
||||
|
||||
private JButton display;
|
||||
private JPanel panel;
|
||||
private double result;
|
||||
private String lastCommand;
|
||||
private boolean start;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CheckBoxTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
CheckBoxFrame frame = new CheckBoxFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a sample text label and check boxes for selecting font attributes.
|
||||
*/
|
||||
class CheckBoxFrame extends JFrame
|
||||
{
|
||||
public CheckBoxFrame()
|
||||
{
|
||||
setTitle("CheckBoxTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add the sample text label
|
||||
|
||||
label = new JLabel("The quick brown fox jumps over the lazy dog.");
|
||||
label.setFont(new Font("Serif", Font.PLAIN, FONTSIZE));
|
||||
add(label, BorderLayout.CENTER);
|
||||
|
||||
// this listener sets the font attribute of
|
||||
// the label to the check box state
|
||||
|
||||
ActionListener listener = new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
int mode = 0;
|
||||
if (bold.isSelected()) mode += Font.BOLD;
|
||||
if (italic.isSelected()) mode += Font.ITALIC;
|
||||
label.setFont(new Font("Serif", mode, FONTSIZE));
|
||||
}
|
||||
};
|
||||
|
||||
// add the check boxes
|
||||
|
||||
JPanel buttonPanel = new JPanel();
|
||||
|
||||
bold = new JCheckBox("Bold");
|
||||
bold.addActionListener(listener);
|
||||
buttonPanel.add(bold);
|
||||
|
||||
italic = new JCheckBox("Italic");
|
||||
italic.addActionListener(listener);
|
||||
buttonPanel.add(italic);
|
||||
|
||||
add(buttonPanel, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JLabel label;
|
||||
private JCheckBox bold;
|
||||
private JCheckBox italic;
|
||||
|
||||
private static final int FONTSIZE = 12;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import java.awt.*;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class CircleLayoutTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
CircleLayoutFrame frame = new CircleLayoutFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that shows buttons arranged along a circle.
|
||||
*/
|
||||
class CircleLayoutFrame extends JFrame
|
||||
{
|
||||
public CircleLayoutFrame()
|
||||
{
|
||||
setTitle("CircleLayoutTest");
|
||||
|
||||
setLayout(new CircleLayout());
|
||||
add(new JButton("Yellow"));
|
||||
add(new JButton("Blue"));
|
||||
add(new JButton("Red"));
|
||||
add(new JButton("Green"));
|
||||
add(new JButton("Orange"));
|
||||
add(new JButton("Fuchsia"));
|
||||
add(new JButton("Indigo"));
|
||||
pack();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A layout manager that lays out components along a circle.
|
||||
*/
|
||||
class CircleLayout implements LayoutManager
|
||||
{
|
||||
public void addLayoutComponent(String name, Component comp)
|
||||
{
|
||||
}
|
||||
|
||||
public void removeLayoutComponent(Component comp)
|
||||
{
|
||||
}
|
||||
|
||||
public void setSizes(Container parent)
|
||||
{
|
||||
if (sizesSet) return;
|
||||
int n = parent.getComponentCount();
|
||||
|
||||
preferredWidth = 0;
|
||||
preferredHeight = 0;
|
||||
minWidth = 0;
|
||||
minHeight = 0;
|
||||
maxComponentWidth = 0;
|
||||
maxComponentHeight = 0;
|
||||
|
||||
// compute the maximum component widths and heights
|
||||
// and set the preferred size to the sum of the component sizes.
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Component c = parent.getComponent(i);
|
||||
if (c.isVisible())
|
||||
{
|
||||
Dimension d = c.getPreferredSize();
|
||||
maxComponentWidth = Math.max(maxComponentWidth, d.width);
|
||||
maxComponentHeight = Math.max(maxComponentHeight, d.height);
|
||||
preferredWidth += d.width;
|
||||
preferredHeight += d.height;
|
||||
}
|
||||
}
|
||||
minWidth = preferredWidth / 2;
|
||||
minHeight = preferredHeight / 2;
|
||||
sizesSet = true;
|
||||
}
|
||||
|
||||
public Dimension preferredLayoutSize(Container parent)
|
||||
{
|
||||
setSizes(parent);
|
||||
Insets insets = parent.getInsets();
|
||||
int width = preferredWidth + insets.left + insets.right;
|
||||
int height = preferredHeight + insets.top + insets.bottom;
|
||||
return new Dimension(width, height);
|
||||
}
|
||||
|
||||
public Dimension minimumLayoutSize(Container parent)
|
||||
{
|
||||
setSizes(parent);
|
||||
Insets insets = parent.getInsets();
|
||||
int width = minWidth + insets.left + insets.right;
|
||||
int height = minHeight + insets.top + insets.bottom;
|
||||
return new Dimension(width, height);
|
||||
}
|
||||
|
||||
public void layoutContainer(Container parent)
|
||||
{
|
||||
setSizes(parent);
|
||||
|
||||
// compute center of the circle
|
||||
|
||||
Insets insets = parent.getInsets();
|
||||
int containerWidth = parent.getSize().width - insets.left - insets.right;
|
||||
int containerHeight = parent.getSize().height - insets.top - insets.bottom;
|
||||
|
||||
int xcenter = insets.left + containerWidth / 2;
|
||||
int ycenter = insets.top + containerHeight / 2;
|
||||
|
||||
// compute radius of the circle
|
||||
|
||||
int xradius = (containerWidth - maxComponentWidth) / 2;
|
||||
int yradius = (containerHeight - maxComponentHeight) / 2;
|
||||
int radius = Math.min(xradius, yradius);
|
||||
|
||||
// lay out components along the circle
|
||||
|
||||
int n = parent.getComponentCount();
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Component c = parent.getComponent(i);
|
||||
if (c.isVisible())
|
||||
{
|
||||
double angle = 2 * Math.PI * i / n;
|
||||
|
||||
// center point of component
|
||||
int x = xcenter + (int) (Math.cos(angle) * radius);
|
||||
int y = ycenter + (int) (Math.sin(angle) * radius);
|
||||
|
||||
// move component so that its center is (x, y)
|
||||
// and its size is its preferred size
|
||||
Dimension d = c.getPreferredSize();
|
||||
c.setBounds(x - d.width / 2, y - d.height / 2, d.width, d.height);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int minWidth = 0;
|
||||
private int minHeight = 0;
|
||||
private int preferredWidth = 0;
|
||||
private int preferredHeight = 0;
|
||||
private boolean sizesSet = false;
|
||||
private int maxComponentWidth = 0;
|
||||
private int maxComponentHeight = 0;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.*;
|
||||
|
||||
/**
|
||||
* @version 1.03 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ColorChooserTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
ColorChooserFrame frame = new ColorChooserFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a color chooser panel
|
||||
*/
|
||||
class ColorChooserFrame extends JFrame
|
||||
{
|
||||
public ColorChooserFrame()
|
||||
{
|
||||
setTitle("ColorChooserTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add color chooser panel to frame
|
||||
|
||||
ColorChooserPanel panel = new ColorChooserPanel();
|
||||
add(panel);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel with buttons to pop up three types of color choosers
|
||||
*/
|
||||
class ColorChooserPanel extends JPanel
|
||||
{
|
||||
public ColorChooserPanel()
|
||||
{
|
||||
JButton modalButton = new JButton("Modal");
|
||||
modalButton.addActionListener(new ModalListener());
|
||||
add(modalButton);
|
||||
|
||||
JButton modelessButton = new JButton("Modeless");
|
||||
modelessButton.addActionListener(new ModelessListener());
|
||||
add(modelessButton);
|
||||
|
||||
JButton immediateButton = new JButton("Immediate");
|
||||
immediateButton.addActionListener(new ImmediateListener());
|
||||
add(immediateButton);
|
||||
}
|
||||
|
||||
/**
|
||||
* This listener pops up a modal color chooser
|
||||
*/
|
||||
private class ModalListener implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
Color defaultColor = getBackground();
|
||||
Color selected = JColorChooser.showDialog(ColorChooserPanel.this, "Set background",
|
||||
defaultColor);
|
||||
if (selected != null) setBackground(selected);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This listener pops up a modeless color chooser. The panel color is changed when the user
|
||||
* clicks the Ok button.
|
||||
*/
|
||||
private class ModelessListener implements ActionListener
|
||||
{
|
||||
public ModelessListener()
|
||||
{
|
||||
chooser = new JColorChooser();
|
||||
dialog = JColorChooser.createDialog(ColorChooserPanel.this, "Background Color",
|
||||
false /* not modal */, chooser, new ActionListener() // OK
|
||||
// button
|
||||
// listener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
setBackground(chooser.getColor());
|
||||
}
|
||||
}, null /* no Cancel button listener */);
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
chooser.setColor(getBackground());
|
||||
dialog.setVisible(true);
|
||||
}
|
||||
|
||||
private JDialog dialog;
|
||||
private JColorChooser chooser;
|
||||
}
|
||||
|
||||
/**
|
||||
* This listener pops up a modeless color chooser. The panel color is changed immediately when
|
||||
* the user picks a new color.
|
||||
*/
|
||||
private class ImmediateListener implements ActionListener
|
||||
{
|
||||
public ImmediateListener()
|
||||
{
|
||||
chooser = new JColorChooser();
|
||||
chooser.getSelectionModel().addChangeListener(new ChangeListener()
|
||||
{
|
||||
public void stateChanged(ChangeEvent event)
|
||||
{
|
||||
setBackground(chooser.getColor());
|
||||
}
|
||||
});
|
||||
|
||||
dialog = new JDialog((Frame) null, false /* not modal */);
|
||||
dialog.add(chooser);
|
||||
dialog.pack();
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
chooser.setColor(getBackground());
|
||||
dialog.setVisible(true);
|
||||
}
|
||||
|
||||
private JDialog dialog;
|
||||
private JColorChooser chooser;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ComboBoxTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
|
||||
ComboBoxFrame frame = new ComboBoxFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a sample text label and a combo box for selecting font faces.
|
||||
*/
|
||||
class ComboBoxFrame extends JFrame
|
||||
{
|
||||
public ComboBoxFrame()
|
||||
{
|
||||
setTitle("ComboBoxTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add the sample text label
|
||||
|
||||
label = new JLabel("The quick brown fox jumps over the lazy dog.");
|
||||
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
|
||||
add(label, BorderLayout.CENTER);
|
||||
|
||||
// make a combo box and add face names
|
||||
|
||||
faceCombo = new JComboBox();
|
||||
faceCombo.setEditable(true);
|
||||
faceCombo.addItem("Serif");
|
||||
faceCombo.addItem("SansSerif");
|
||||
faceCombo.addItem("Monospaced");
|
||||
faceCombo.addItem("Dialog");
|
||||
faceCombo.addItem("DialogInput");
|
||||
|
||||
// the combo box listener changes the label font to the selected face name
|
||||
|
||||
faceCombo.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
label.setFont(new Font((String) faceCombo.getSelectedItem(), Font.PLAIN,
|
||||
DEFAULT_SIZE));
|
||||
}
|
||||
});
|
||||
|
||||
// add combo box to a panel at the frame's southern border
|
||||
|
||||
JPanel comboPanel = new JPanel();
|
||||
comboPanel.add(faceCombo);
|
||||
add(comboPanel, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JComboBox faceCombo;
|
||||
private JLabel label;
|
||||
private static final int DEFAULT_SIZE = 12;
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class DataExchangeTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
DataExchangeFrame frame = new DataExchangeFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a menu whose File->Connect action shows a password dialog.
|
||||
*/
|
||||
class DataExchangeFrame extends JFrame
|
||||
{
|
||||
public DataExchangeFrame()
|
||||
{
|
||||
setTitle("DataExchangeTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// construct a File menu
|
||||
|
||||
JMenuBar mbar = new JMenuBar();
|
||||
setJMenuBar(mbar);
|
||||
JMenu fileMenu = new JMenu("File");
|
||||
mbar.add(fileMenu);
|
||||
|
||||
// add Connect and Exit menu items
|
||||
|
||||
JMenuItem connectItem = new JMenuItem("Connect");
|
||||
connectItem.addActionListener(new ConnectAction());
|
||||
fileMenu.add(connectItem);
|
||||
|
||||
// The Exit item exits the program
|
||||
|
||||
JMenuItem exitItem = new JMenuItem("Exit");
|
||||
exitItem.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
fileMenu.add(exitItem);
|
||||
|
||||
textArea = new JTextArea();
|
||||
add(new JScrollPane(textArea), BorderLayout.CENTER);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private PasswordChooser dialog = null;
|
||||
private JTextArea textArea;
|
||||
|
||||
/**
|
||||
* The Connect action pops up the password dialog.
|
||||
*/
|
||||
|
||||
private class ConnectAction implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
// if first time, construct dialog
|
||||
|
||||
if (dialog == null) dialog = new PasswordChooser();
|
||||
|
||||
// set default values
|
||||
dialog.setUser(new User("yourname", null));
|
||||
|
||||
// pop up dialog
|
||||
if (dialog.showDialog(DataExchangeFrame.this, "Connect"))
|
||||
{
|
||||
// if accepted, retrieve user input
|
||||
User u = dialog.getUser();
|
||||
textArea.append("user name = " + u.getName() + ", password = "
|
||||
+ (new String(u.getPassword())) + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A password chooser that is shown inside a dialog
|
||||
*/
|
||||
class PasswordChooser extends JPanel
|
||||
{
|
||||
public PasswordChooser()
|
||||
{
|
||||
setLayout(new BorderLayout());
|
||||
|
||||
// construct a panel with user name and password fields
|
||||
|
||||
JPanel panel = new JPanel();
|
||||
panel.setLayout(new GridLayout(2, 2));
|
||||
panel.add(new JLabel("User name:"));
|
||||
panel.add(username = new JTextField(""));
|
||||
panel.add(new JLabel("Password:"));
|
||||
panel.add(password = new JPasswordField(""));
|
||||
add(panel, BorderLayout.CENTER);
|
||||
|
||||
// create Ok and Cancel buttons that terminate the dialog
|
||||
|
||||
okButton = new JButton("Ok");
|
||||
okButton.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
ok = true;
|
||||
dialog.setVisible(false);
|
||||
}
|
||||
});
|
||||
|
||||
JButton cancelButton = new JButton("Cancel");
|
||||
cancelButton.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
dialog.setVisible(false);
|
||||
}
|
||||
});
|
||||
|
||||
// add buttons to southern border
|
||||
|
||||
JPanel buttonPanel = new JPanel();
|
||||
buttonPanel.add(okButton);
|
||||
buttonPanel.add(cancelButton);
|
||||
add(buttonPanel, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the dialog defaults.
|
||||
* @param u the default user information
|
||||
*/
|
||||
public void setUser(User u)
|
||||
{
|
||||
username.setText(u.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the dialog entries.
|
||||
* @return a User object whose state represents the dialog entries
|
||||
*/
|
||||
public User getUser()
|
||||
{
|
||||
return new User(username.getText(), password.getPassword());
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the chooser panel in a dialog
|
||||
* @param parent a component in the owner frame or null
|
||||
* @param title the dialog window title
|
||||
*/
|
||||
public boolean showDialog(Component parent, String title)
|
||||
{
|
||||
ok = false;
|
||||
|
||||
// locate the owner frame
|
||||
|
||||
Frame owner = null;
|
||||
if (parent instanceof Frame) owner = (Frame) parent;
|
||||
else owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
|
||||
|
||||
// if first time, or if owner has changed, make new dialog
|
||||
|
||||
if (dialog == null || dialog.getOwner() != owner)
|
||||
{
|
||||
dialog = new JDialog(owner, true);
|
||||
dialog.add(this);
|
||||
dialog.getRootPane().setDefaultButton(okButton);
|
||||
dialog.pack();
|
||||
}
|
||||
|
||||
// set title and show dialog
|
||||
|
||||
dialog.setTitle(title);
|
||||
dialog.setVisible(true);
|
||||
return ok;
|
||||
}
|
||||
|
||||
private JTextField username;
|
||||
private JPasswordField password;
|
||||
private JButton okButton;
|
||||
private boolean ok;
|
||||
private JDialog dialog;
|
||||
}
|
||||
|
||||
/**
|
||||
* A user has a name and password. For security reasons, the password is stored as a char[], not a
|
||||
* String.
|
||||
*/
|
||||
class User
|
||||
{
|
||||
public User(String aName, char[] aPassword)
|
||||
{
|
||||
name = aName;
|
||||
password = aPassword;
|
||||
}
|
||||
|
||||
public String getName()
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
||||
public char[] getPassword()
|
||||
{
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setName(String aName)
|
||||
{
|
||||
name = aName;
|
||||
}
|
||||
|
||||
public void setPassword(char[] aPassword)
|
||||
{
|
||||
password = aPassword;
|
||||
}
|
||||
|
||||
private String name;
|
||||
private char[] password;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class DialogTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
DialogFrame frame = new DialogFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a menu whose File->About action shows a dialog.
|
||||
*/
|
||||
class DialogFrame extends JFrame
|
||||
{
|
||||
public DialogFrame()
|
||||
{
|
||||
setTitle("DialogTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// construct a File menu
|
||||
|
||||
JMenuBar menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
JMenu fileMenu = new JMenu("File");
|
||||
menuBar.add(fileMenu);
|
||||
|
||||
// add About and Exit menu items
|
||||
|
||||
// The About item shows the About dialog
|
||||
|
||||
JMenuItem aboutItem = new JMenuItem("About");
|
||||
aboutItem.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
if (dialog == null) // first time
|
||||
dialog = new AboutDialog(DialogFrame.this);
|
||||
dialog.setVisible(true); // pop up dialog
|
||||
}
|
||||
});
|
||||
fileMenu.add(aboutItem);
|
||||
|
||||
// The Exit item exits the program
|
||||
|
||||
JMenuItem exitItem = new JMenuItem("Exit");
|
||||
exitItem.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
fileMenu.add(exitItem);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private AboutDialog dialog;
|
||||
}
|
||||
|
||||
/**
|
||||
* A sample modal dialog that displays a message and waits for the user to click the Ok button.
|
||||
*/
|
||||
class AboutDialog extends JDialog
|
||||
{
|
||||
public AboutDialog(JFrame owner)
|
||||
{
|
||||
super(owner, "About DialogTest", true);
|
||||
|
||||
// add HTML label to center
|
||||
|
||||
add(
|
||||
new JLabel(
|
||||
"<html><h1><i>Core Java</i></h1><hr>By Cay Horstmann and Gary Cornell</html>"),
|
||||
BorderLayout.CENTER);
|
||||
|
||||
// Ok button closes the dialog
|
||||
|
||||
JButton ok = new JButton("Ok");
|
||||
ok.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
setVisible(false);
|
||||
}
|
||||
});
|
||||
|
||||
// add Ok button to southern border
|
||||
|
||||
JPanel panel = new JPanel();
|
||||
panel.add(ok);
|
||||
add(panel, BorderLayout.SOUTH);
|
||||
|
||||
setSize(250, 150);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.beans.*;
|
||||
import java.io.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.filechooser.*;
|
||||
import javax.swing.filechooser.FileFilter;
|
||||
|
||||
/**
|
||||
* @version 1.23 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class FileChooserTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
ImageViewerFrame frame = new ImageViewerFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that has a menu for loading an image and a display area for the loaded image.
|
||||
*/
|
||||
class ImageViewerFrame extends JFrame
|
||||
{
|
||||
public ImageViewerFrame()
|
||||
{
|
||||
setTitle("FileChooserTest");
|
||||
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)
|
||||
{
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
// use a label to display the images
|
||||
label = new JLabel();
|
||||
add(label);
|
||||
|
||||
// set up file chooser
|
||||
chooser = new JFileChooser();
|
||||
|
||||
// accept all image files ending with .jpg, .jpeg, .gif
|
||||
/*
|
||||
final ExtensionFileFilter filter = new ExtensionFileFilter();
|
||||
filter.addExtension("jpg");
|
||||
filter.addExtension("jpeg");
|
||||
filter.addExtension("gif");
|
||||
filter.setDescription("Image files");
|
||||
*/
|
||||
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "jpeg", "gif");
|
||||
chooser.setFileFilter(filter);
|
||||
|
||||
chooser.setAccessory(new ImagePreviewer(chooser));
|
||||
|
||||
chooser.setFileView(new FileIconView(filter, new ImageIcon("palette.gif")));
|
||||
}
|
||||
|
||||
/**
|
||||
* This is the listener for the File->Open menu item.
|
||||
*/
|
||||
private class FileOpenListener implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
chooser.setCurrentDirectory(new File("."));
|
||||
|
||||
// show file chooser dialog
|
||||
int result = chooser.showOpenDialog(ImageViewerFrame.this);
|
||||
|
||||
// if image file accepted, set it as icon of the label
|
||||
if (result == JFileChooser.APPROVE_OPTION)
|
||||
{
|
||||
String name = chooser.getSelectedFile().getPath();
|
||||
label.setIcon(new ImageIcon(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
private JLabel label;
|
||||
private JFileChooser chooser;
|
||||
}
|
||||
|
||||
/**
|
||||
* A file view that displays an icon for all files that match a file filter.
|
||||
*/
|
||||
class FileIconView extends FileView
|
||||
{
|
||||
/**
|
||||
* Constructs a FileIconView.
|
||||
* @param aFilter a file filter--all files that this filter accepts will be shown with the icon.
|
||||
* @param anIcon--the icon shown with all accepted files.
|
||||
*/
|
||||
public FileIconView(FileFilter aFilter, Icon anIcon)
|
||||
{
|
||||
filter = aFilter;
|
||||
icon = anIcon;
|
||||
}
|
||||
|
||||
public Icon getIcon(File f)
|
||||
{
|
||||
if (!f.isDirectory() && filter.accept(f)) return icon;
|
||||
else return null;
|
||||
}
|
||||
|
||||
private FileFilter filter;
|
||||
private Icon icon;
|
||||
}
|
||||
|
||||
/**
|
||||
* A file chooser accessory that previews images.
|
||||
*/
|
||||
class ImagePreviewer extends JLabel
|
||||
{
|
||||
/**
|
||||
* Constructs an ImagePreviewer.
|
||||
* @param chooser the file chooser whose property changes trigger an image change in this
|
||||
* previewer
|
||||
*/
|
||||
public ImagePreviewer(JFileChooser chooser)
|
||||
{
|
||||
setPreferredSize(new Dimension(100, 100));
|
||||
setBorder(BorderFactory.createEtchedBorder());
|
||||
|
||||
chooser.addPropertyChangeListener(new PropertyChangeListener()
|
||||
{
|
||||
public void propertyChange(PropertyChangeEvent event)
|
||||
{
|
||||
if (event.getPropertyName() == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
|
||||
{
|
||||
// the user has selected a new file
|
||||
File f = (File) event.getNewValue();
|
||||
if (f == null)
|
||||
{
|
||||
setIcon(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// read the image into an icon
|
||||
ImageIcon icon = new ImageIcon(f.getPath());
|
||||
|
||||
// if the icon is too large to fit, scale it
|
||||
if (icon.getIconWidth() > getWidth()) icon = new ImageIcon(icon.getImage()
|
||||
.getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));
|
||||
|
||||
setIcon(icon);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 152 B |
@@ -0,0 +1,110 @@
|
||||
import java.awt.*;
|
||||
|
||||
/**
|
||||
* This class simplifies the use of the GridBagConstraints class.
|
||||
* @version 1.01 2004-05-06
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class GBC extends GridBagConstraints
|
||||
{
|
||||
/**
|
||||
* Constructs a GBC with a given gridx and gridy position and all other grid
|
||||
* bag constraint values set to the default.
|
||||
* @param gridx the gridx position
|
||||
* @param gridy the gridy position
|
||||
*/
|
||||
public GBC(int gridx, int gridy)
|
||||
{
|
||||
this.gridx = gridx;
|
||||
this.gridy = gridy;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a GBC with given gridx, gridy, gridwidth, gridheight and all
|
||||
* other grid bag constraint values set to the default.
|
||||
* @param gridx the gridx position
|
||||
* @param gridy the gridy position
|
||||
* @param gridwidth the cell span in x-direction
|
||||
* @param gridheight the cell span in y-direction
|
||||
*/
|
||||
public GBC(int gridx, int gridy, int gridwidth, int gridheight)
|
||||
{
|
||||
this.gridx = gridx;
|
||||
this.gridy = gridy;
|
||||
this.gridwidth = gridwidth;
|
||||
this.gridheight = gridheight;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the anchor.
|
||||
* @param anchor the anchor value
|
||||
* @return this object for further modification
|
||||
*/
|
||||
public GBC setAnchor(int anchor)
|
||||
{
|
||||
this.anchor = anchor;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the fill direction.
|
||||
* @param fill the fill direction
|
||||
* @return this object for further modification
|
||||
*/
|
||||
public GBC setFill(int fill)
|
||||
{
|
||||
this.fill = fill;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cell weights.
|
||||
* @param weightx the cell weight in x-direction
|
||||
* @param weighty the cell weight in y-direction
|
||||
* @return this object for further modification
|
||||
*/
|
||||
public GBC setWeight(double weightx, double weighty)
|
||||
{
|
||||
this.weightx = weightx;
|
||||
this.weighty = weighty;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the insets of this cell.
|
||||
* @param distance the spacing to use in all directions
|
||||
* @return this object for further modification
|
||||
*/
|
||||
public GBC setInsets(int distance)
|
||||
{
|
||||
this.insets = new Insets(distance, distance, distance, distance);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the insets of this cell.
|
||||
* @param top the spacing to use on top
|
||||
* @param left the spacing to use to the left
|
||||
* @param bottom the spacing to use on the bottom
|
||||
* @param right the spacing to use to the right
|
||||
* @return this object for further modification
|
||||
*/
|
||||
public GBC setInsets(int top, int left, int bottom, int right)
|
||||
{
|
||||
this.insets = new Insets(top, left, bottom, right);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the internal padding
|
||||
* @param ipadx the internal padding in x-direction
|
||||
* @param ipady the internal padding in y-direction
|
||||
* @return this object for further modification
|
||||
*/
|
||||
public GBC setIpad(int ipadx, int ipady)
|
||||
{
|
||||
this.ipadx = ipadx;
|
||||
this.ipady = ipady;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class GridBagLayoutTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
FontFrame frame = new FontFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that uses a grid bag layout to arrange font selection components.
|
||||
*/
|
||||
class FontFrame extends JFrame
|
||||
{
|
||||
public FontFrame()
|
||||
{
|
||||
setTitle("GridBagLayoutTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
GridBagLayout layout = new GridBagLayout();
|
||||
setLayout(layout);
|
||||
|
||||
ActionListener listener = new FontAction();
|
||||
|
||||
// construct components
|
||||
|
||||
JLabel faceLabel = new JLabel("Face: ");
|
||||
|
||||
face = new JComboBox(new String[] { "Serif", "SansSerif", "Monospaced", "Dialog",
|
||||
"DialogInput" });
|
||||
|
||||
face.addActionListener(listener);
|
||||
|
||||
JLabel sizeLabel = new JLabel("Size: ");
|
||||
|
||||
size = new JComboBox(new String[] { "8", "10", "12", "15", "18", "24", "36", "48" });
|
||||
|
||||
size.addActionListener(listener);
|
||||
|
||||
bold = new JCheckBox("Bold");
|
||||
bold.addActionListener(listener);
|
||||
|
||||
italic = new JCheckBox("Italic");
|
||||
italic.addActionListener(listener);
|
||||
|
||||
sample = new JTextArea();
|
||||
sample.setText("The quick brown fox jumps over the lazy dog");
|
||||
sample.setEditable(false);
|
||||
sample.setLineWrap(true);
|
||||
sample.setBorder(BorderFactory.createEtchedBorder());
|
||||
|
||||
// add components to grid, using GBC convenience class
|
||||
|
||||
add(faceLabel, new GBC(0, 0).setAnchor(GBC.EAST));
|
||||
add(face, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(1));
|
||||
add(sizeLabel, new GBC(0, 1).setAnchor(GBC.EAST));
|
||||
add(size, new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(1));
|
||||
add(bold, new GBC(0, 2, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100));
|
||||
add(italic, new GBC(0, 3, 2, 1).setAnchor(GBC.CENTER).setWeight(100, 100));
|
||||
add(sample, new GBC(2, 0, 1, 4).setFill(GBC.BOTH).setWeight(100, 100));
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JComboBox face;
|
||||
private JComboBox size;
|
||||
private JCheckBox bold;
|
||||
private JCheckBox italic;
|
||||
private JTextArea sample;
|
||||
|
||||
/**
|
||||
* An action listener that changes the font of the sample text.
|
||||
*/
|
||||
private class FontAction implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
String fontFace = (String) face.getSelectedItem();
|
||||
int fontStyle = (bold.isSelected() ? Font.BOLD : 0)
|
||||
+ (italic.isSelected() ? Font.ITALIC : 0);
|
||||
int fontSize = Integer.parseInt((String) size.getSelectedItem());
|
||||
Font font = new Font(fontFace, fontStyle, fontSize);
|
||||
sample.setFont(font);
|
||||
sample.repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.0 2007-04-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class GroupLayoutTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
FontFrame frame = new FontFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that uses a group layout to arrange font selection components.
|
||||
*/
|
||||
class FontFrame extends JFrame
|
||||
{
|
||||
public FontFrame()
|
||||
{
|
||||
setTitle("GroupLayoutTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
ActionListener listener = new FontAction();
|
||||
|
||||
// construct components
|
||||
|
||||
JLabel faceLabel = new JLabel("Face: ");
|
||||
|
||||
face = new JComboBox(new String[] { "Serif", "SansSerif", "Monospaced", "Dialog",
|
||||
"DialogInput" });
|
||||
|
||||
face.addActionListener(listener);
|
||||
|
||||
JLabel sizeLabel = new JLabel("Size: ");
|
||||
|
||||
size = new JComboBox(new String[] { "8", "10", "12", "15", "18", "24", "36", "48" });
|
||||
|
||||
size.addActionListener(listener);
|
||||
|
||||
bold = new JCheckBox("Bold");
|
||||
bold.addActionListener(listener);
|
||||
|
||||
italic = new JCheckBox("Italic");
|
||||
italic.addActionListener(listener);
|
||||
|
||||
sample = new JTextArea();
|
||||
sample.setText("The quick brown fox jumps over the lazy dog");
|
||||
sample.setEditable(false);
|
||||
sample.setLineWrap(true);
|
||||
sample.setBorder(BorderFactory.createEtchedBorder());
|
||||
|
||||
pane = new JScrollPane(sample);
|
||||
|
||||
GroupLayout layout = new GroupLayout(getContentPane());
|
||||
setLayout(layout);
|
||||
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
|
||||
.addGroup(
|
||||
layout.createSequentialGroup().addContainerGap().addGroup(
|
||||
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(
|
||||
GroupLayout.Alignment.TRAILING,
|
||||
layout.createSequentialGroup().addGroup(
|
||||
layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
|
||||
.addComponent(faceLabel).addComponent(sizeLabel))
|
||||
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
|
||||
.addGroup(
|
||||
layout.createParallelGroup(
|
||||
GroupLayout.Alignment.LEADING, false)
|
||||
.addComponent(size).addComponent(face)))
|
||||
.addComponent(italic).addComponent(bold)).addPreferredGap(
|
||||
LayoutStyle.ComponentPlacement.RELATED).addComponent(pane)
|
||||
.addContainerGap()));
|
||||
|
||||
layout.linkSize(SwingConstants.HORIZONTAL, new java.awt.Component[] { face, size });
|
||||
|
||||
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
|
||||
.addGroup(
|
||||
layout.createSequentialGroup().addContainerGap().addGroup(
|
||||
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(
|
||||
pane, GroupLayout.Alignment.TRAILING).addGroup(
|
||||
layout.createSequentialGroup().addGroup(
|
||||
layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
|
||||
.addComponent(face).addComponent(faceLabel))
|
||||
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
|
||||
.addGroup(
|
||||
layout.createParallelGroup(
|
||||
GroupLayout.Alignment.BASELINE).addComponent(size)
|
||||
.addComponent(sizeLabel)).addPreferredGap(
|
||||
LayoutStyle.ComponentPlacement.RELATED).addComponent(
|
||||
italic, GroupLayout.DEFAULT_SIZE,
|
||||
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
|
||||
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
|
||||
.addComponent(bold, GroupLayout.DEFAULT_SIZE,
|
||||
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
|
||||
.addContainerGap()));
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JComboBox face;
|
||||
private JComboBox size;
|
||||
private JCheckBox bold;
|
||||
private JCheckBox italic;
|
||||
private JScrollPane pane;
|
||||
private JTextArea sample;
|
||||
|
||||
/**
|
||||
* An action listener that changes the font of the sample text.
|
||||
*/
|
||||
private class FontAction implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
String fontFace = (String) face.getSelectedItem();
|
||||
int fontStyle = (bold.isSelected() ? Font.BOLD : 0)
|
||||
+ (italic.isSelected() ? Font.ITALIC : 0);
|
||||
int fontSize = Integer.parseInt((String) size.getSelectedItem());
|
||||
Font font = new Font(fontFace, fontStyle, fontSize);
|
||||
sample.setFont(font);
|
||||
sample.repaint();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import java.awt.EventQueue;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.23 2007-05-30
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class MenuTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
MenuFrame frame = new MenuFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a sample menu bar.
|
||||
*/
|
||||
class MenuFrame extends JFrame
|
||||
{
|
||||
public MenuFrame()
|
||||
{
|
||||
setTitle("MenuTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
JMenu fileMenu = new JMenu("File");
|
||||
fileMenu.add(new TestAction("New"));
|
||||
|
||||
// demonstrate accelerators
|
||||
|
||||
JMenuItem openItem = fileMenu.add(new TestAction("Open"));
|
||||
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
|
||||
|
||||
fileMenu.addSeparator();
|
||||
|
||||
saveAction = new TestAction("Save");
|
||||
JMenuItem saveItem = fileMenu.add(saveAction);
|
||||
saveItem.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
|
||||
|
||||
saveAsAction = new TestAction("Save As");
|
||||
fileMenu.add(saveAsAction);
|
||||
fileMenu.addSeparator();
|
||||
|
||||
fileMenu.add(new AbstractAction("Exit")
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.exit(0);
|
||||
}
|
||||
});
|
||||
|
||||
// demonstrate check box and radio button menus
|
||||
|
||||
readonlyItem = new JCheckBoxMenuItem("Read-only");
|
||||
readonlyItem.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
boolean saveOk = !readonlyItem.isSelected();
|
||||
saveAction.setEnabled(saveOk);
|
||||
saveAsAction.setEnabled(saveOk);
|
||||
}
|
||||
});
|
||||
|
||||
ButtonGroup group = new ButtonGroup();
|
||||
|
||||
JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert");
|
||||
insertItem.setSelected(true);
|
||||
JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
|
||||
|
||||
group.add(insertItem);
|
||||
group.add(overtypeItem);
|
||||
|
||||
// demonstrate icons
|
||||
|
||||
Action cutAction = new TestAction("Cut");
|
||||
cutAction.putValue(Action.SMALL_ICON, new ImageIcon("cut.gif"));
|
||||
Action copyAction = new TestAction("Copy");
|
||||
copyAction.putValue(Action.SMALL_ICON, new ImageIcon("copy.gif"));
|
||||
Action pasteAction = new TestAction("Paste");
|
||||
pasteAction.putValue(Action.SMALL_ICON, new ImageIcon("paste.gif"));
|
||||
|
||||
JMenu editMenu = new JMenu("Edit");
|
||||
editMenu.add(cutAction);
|
||||
editMenu.add(copyAction);
|
||||
editMenu.add(pasteAction);
|
||||
|
||||
// demonstrate nested menus
|
||||
|
||||
JMenu optionMenu = new JMenu("Options");
|
||||
|
||||
optionMenu.add(readonlyItem);
|
||||
optionMenu.addSeparator();
|
||||
optionMenu.add(insertItem);
|
||||
optionMenu.add(overtypeItem);
|
||||
|
||||
editMenu.addSeparator();
|
||||
editMenu.add(optionMenu);
|
||||
|
||||
// demonstrate mnemonics
|
||||
|
||||
JMenu helpMenu = new JMenu("Help");
|
||||
helpMenu.setMnemonic('H');
|
||||
|
||||
JMenuItem indexItem = new JMenuItem("Index");
|
||||
indexItem.setMnemonic('I');
|
||||
helpMenu.add(indexItem);
|
||||
|
||||
// you can also add the mnemonic key to an action
|
||||
Action aboutAction = new TestAction("About");
|
||||
aboutAction.putValue(Action.MNEMONIC_KEY, new Integer('A'));
|
||||
helpMenu.add(aboutAction);
|
||||
|
||||
// add all top-level menus to menu bar
|
||||
|
||||
JMenuBar menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
menuBar.add(fileMenu);
|
||||
menuBar.add(editMenu);
|
||||
menuBar.add(helpMenu);
|
||||
|
||||
// demonstrate pop-ups
|
||||
|
||||
popup = new JPopupMenu();
|
||||
popup.add(cutAction);
|
||||
popup.add(copyAction);
|
||||
popup.add(pasteAction);
|
||||
|
||||
JPanel panel = new JPanel();
|
||||
panel.setComponentPopupMenu(popup);
|
||||
add(panel);
|
||||
|
||||
// the following line is a workaround for bug 4966109
|
||||
panel.addMouseListener(new MouseAdapter()
|
||||
{
|
||||
});
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private Action saveAction;
|
||||
private Action saveAsAction;
|
||||
private JCheckBoxMenuItem readonlyItem;
|
||||
private JPopupMenu popup;
|
||||
}
|
||||
|
||||
/**
|
||||
* A sample action that prints the action name to System.out
|
||||
*/
|
||||
class TestAction extends AbstractAction
|
||||
{
|
||||
public TestAction(String name)
|
||||
{
|
||||
super(name);
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.out.println(getValue(Action.NAME) + " selected.");
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 145 B |
|
After Width: | Height: | Size: 130 B |
|
After Width: | Height: | Size: 159 B |
@@ -0,0 +1,218 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import java.awt.geom.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-04-28
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class OptionDialogTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
OptionDialogFrame frame = new OptionDialogFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A panel with radio buttons inside a titled border.
|
||||
*/
|
||||
class ButtonPanel extends JPanel
|
||||
{
|
||||
/**
|
||||
* Constructs a button panel.
|
||||
* @param title the title shown in the border
|
||||
* @param options an array of radio button labels
|
||||
*/
|
||||
public ButtonPanel(String title, String... options)
|
||||
{
|
||||
setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), title));
|
||||
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
|
||||
group = new ButtonGroup();
|
||||
|
||||
// make one radio button for each option
|
||||
for (String option : options)
|
||||
{
|
||||
JRadioButton b = new JRadioButton(option);
|
||||
b.setActionCommand(option);
|
||||
add(b);
|
||||
group.add(b);
|
||||
b.setSelected(option == options[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the currently selected option.
|
||||
* @return the label of the currently selected radio button.
|
||||
*/
|
||||
public String getSelection()
|
||||
{
|
||||
return group.getSelection().getActionCommand();
|
||||
}
|
||||
|
||||
private ButtonGroup group;
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame that contains settings for selecting various option dialogs.
|
||||
*/
|
||||
class OptionDialogFrame extends JFrame
|
||||
{
|
||||
public OptionDialogFrame()
|
||||
{
|
||||
setTitle("OptionDialogTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
JPanel gridPanel = new JPanel();
|
||||
gridPanel.setLayout(new GridLayout(2, 3));
|
||||
|
||||
typePanel = new ButtonPanel("Type", "Message", "Confirm", "Option", "Input");
|
||||
messageTypePanel = new ButtonPanel("Message Type", "ERROR_MESSAGE", "INFORMATION_MESSAGE",
|
||||
"WARNING_MESSAGE", "QUESTION_MESSAGE", "PLAIN_MESSAGE");
|
||||
messagePanel = new ButtonPanel("Message", "String", "Icon", "Component", "Other", "Object[]");
|
||||
optionTypePanel = new ButtonPanel("Confirm", "DEFAULT_OPTION", "YES_NO_OPTION",
|
||||
"YES_NO_CANCEL_OPTION", "OK_CANCEL_OPTION");
|
||||
optionsPanel = new ButtonPanel("Option", "String[]", "Icon[]", "Object[]");
|
||||
inputPanel = new ButtonPanel("Input", "Text field", "Combo box");
|
||||
|
||||
gridPanel.add(typePanel);
|
||||
gridPanel.add(messageTypePanel);
|
||||
gridPanel.add(messagePanel);
|
||||
gridPanel.add(optionTypePanel);
|
||||
gridPanel.add(optionsPanel);
|
||||
gridPanel.add(inputPanel);
|
||||
|
||||
// add a panel with a Show button
|
||||
|
||||
JPanel showPanel = new JPanel();
|
||||
JButton showButton = new JButton("Show");
|
||||
showButton.addActionListener(new ShowAction());
|
||||
showPanel.add(showButton);
|
||||
|
||||
add(gridPanel, BorderLayout.CENTER);
|
||||
add(showPanel, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the currently selected message.
|
||||
* @return a string, icon, component or object array, depending on the Message panel selection
|
||||
*/
|
||||
public Object getMessage()
|
||||
{
|
||||
String s = messagePanel.getSelection();
|
||||
if (s.equals("String")) return messageString;
|
||||
else if (s.equals("Icon")) return messageIcon;
|
||||
else if (s.equals("Component")) return messageComponent;
|
||||
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
|
||||
messageComponent, messageObject };
|
||||
else if (s.equals("Other")) return messageObject;
|
||||
else return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the currently selected options.
|
||||
* @return an array of strings, icons or objects, depending on the Option panel selection
|
||||
*/
|
||||
public Object[] getOptions()
|
||||
{
|
||||
String s = optionsPanel.getSelection();
|
||||
if (s.equals("String[]")) return new String[] { "Yellow", "Blue", "Red" };
|
||||
else if (s.equals("Icon[]")) return new Icon[] { new ImageIcon("yellow-ball.gif"),
|
||||
new ImageIcon("blue-ball.gif"), new ImageIcon("red-ball.gif") };
|
||||
else if (s.equals("Object[]")) return new Object[] { messageString, messageIcon,
|
||||
messageComponent, messageObject };
|
||||
else return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the selected message or option type
|
||||
* @param panel the Message Type or Confirm panel
|
||||
* @return the selected XXX_MESSAGE or XXX_OPTION constant from the JOptionPane class
|
||||
*/
|
||||
public int getType(ButtonPanel panel)
|
||||
{
|
||||
String s = panel.getSelection();
|
||||
try
|
||||
{
|
||||
return JOptionPane.class.getField(s).getInt(null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The action listener for the Show button shows a Confirm, Input, Message or Option dialog
|
||||
* depending on the Type panel selection.
|
||||
*/
|
||||
private class ShowAction implements ActionListener
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
if (typePanel.getSelection().equals("Confirm")) JOptionPane.showConfirmDialog(
|
||||
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
|
||||
getType(messageTypePanel));
|
||||
else if (typePanel.getSelection().equals("Input"))
|
||||
{
|
||||
if (inputPanel.getSelection().equals("Text field")) JOptionPane.showInputDialog(
|
||||
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
|
||||
else JOptionPane.showInputDialog(OptionDialogFrame.this, getMessage(), "Title",
|
||||
getType(messageTypePanel), null, new String[] { "Yellow", "Blue", "Red" },
|
||||
"Blue");
|
||||
}
|
||||
else if (typePanel.getSelection().equals("Message")) JOptionPane.showMessageDialog(
|
||||
OptionDialogFrame.this, getMessage(), "Title", getType(messageTypePanel));
|
||||
else if (typePanel.getSelection().equals("Option")) JOptionPane.showOptionDialog(
|
||||
OptionDialogFrame.this, getMessage(), "Title", getType(optionTypePanel),
|
||||
getType(messageTypePanel), null, getOptions(), getOptions()[0]);
|
||||
}
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 600;
|
||||
public static final int DEFAULT_HEIGHT = 400;
|
||||
|
||||
private ButtonPanel typePanel;
|
||||
private ButtonPanel messagePanel;
|
||||
private ButtonPanel messageTypePanel;
|
||||
private ButtonPanel optionTypePanel;
|
||||
private ButtonPanel optionsPanel;
|
||||
private ButtonPanel inputPanel;
|
||||
|
||||
private String messageString = "Message";
|
||||
private Icon messageIcon = new ImageIcon("blue-ball.gif");
|
||||
private Object messageObject = new Date();
|
||||
private Component messageComponent = new SampleComponent();
|
||||
}
|
||||
|
||||
/**
|
||||
* A component with a painted surface
|
||||
*/
|
||||
|
||||
class SampleComponent extends JComponent
|
||||
{
|
||||
public void paintComponent(Graphics g)
|
||||
{
|
||||
Graphics2D g2 = (Graphics2D) g;
|
||||
Rectangle2D rect = new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1);
|
||||
g2.setPaint(Color.YELLOW);
|
||||
g2.fill(rect);
|
||||
g2.setPaint(Color.BLUE);
|
||||
g2.draw(rect);
|
||||
}
|
||||
|
||||
public Dimension getPreferredSize()
|
||||
{
|
||||
return new Dimension(10, 10);
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 925 B |
|
After Width: | Height: | Size: 527 B |
|
After Width: | Height: | Size: 925 B |
@@ -0,0 +1,89 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.33 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class RadioButtonTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
RadioButtonFrame frame = new RadioButtonFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a sample text label and radio buttons for selecting font sizes.
|
||||
*/
|
||||
class RadioButtonFrame extends JFrame
|
||||
{
|
||||
public RadioButtonFrame()
|
||||
{
|
||||
setTitle("RadioButtonTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add the sample text label
|
||||
|
||||
label = new JLabel("The quick brown fox jumps over the lazy dog.");
|
||||
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
|
||||
add(label, BorderLayout.CENTER);
|
||||
|
||||
// add the radio buttons
|
||||
|
||||
buttonPanel = new JPanel();
|
||||
group = new ButtonGroup();
|
||||
|
||||
addRadioButton("Small", 8);
|
||||
addRadioButton("Medium", 12);
|
||||
addRadioButton("Large", 18);
|
||||
addRadioButton("Extra large", 36);
|
||||
|
||||
add(buttonPanel, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a radio button that sets the font size of the sample text.
|
||||
* @param name the string to appear on the button
|
||||
* @param size the font size that this button sets
|
||||
*/
|
||||
public void addRadioButton(String name, final int size)
|
||||
{
|
||||
boolean selected = size == DEFAULT_SIZE;
|
||||
JRadioButton button = new JRadioButton(name, selected);
|
||||
group.add(button);
|
||||
buttonPanel.add(button);
|
||||
|
||||
// this listener sets the label font size
|
||||
|
||||
ActionListener listener = new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
// size refers to the final parameter of the addRadioButton
|
||||
// method
|
||||
label.setFont(new Font("Serif", Font.PLAIN, size));
|
||||
}
|
||||
};
|
||||
|
||||
button.addActionListener(listener);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 400;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JPanel buttonPanel;
|
||||
private ButtonGroup group;
|
||||
private JLabel label;
|
||||
|
||||
private static final int DEFAULT_SIZE = 12;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import java.awt.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
import javax.swing.event.*;
|
||||
|
||||
/**
|
||||
* @version 1.13 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class SliderTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
SliderTestFrame frame = new SliderTestFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with many sliders and a text field to show slider values.
|
||||
*/
|
||||
class SliderTestFrame extends JFrame
|
||||
{
|
||||
public SliderTestFrame()
|
||||
{
|
||||
setTitle("SliderTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
sliderPanel = new JPanel();
|
||||
sliderPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
|
||||
|
||||
// common listener for all sliders
|
||||
listener = new ChangeListener()
|
||||
{
|
||||
public void stateChanged(ChangeEvent event)
|
||||
{
|
||||
// update text field when the slider value changes
|
||||
JSlider source = (JSlider) event.getSource();
|
||||
textField.setText("" + source.getValue());
|
||||
}
|
||||
};
|
||||
|
||||
// add a plain slider
|
||||
|
||||
JSlider slider = new JSlider();
|
||||
addSlider(slider, "Plain");
|
||||
|
||||
// add a slider with major and minor ticks
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintTicks(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(5);
|
||||
addSlider(slider, "Ticks");
|
||||
|
||||
// add a slider that snaps to ticks
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintTicks(true);
|
||||
slider.setSnapToTicks(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(5);
|
||||
addSlider(slider, "Snap to ticks");
|
||||
|
||||
// add a slider with no track
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintTicks(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(5);
|
||||
slider.setPaintTrack(false);
|
||||
addSlider(slider, "No track");
|
||||
|
||||
// add an inverted slider
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintTicks(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(5);
|
||||
slider.setInverted(true);
|
||||
addSlider(slider, "Inverted");
|
||||
|
||||
// add a slider with numeric labels
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintTicks(true);
|
||||
slider.setPaintLabels(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(5);
|
||||
addSlider(slider, "Labels");
|
||||
|
||||
// add a slider with alphabetic labels
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintLabels(true);
|
||||
slider.setPaintTicks(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(5);
|
||||
|
||||
Dictionary<Integer, Component> labelTable = new Hashtable<Integer, Component>();
|
||||
labelTable.put(0, new JLabel("A"));
|
||||
labelTable.put(20, new JLabel("B"));
|
||||
labelTable.put(40, new JLabel("C"));
|
||||
labelTable.put(60, new JLabel("D"));
|
||||
labelTable.put(80, new JLabel("E"));
|
||||
labelTable.put(100, new JLabel("F"));
|
||||
|
||||
slider.setLabelTable(labelTable);
|
||||
addSlider(slider, "Custom labels");
|
||||
|
||||
// add a slider with icon labels
|
||||
|
||||
slider = new JSlider();
|
||||
slider.setPaintTicks(true);
|
||||
slider.setPaintLabels(true);
|
||||
slider.setSnapToTicks(true);
|
||||
slider.setMajorTickSpacing(20);
|
||||
slider.setMinorTickSpacing(20);
|
||||
|
||||
labelTable = new Hashtable<Integer, Component>();
|
||||
|
||||
// add card images
|
||||
|
||||
labelTable.put(0, new JLabel(new ImageIcon("nine.gif")));
|
||||
labelTable.put(20, new JLabel(new ImageIcon("ten.gif")));
|
||||
labelTable.put(40, new JLabel(new ImageIcon("jack.gif")));
|
||||
labelTable.put(60, new JLabel(new ImageIcon("queen.gif")));
|
||||
labelTable.put(80, new JLabel(new ImageIcon("king.gif")));
|
||||
labelTable.put(100, new JLabel(new ImageIcon("ace.gif")));
|
||||
|
||||
slider.setLabelTable(labelTable);
|
||||
addSlider(slider, "Icon labels");
|
||||
|
||||
// add the text field that displays the slider value
|
||||
|
||||
textField = new JTextField();
|
||||
add(sliderPanel, BorderLayout.CENTER);
|
||||
add(textField, BorderLayout.SOUTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a slider to the slider panel and hooks up the listener
|
||||
* @param s the slider
|
||||
* @param description the slider description
|
||||
*/
|
||||
public void addSlider(JSlider s, String description)
|
||||
{
|
||||
s.addChangeListener(listener);
|
||||
JPanel panel = new JPanel();
|
||||
panel.add(s);
|
||||
panel.add(new JLabel(description));
|
||||
sliderPanel.add(panel);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 350;
|
||||
public static final int DEFAULT_HEIGHT = 450;
|
||||
|
||||
private JPanel sliderPanel;
|
||||
private JTextField textField;
|
||||
private ChangeListener listener;
|
||||
}
|
||||
|
After Width: | Height: | Size: 208 B |
|
After Width: | Height: | Size: 388 B |
|
After Width: | Height: | Size: 393 B |
|
After Width: | Height: | Size: 262 B |
|
After Width: | Height: | Size: 393 B |
|
After Width: | Height: | Size: 262 B |
@@ -0,0 +1,75 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.40 2007-04-27
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class TextComponentTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
TextComponentFrame frame = new TextComponentFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with sample text components.
|
||||
*/
|
||||
class TextComponentFrame extends JFrame
|
||||
{
|
||||
public TextComponentFrame()
|
||||
{
|
||||
setTitle("TextComponentTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
final JTextField textField = new JTextField();
|
||||
final JPasswordField passwordField = new JPasswordField();
|
||||
|
||||
JPanel northPanel = new JPanel();
|
||||
northPanel.setLayout(new GridLayout(2, 2));
|
||||
northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
|
||||
northPanel.add(textField);
|
||||
northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
|
||||
northPanel.add(passwordField);
|
||||
|
||||
add(northPanel, BorderLayout.NORTH);
|
||||
|
||||
final JTextArea textArea = new JTextArea(8, 40);
|
||||
JScrollPane scrollPane = new JScrollPane(textArea);
|
||||
|
||||
add(scrollPane, BorderLayout.CENTER);
|
||||
|
||||
// add button to append text into the text area
|
||||
|
||||
JPanel southPanel = new JPanel();
|
||||
|
||||
JButton insertButton = new JButton("Insert");
|
||||
southPanel.add(insertButton);
|
||||
insertButton.addActionListener(new ActionListener()
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
textArea.append("User name: " + textField.getText() + " Password: "
|
||||
+ new String(passwordField.getPassword()) + "\n");
|
||||
}
|
||||
});
|
||||
|
||||
add(southPanel, BorderLayout.SOUTH);
|
||||
|
||||
// add a text area with scroll bars
|
||||
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 300;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import java.awt.*;
|
||||
import java.awt.event.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.13 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class ToolBarTest
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
ToolBarFrame frame = new ToolBarFrame();
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A frame with a toolbar and menu for color changes.
|
||||
*/
|
||||
class ToolBarFrame extends JFrame
|
||||
{
|
||||
public ToolBarFrame()
|
||||
{
|
||||
setTitle("ToolBarTest");
|
||||
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
|
||||
// add a panel for color change
|
||||
|
||||
panel = new JPanel();
|
||||
add(panel, BorderLayout.CENTER);
|
||||
|
||||
// set up actions
|
||||
|
||||
Action blueAction = new ColorAction("Blue", new ImageIcon("blue-ball.gif"), Color.BLUE);
|
||||
Action yellowAction = new ColorAction("Yellow", new ImageIcon("yellow-ball.gif"),
|
||||
Color.YELLOW);
|
||||
Action redAction = new ColorAction("Red", new ImageIcon("red-ball.gif"), Color.RED);
|
||||
|
||||
Action exitAction = new AbstractAction("Exit", new ImageIcon("exit.gif"))
|
||||
{
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
System.exit(0);
|
||||
}
|
||||
};
|
||||
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit");
|
||||
|
||||
// populate tool bar
|
||||
|
||||
JToolBar bar = new JToolBar();
|
||||
bar.add(blueAction);
|
||||
bar.add(yellowAction);
|
||||
bar.add(redAction);
|
||||
bar.addSeparator();
|
||||
bar.add(exitAction);
|
||||
add(bar, BorderLayout.NORTH);
|
||||
|
||||
// populate menu
|
||||
|
||||
JMenu menu = new JMenu("Color");
|
||||
menu.add(yellowAction);
|
||||
menu.add(blueAction);
|
||||
menu.add(redAction);
|
||||
menu.add(exitAction);
|
||||
JMenuBar menuBar = new JMenuBar();
|
||||
menuBar.add(menu);
|
||||
setJMenuBar(menuBar);
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 300;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
|
||||
private JPanel panel;
|
||||
|
||||
/**
|
||||
* The color action sets the background of the frame to a given color.
|
||||
*/
|
||||
class ColorAction extends AbstractAction
|
||||
{
|
||||
public ColorAction(String name, Icon icon, Color c)
|
||||
{
|
||||
putValue(Action.NAME, name);
|
||||
putValue(Action.SMALL_ICON, icon);
|
||||
putValue(Action.SHORT_DESCRIPTION, name + " background");
|
||||
putValue("Color", c);
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent event)
|
||||
{
|
||||
Color c = (Color) getValue("Color");
|
||||
panel.setBackground(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 925 B |
|
After Width: | Height: | Size: 865 B |
|
After Width: | Height: | Size: 527 B |
|
After Width: | Height: | Size: 925 B |
@@ -0,0 +1,3 @@
|
||||
<applet code="AppletApplication.class"
|
||||
width="180" height="180">
|
||||
</applet>
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* The applet viewer reads the tags below if you call it with appletviewer AppletApplication.java No
|
||||
* separate HTML file is required. <applet code="AppletApplication.class" width="200" height="200">
|
||||
* </applet>
|
||||
*/
|
||||
|
||||
import java.awt.EventQueue;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* It's an applet. It's an application. It's BOTH!
|
||||
* @version 1.32 2007-04-28
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class AppletApplication extends NotHelloWorldApplet
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
AppletFrame frame = new AppletFrame(new NotHelloWorldApplet());
|
||||
frame.setTitle("NotHelloWorldApplet");
|
||||
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
|
||||
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
frame.setVisible(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static final int DEFAULT_WIDTH = 200;
|
||||
public static final int DEFAULT_HEIGHT = 200;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import java.awt.*;
|
||||
import java.applet.*;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.32 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class AppletFrame extends JFrame implements AppletStub, AppletContext
|
||||
{
|
||||
public AppletFrame(Applet anApplet)
|
||||
{
|
||||
applet = anApplet;
|
||||
add(applet);
|
||||
applet.setStub(this);
|
||||
}
|
||||
|
||||
public void setVisible(boolean b)
|
||||
{
|
||||
if (b)
|
||||
{
|
||||
applet.init();
|
||||
super.setVisible(true);
|
||||
applet.start();
|
||||
}
|
||||
else
|
||||
{
|
||||
applet.stop();
|
||||
super.setVisible(false);
|
||||
applet.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// AppletStub methods
|
||||
public boolean isActive()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public URL getDocumentBase()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public URL getCodeBase()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public String getParameter(String name)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
public AppletContext getAppletContext()
|
||||
{
|
||||
return this;
|
||||
}
|
||||
|
||||
public void appletResize(int width, int height)
|
||||
{
|
||||
}
|
||||
|
||||
// AppletContext methods
|
||||
public AudioClip getAudioClip(URL url)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public Image getImage(URL url)
|
||||
{
|
||||
return Toolkit.getDefaultToolkit().getImage(url);
|
||||
}
|
||||
|
||||
public Applet getApplet(String name)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public Enumeration<Applet> getApplets()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public void showDocument(URL url)
|
||||
{
|
||||
}
|
||||
|
||||
public void showDocument(URL url, String target)
|
||||
{
|
||||
}
|
||||
|
||||
public void showStatus(String status)
|
||||
{
|
||||
}
|
||||
|
||||
public void setStream(String key, InputStream stream)
|
||||
{
|
||||
}
|
||||
|
||||
public InputStream getStream(String key)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public Iterator<String> getStreamKeys()
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
private Applet applet;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* The following HTML tags are required to display this applet in a browser: <applet
|
||||
* code="NotHelloWorldApplet.class" width="300" height="100"> </applet>
|
||||
*/
|
||||
|
||||
import java.awt.EventQueue;
|
||||
|
||||
import javax.swing.*;
|
||||
|
||||
/**
|
||||
* @version 1.22 2007-06-12
|
||||
* @author Cay Horstmann
|
||||
*/
|
||||
public class NotHelloWorldApplet extends JApplet
|
||||
{
|
||||
public void init()
|
||||
{
|
||||
EventQueue.invokeLater(new Runnable()
|
||||
{
|
||||
public void run()
|
||||
{
|
||||
JLabel label = new JLabel("Not a Hello, World applet", SwingConstants.CENTER);
|
||||
add(label);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
/* AUTOMATICALLY GENERATED ON Tue Apr 16 17:20:59 EDT 2002*/
|
||||
/* DO NOT EDIT */
|
||||
|
||||
grant {
|
||||
permission java.security.AllPermission;
|
||||
};
|
||||
|
||||