| Book Seven: Web Programming
- Creating Applets
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class PizzaApplet extends JApplet
{
private JButton buttonOK;
private JRadioButton small, medium, large;
private JCheckBox pepperoni, mushrooms, anchovies;
public void init()
{
this.setSize(320,200);
ButtonListener bl = new ButtonListener();
JPanel mainPanel = new JPanel();
JPanel sizePanel = new JPanel();
Border b1 = BorderFactory.createTitledBorder("Size");
sizePanel.setBorder(b1);
ButtonGroup sizeGroup = new ButtonGroup();
small = new JRadioButton("Small");
small.setSelected(true);
sizePanel.add(small);
sizeGroup.add(small);
medium = new JRadioButton("Medium");
sizePanel.add(medium);
sizeGroup.add(medium);
large = new JRadioButton("Large");
sizePanel.add(large);
sizeGroup.add(large);
mainPanel.add(sizePanel);
JPanel topPanel = new JPanel();
Border b2 = BorderFactory.createTitledBorder("Toppings");
topPanel.setBorder(b2);
pepperoni = new JCheckBox("Pepperoni");
topPanel.add(pepperoni);
mushrooms = new JCheckBox("Mushrooms");
topPanel.add(mushrooms);
anchovies = new JCheckBox("Anchovies");
topPanel.add(anchovies);
mainPanel.add(topPanel);
buttonOK = new JButton("OK");
buttonOK.addActionListener(bl);
mainPanel.add(buttonOK);
this.add(mainPanel);
this.setVisible(true);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == buttonOK)
{
String tops = "";
if (pepperoni.isSelected()) tops += "Pepperoni\n";
if (mushrooms.isSelected()) tops += "Mushrooms\n";
if (anchovies.isSelected()) tops += "Anchovies\n";
String msg = "You ordered a ";
if (small.isSelected()) msg += "small pizza with ";
if (medium.isSelected()) msg += "medium pizza with ";
if (large.isSelected()) msg += "large pizza with ";
if (tops.equals("")) msg += "no toppings.";
else msg += "the following toppings:\n" + tops;
JOptionPane.showMessageDialog(buttonOK, msg, "Your Order", JOptionPane.INFORMATION_MESSAGE);
pepperoni.setSelected(false);
mushrooms.setSelected(false);
anchovies.setSelected(false);
small.setSelected(true);
}
}
}
}
It comes with an HTML file:
<html>
<head>
<title>The Pizza Applet</title>
</head>
<body>
<H1>Welcome to the Pizza Applet!</H1>
<APPLET code="PizzaApplet" width="300" height="180">
Sorry, your browser isn't able to run Java applets.
</APPLET>
</body>
</html>
- Creating Servlets
We've installed Tomcat, and have started discussing JSPs and servlets.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>HelloWorld</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body>");
out.println("</html>");
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String msg = getGreeting();
out.println("<html>");
out.println("<head>");
out.println("<title>HelloWorld Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println(msg);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
doGet(request, response);
}
private String getGreeting()
{
String msg = "";
int rand = (int)(Math.random() * (6)) + 1;
switch (rand)
{
case 1:
return "Hello, World!";
case 2:
return "Greetings!";
case 3:
return "Felicitations!";
case 4:
return "Yo, Dude!";
case 5:
return "Whasssuuuup?";
case 6:
return "Hark!";
}
return null;
}
}
We need to talk about deploying too (webapps, contexts, web.xml and so on).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InputServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
String name = request.getParameter("Name");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Input Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Hello " + name);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
doGet(request, response);
}
}
Pass the input to the above via the URL or an HTML form.
- Using Java Server Pages
Good, well-written descriptions of what you need to know.
<html>
<%@ page import="java.text.*" %>
<%@ page import="java.util.*" %>
<head>
<title>Date JSP</title>
</head>
<body>
<h1>
Today is
<%
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL);
Date today = new Date();
String msg = df.format(today);
out.println(msg);
%>
</h1>
<h1>Have a nice day!</h1>
</body>
</html>
This is like PHP:
<html>
<head>
<title>Can't
</head>
<body>
<% for (int i = 0; i < 12; i++)
{
%>
All work and no play makes Jack a dull boy.<br>
<%
}
%>
</body>
</html>
- Using JavaBeans
Skip this chapter.
|
| Book Eight: Files and Databases
- Working with Files
This is a traditionally useful chapter. Quick program to look at:
import java.io.*;
public class ListDirectory
{
public static void main(String[] args)
{
String path = args[0];
File dir = new File(path);
if (dir.isDirectory())
{
File[] files = dir.listFiles();
for (File f : files)
{
System.out.println(f.getName());
}
}
else
System.out.println("Not a directory.");
}
}
- Using File Streams
import java.io.*;
import java.text.NumberFormat;
public class ReadFile
{
public static void main(String[] args)
{
NumberFormat cf = NumberFormat.getCurrencyInstance();
BufferedReader in = getReader("movies.txt");
Movie movie = readMovie(in);
while (movie != null)
{
String msg = Integer.toString(movie.year);
msg += ": " + movie.title;
msg += " (" + cf.format(movie.price) + ")";
System.out.println(msg);
movie = readMovie(in);
}
}
private static BufferedReader getReader(String name)
{
BufferedReader in = null;
try
{
File file = new File(name);
in = new BufferedReader(
new FileReader(file) );
}
catch (FileNotFoundException e)
{
System.out.println("The file doesn't exist.");
System.exit(0);
}
catch (IOException e)
{
System.out.println("I/O Error");
System.exit(0);
}
return in;
}
private static Movie readMovie(BufferedReader in)
{
String title;
int year;
double price;
String line = "";
String[] data;
try
{
line = in.readLine();
}
catch (IOException e)
{
System.out.println("I/O Error");
System.exit(0);
}
if (line == null)
return null;
else
{
data = line.split("\t");
title = data[0];
year = Integer.parseInt(data[1]);
price = Double.parseDouble(data[2]);
return new Movie(title, year, price);
}
}
private static class Movie
{
public String title;
public int year;
public double price;
public Movie(String title, int year, double price)
{
this.title = title;
this.year = year;
this.price = price;
}
}
}
This needs the following file (movies.txt):
It's a Wonderful Life [tab] from book1946 [tab] from book14.95
The Great Race [tab] from book1965 [tab] from book12.95
Young Frankenstein [tab] from book1974 [tab] from book16.95
The Return of the Pink Panther [tab] from book1975.11.95
Star Wars [tab] from book1977 [tab] from book17.95
The Princess Bride [tab] from book1987 [tab] from book16.95
Glory [tab] from book1989 [tab] from book14.95
Apollo 13 [tab] from book1995 [tab] from book19.95
The Game [tab] from book1997 [tab] from book14.95
The Lord of the Rings: The Fellowship of the Ring [tab] from book2001 [tab] from book19.95
By [tab] I am indicating the actual tab character.
There's much more to this chapter, but this will suffice for this review.
- Database for $100, Please
This chapter is mostly about SQL and database design:
drop database movies;
create database movies;
use movies;
create table movie (
id int not null auto_increment,
title varchar(50),
year int,
price decimal(8,2),
primary key(id)
);
insert into movie (title, year, price) values ("It's ...", ..., ...);
insert into movie (title, year, price) values ("The Great Race", 1965, 12.95);
insert into movie (title, year, price) values ("Young Frankenstein", 1974, 16.95);
insert into movie (title, year, price) values ("The Return of the Pink Panther", 1975, 11.95);
insert into movie (title, year, price) values ("Star Wars", 1977, 17.95);
insert into movie (title, year, price) values ("The Princess Bride", 1987, 16.95);
insert into movie (title, year, price) values ("Glory", 1989, 14.95);
insert into movie (title, year, price) values ("Apollo 13", 1995, 19.95);
insert into movie (title, year, price) values ("The Game", 1997, 14.95);
insert into movie (title, year, price) values ("The Lord of the Rings: The Fellowship of the Ring", 2001, 19.95);
Nothing else from this chapter will be highlighted here, but there's more you can benefit from if you read it.
- Using JDBC to Connect to a Database
We'll have our own examples.
- Working with XML
Skip this chapter, but know it's useful and interesting.
Book Nine: Fun and Games
- Fun with Fonts and Colors
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Fonts extends JFrame
{
public static void main(String [] args)
{
new Fonts();
}
private JLabel sampleText;
private JComboBox fontComboBox;
private JComboBox sizeComboBox;
private JCheckBox boldCheck, italCheck;
private String[] fonts;
public Fonts()
{
this.setSize(500,150);
this.setTitle("Fun with Fonts ");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FontListener fl = new FontListener();
sampleText = new JLabel(
"All work and no play makes Jack a dull boy");
this.add(sampleText, BorderLayout.NORTH);
GraphicsEnvironment g;
g = GraphicsEnvironment
.getLocalGraphicsEnvironment();
fonts = g.getAvailableFontFamilyNames();
JPanel controlPanel = new JPanel();
fontComboBox = new JComboBox(fonts);
fontComboBox.addActionListener(fl);
controlPanel.add(new JLabel("Family: "));
controlPanel.add(fontComboBox);
Integer[] sizes = {7, 8, 9, 10, 11, 12,
14, 18, 20, 22, 24, 36};
sizeComboBox = new JComboBox(sizes);
sizeComboBox.setSelectedIndex(5);
sizeComboBox.addActionListener(fl);
controlPanel.add(new JLabel("Size: "));
controlPanel.add(sizeComboBox);
boldCheck = new JCheckBox("Bold");
boldCheck.addActionListener(fl);
controlPanel.add(boldCheck);
italCheck = new JCheckBox("Ital");
italCheck.addActionListener(fl);
controlPanel.add(italCheck);
this.add(controlPanel, BorderLayout.SOUTH);
fl.updateText();
this.setVisible(true);
}
private class FontListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
updateText();
}
public void updateText()
{
String name = (String) fontComboBox.getSelectedItem();
Integer size = (Integer)sizeComboBox.getSelectedItem();
int style;
if ( boldCheck.isSelected()
&& italCheck.isSelected())
style = Font.BOLD | Font.ITALIC;
else if (boldCheck.isSelected())
style = Font.BOLD;
else if (italCheck.isSelected())
style = Font.ITALIC;
else
style = Font.PLAIN;
Font f = new Font(name, style,
size.intValue());
sampleText.setFont(f);
}
}
}
Can you walk [through] the code above?
Hopefully that's not too hard.
There's more in the chapter.
- Drawing Shapes
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
public class DrawingBoard extends JFrame
{
public static void main(String [] args)
{
new DrawingBoard();
}
public DrawingBoard()
{
this.setSize(300, 300);
this.setTitle("The Drawing Board");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(new PaintSurface(), BorderLayout.CENTER);
this.setVisible(true);
}
private class PaintSurface extends JComponent
{
ArrayList<Shape> shapes = new ArrayList<Shape>();
Point startDrag, endDrag;
public PaintSurface()
{
this.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
startDrag = new Point(e.getX(), e.getY());
endDrag = startDrag;
repaint();
}
public void mouseReleased(MouseEvent e)
{
Shape r = makeRectangle(
startDrag.x, startDrag.y,
e.getX(), e.getY());
shapes.add(r);
startDrag = null;
endDrag = null;
repaint();
}
} );
this.addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
endDrag = new Point(e.getX(), e.getY());
repaint();
}
} );
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
// turn on antialiasing
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// draw background grid
g2.setPaint(Color.LIGHT_GRAY);
for (int i = 0; i < getSize().width; i += 10)
{
Shape line = new Line2D.Float(
i, 0, i, getSize().height);
g2.draw(line);
}
for (int i = 0; i < getSize().height; i += 10)
{
Shape line = new Line2D.Float(
0, i, getSize().width, i);
g2.draw(line);
}
// draw the shapes
Color[] colors = {Color.RED, Color.BLUE,
Color.PINK, Color.YELLOW,
Color.MAGENTA, Color.CYAN };
int colorIndex = 0;
g2.setStroke(new BasicStroke(2));
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, 0.50f));
for (Shape s : shapes)
{
g2.setPaint(Color.BLACK);
g2.draw(s);
g2.setPaint(colors[(colorIndex++)%6]);
g2.fill(s);
}
// paint the temporary rectangle
if (startDrag != null && endDrag != null)
{
g2.setPaint(Color.LIGHT_GRAY);
Shape r = makeRectangle(
startDrag.x, startDrag.y,
endDrag.x, endDrag.y);
g2.draw(r);
}
}
private Rectangle2D.Float makeRectangle(
int x1, int y1, int x2, int y2)
{
int x = Math.min(x1, x2);
int y = Math.min(y1, y2);
int width = Math.abs(x1 - x2);
int height = Math.abs(y1 - y2);
return new Rectangle2D.Float(
x, y, width, height);
}
}
}
This is not very surprising.
- Using Images and Sound
import javax.swing.*;
public class PictureApp extends JFrame
{
public static void main(String [] args)
{
new PictureApp();
}
public PictureApp()
{
this.setTitle("Picture Application");
this.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
ImageIcon pic = new ImageIcon("HalfDome.jpg");
panel1.add(new JLabel(pic));
this.add(panel1);
this.pack();
this.setVisible(true);
}
}
Get your own picture.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class PictureFrame extends JFrame
implements ActionListener
{
Image img;
JButton getPictureButton;
public static void main(String [] args)
{
new PictureFrame();
}
public PictureFrame()
{
this.setSize(300, 300);
this.setTitle("Picture Frame Application");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel picPanel = new PicturePanel();
this.add(picPanel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
getPictureButton = new JButton("Get Picture");
getPictureButton.addActionListener(this);
buttonPanel.add(getPictureButton);
this.add(buttonPanel, BorderLayout.SOUTH);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String file = getImageFile();
if (file != null)
{
Toolkit kit = Toolkit.getDefaultToolkit();
img = kit.getImage(file);
img = img.getScaledInstance(
300, -1, Image.SCALE_SMOOTH);
this.repaint();
}
}
private String getImageFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new ImageFilter());
int result = fc.showOpenDialog(null);
File file = null;
if (result == JFileChooser.APPROVE_OPTION)
{
file = fc.getSelectedFile();
return file.getPath();
}
else
return null;
}
private class PicturePanel extends JPanel
{
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, this);
}
}
private class ImageFilter
extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
if (f.isDirectory())
return true;
String name = f.getName();
if (name.matches(".*((.jpg)|(.gif)|(.png))"))
return true;
else
return false;
}
public String getDescription()
{
return "Image files (*.jpg, *.gif, *.png)";
}
}
}
A more evolved picture browser...
(I'm skipping sound for now).
- Animation and Game Programming
/* <applet code=NotPong.class width=300 height=300>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.concurrent.*;
public class NotPong extends JApplet
{
public static final int WIDTH = 400;
public static final int HEIGHT = 400;
private PaintSurface canvas;
public void init()
{
this.setSize(WIDTH, HEIGHT);
canvas = new PaintSurface();
this.add(canvas, BorderLayout.CENTER);
ScheduledThreadPoolExecutor executor =
new ScheduledThreadPoolExecutor(3);
executor.scheduleAtFixedRate(new AnimationThread(this),
0L, 20L, TimeUnit.MILLISECONDS);
}
}
class AnimationThread implements Runnable
{
JApplet c;
public AnimationThread(JApplet c)
{
this.c = c;
}
public void run()
{
c.repaint();
}
}
class PaintSurface extends JComponent
{
int paddle_x = 0;
int paddle_y = 360;
int score = 0;
float english = 1.0f;
Ball ball;
Color[] color = {Color.RED, Color.ORANGE,
Color.MAGENTA, Color.ORANGE,
Color.CYAN, Color.BLUE};
int colorIndex;
public PaintSurface()
{
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
if (e.getX() - 30 - paddle_x > 5)
english = 1.5f;
else if (e.getX() - 30 - paddle_x < -5)
english = -1.5f;
else
english = 1.0f;
paddle_x = e.getX() - 30;
}
} );
ball = new Ball(20);
}
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Shape paddle = new Rectangle2D.Float(
paddle_x, paddle_y, 60, 8);
g2.setColor(color[colorIndex % 6]);
if (ball.intersects(paddle_x, paddle_y, 60, 8)
&& ball.y_speed > 0)
{
ball.y_speed = -ball.y_speed;
ball.x_speed = (int)(ball.x_speed * english);
if (english != 1.0f)
colorIndex++;
score += Math.abs(ball.x_speed * 10);
}
if (ball.getY() + ball.getHeight()
>= NotPong.HEIGHT)
{
ball = new Ball(20);
score -= 1000;
colorIndex = 0;
}
ball.move();
g2.fill(ball);
g2.setColor(Color.BLACK);
g2.fill(paddle);
g2.drawString("Score: " + score, 250, 20);
}
}
class Ball extends Ellipse2D.Float
{
public int x_speed, y_speed;
private int d;
private int width = NotPong.WIDTH;
private int height = NotPong.HEIGHT;
public Ball(int diameter)
{
super((int)(Math.random() * (NotPong.WIDTH - 20) + 1),
0, diameter, diameter);
this.d = diameter;
this.x_speed = (int)(Math.random() * 5 + 5);
this.y_speed = (int)(Math.random() * 5 + 5);
}
public void move()
{
if (super.x < 0 || super.x > width - d)
x_speed = -x_speed;
if (super.y < 0 || super.y > height - d)
y_speed = -y_speed;
super.x += x_speed;
super.y += y_speed;
}
}
That's it.
|