控制台程序。

在Sketcher中创建形状时,并不知道应该以什么顺序创建不同类型的形状,这完全取决于使用Sketcher程序生成草图的人。因此需要绘制形状,对它们执行其他操作而不必知道图形是什么。当然,多态性在这里是有帮助的。

最简单的方法可能是为Sketcher形状类定义通用的基类,并在每个形状类中包含一个成员来存储某种java.awt.geom形状对象,接着把对形状类对象的引用存储为基类类型以获得多态行为。

1、通用基类:

 import java.awt.*;
import java.io.Serializable;
import static Constants.SketcherConstants.*;
import java.awt.geom.*; public abstract class Element implements Serializable{ public Element(Point position, Color color) {
this.position = new Point(position);
this.color = color;
} protected Element(Color color) {
this.color = color;
} // Returns the color of the element
public Color getColor() {
return color;
} // Returns the position of the element
public Point getPosition() {
return position;
} // Returns the bounding rectangle enclosing an element boundary
public java.awt.Rectangle getBounds() {
return bounds;
} // Create a new element
public static Element createElement(int type, Color color, Point start, Point end) {
switch(type) {
case LINE:
return new Element.Line(start, end, color);
case RECTANGLE:
return new Rectangle(start, end, color);
case CIRCLE:
return new Circle(start, end, color);
case CURVE:
return new Curve(start, end, color);
default:
assert false; // We should never get to here
}
return null;
} // Nested class defining a line
public static class Line extends Element {
public Line(Point start, Point end, Color color) {
super(start, color);
line = new Line2D.Double(origin.x, origin.y, end.x - position.x, end.y - position.y);
bounds = new java.awt.Rectangle(
Math.min(start.x ,end.x), Math.min(start.y, end.y),
Math.abs(start.x - end.x)+1, Math.abs(start.y - end.y)+1);
} // Change the end point for the line
public void modify(Point start, Point last) {
line.x2 = last.x - position.x;
line.y2 = last.y - position.y;
bounds = new java.awt.Rectangle(
Math.min(start.x ,last.x), Math.min(start.y, last.y),
Math.abs(start.x - last.x)+1, Math.abs(start.y - last.y)+1);
} // Display the line
public void draw(Graphics2D g2D) {
g2D.setPaint(color); // Set the line color
g2D.translate(position.x, position.y); // Move context origin
g2D.draw(line); // Draw the line
g2D.translate(-position.x, -position.y); // Move context origin back
}
private Line2D.Double line;
private final static long serialVersionUID = 1001L;
} // Nested class defining a rectangle
public static class Rectangle extends Element {
public Rectangle(Point start, Point end, Color color) {
super(new Point(Math.min(start.x, end.x), Math.min(start.y, end.y)), color);
rectangle = new Rectangle2D.Double(
origin.x, origin.y, // Top-left corner
Math.abs(start.x - end.x), Math.abs(start.y - end.y)); // Width & height
bounds = new java.awt.Rectangle(
Math.min(start.x ,end.x), Math.min(start.y, end.y),
Math.abs(start.x - end.x)+1, Math.abs(start.y - end.y)+1);
} // Display the rectangle
public void draw(Graphics2D g2D) {
g2D.setPaint(color); // Set the rectangle color
g2D.translate(position.x, position.y); // Move context origin
g2D.draw(rectangle); // Draw the rectangle
g2D.translate(-position.x, -position.y); // Move context origin back
} // Method to redefine the rectangle
public void modify(Point start, Point last) {
bounds.x = position.x = Math.min(start.x, last.x);
bounds.y = position.y = Math.min(start.y, last.y);
rectangle.width = Math.abs(start.x - last.x);
rectangle.height = Math.abs(start.y - last.y);
bounds.width = (int)rectangle.width +1;
bounds.height = (int)rectangle.height + 1;
} private Rectangle2D.Double rectangle;
private final static long serialVersionUID = 1001L;
} // Nested class defining a circle
public static class Circle extends Element {
public Circle(Point center, Point circum, Color color) {
super(color); // Radius is distance from center to circumference
double radius = center.distance(circum);
position = new Point(center.x - (int)radius, center.y - (int)radius);
circle = new Ellipse2D.Double(origin.x, origin.y, 2.*radius, 2.*radius);
bounds = new java.awt.Rectangle(position.x, position.y,
1 + (int)circle.width, 1+(int)circle.height);
} // Display the circle
public void draw(Graphics2D g2D) {
g2D.setPaint(color); // Set the circle color
g2D.translate(position.x, position.y); // Move context origin
g2D.draw(circle); // Draw the circle
g2D.translate(-position.x, -position.y); // Move context origin back
} // Recreate this circle
public void modify(Point center, Point circum) {
double radius = center.distance(circum);
circle.width = circle.height = 2*radius;
position.x = center.x - (int)radius;
position.y = center.y - (int)radius;
bounds = new java.awt.Rectangle(position.x, position.y,
1 + (int)circle.width, 1+(int)circle.height);
} private Ellipse2D.Double circle;
private final static long serialVersionUID = 1001L;
} // Nested class defining a curve
public static class Curve extends Element {
public Curve(Point start, Point next, Color color) {
super(start, color);
curve = new GeneralPath();
curve.moveTo(origin.x, origin.y); // Set current position as origin
curve.lineTo(next.x - position.x, next.y - position.y); // Add segment
bounds = new java.awt.Rectangle(
Math.min(start.x ,next.x), Math.min(start.y, next.y),
Math.abs(next.x - start.x)+1, Math.abs(next.y - start.y)+1);
} // Add another segment
public void modify(Point start, Point next) {
curve.lineTo(next.x - position.x, next.y - position.y); // Add segment
bounds.add(new java.awt.Rectangle(next.x,next.y, 1, 1)); // Extend bounds
} // Display the curve
public void draw(Graphics2D g2D) {
g2D.setPaint(color); // Set the curve color
g2D.translate(position.x, position.y); // Move context origin
g2D.draw(curve); // Draw the curve
g2D.translate(-position.x, -position.y); // Move context origin back
} private GeneralPath curve;
private final static long serialVersionUID = 1001L;
} // Abstract Element class methods
public abstract void draw(Graphics2D g2D);
public abstract void modify(Point start, Point last); // Element class fields
protected Point position; // Position of a shape
protected Color color; // Color of a shape
protected java.awt.Rectangle bounds; // Bounding rectangle
protected static final Point origin = new Point(); // Origin for elements
private final static long serialVersionUID = 1001L;
}

2、实现了链表和Iterable<Element>接口的模型:

 import java.io.Serializable;
import java.util.*; public class SketcherModel extends Observable implements Serializable, Iterable<Element> { //Remove an element from the sketch
public boolean remove(Element element) {
boolean removed = elements.remove(element);
if(removed) {
setChanged();
notifyObservers(element.getBounds());
}
return removed;
} //Add an element to the sketch
public void add(Element element) {
elements.add(element);
setChanged();
notifyObservers(element.getBounds());
} // Get iterator for sketch elements
public Iterator<Element> iterator() {
return elements.iterator();
} protected LinkedList<Element> elements = new LinkedList<>();
private final static long serialVersionUID = 1001L;
}

3、视图:

 import javax.swing.JComponent;
import java.util.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.event.MouseInputAdapter; @SuppressWarnings("serial")
public class SketcherView extends JComponent implements Observer {
public SketcherView(Sketcher theApp) {
this.theApp = theApp;
MouseHandler handler = new MouseHandler(); // create the mouse listener
addMouseListener(handler); // Listen for button events
addMouseMotionListener(handler); // Listen for motion events
} // Method called by Observable object when it changes
public void update(Observable o, Object rectangle) {
if(rectangle != null) {
repaint((java.awt.Rectangle)rectangle);
} else {
repaint();
}
} // Method to draw on the view
@Override
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D)g; // Get a 2D device context
for(Element element: theApp.getModel()) { // For each element in the model
element.draw(g2D); // ...draw the element
}
} class MouseHandler extends MouseInputAdapter {
@Override
public void mousePressed(MouseEvent e) {
start = e.getPoint(); // Save the cursor position in start
buttonState = e.getButton(); // Record which button was pressed
if(buttonState == MouseEvent.BUTTON1) {
g2D = (Graphics2D)getGraphics(); // Get graphics context
g2D.setXORMode(getBackground()); // Set XOR mode
}
} @Override
public void mouseDragged(MouseEvent e) {
last = e.getPoint(); // Save cursor position if(buttonState == MouseEvent.BUTTON1) {
if(tempElement == null) { // Is there an element?
tempElement = Element.createElement( // No, so create one
theApp.getWindow().getElementType(),
theApp.getWindow().getElementColor(),
start, last);
} else {
tempElement.draw(g2D); // Yes draw to erase it
tempElement.modify(start, last); // Now modify it
}
tempElement.draw(g2D); // and draw it
}
} @Override
public void mouseReleased(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
buttonState = MouseEvent.NOBUTTON; // Reset the button state if(tempElement != null) { // If there is an element...
theApp.getModel().add(tempElement); // ...add it to the model...
tempElement = null; // ...and reset the field
}
if(g2D != null) { // If there's a graphics context
g2D.dispose(); // ...release the resource...
g2D = null; // ...and reset field to null
}
start = last = null; // Remove any points
}
} @Override
public void mouseEntered(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
} @Override
public void mouseExited(MouseEvent e) {
setCursor(Cursor.getDefaultCursor());
} private Point start; // Stores cursor position on press
private Point last; // Stores cursor position on drag
private Element tempElement = null; // Stores a temporary element
private int buttonState = MouseEvent.NOBUTTON; // Records button state
private Graphics2D g2D = null; // Temporary graphics context
} private Sketcher theApp; // The application object
}

4、窗口框架:

 // Frame for the Sketcher application
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.awt.*; import static java.awt.event.InputEvent.*;
import static java.awt.AWTEvent.*;
import static java.awt.Color.*;
import static Constants.SketcherConstants.*;
import static javax.swing.Action.*; @SuppressWarnings("serial")
public class SketcherFrame extends JFrame {
// Constructor
public SketcherFrame(String title, Sketcher theApp) {
setTitle(title); // Set the window title
this.theApp = theApp; // Save app. object reference
setJMenuBar(menuBar); // Add the menu bar to the window
setDefaultCloseOperation(EXIT_ON_CLOSE); // Default is exit the application createFileMenu(); // Create the File menu
createElementMenu(); // Create the element menu
createColorMenu(); // Create the element menu
createToolbar();
toolBar.setRollover(true);
getContentPane().add(toolBar, BorderLayout.NORTH);
} // Create File menu item actions
private void createFileMenuActions() {
newAction = new FileAction("New", 'N', CTRL_DOWN_MASK);
openAction = new FileAction("Open", 'O', CTRL_DOWN_MASK);
closeAction = new FileAction("Close");
saveAction = new FileAction("Save", 'S', CTRL_DOWN_MASK);
saveAsAction = new FileAction("Save As...");
printAction = new FileAction("Print", 'P', CTRL_DOWN_MASK);
exitAction = new FileAction("Exit", 'X', CTRL_DOWN_MASK); // Initialize the array
FileAction[] actions = {openAction, closeAction, saveAction, saveAsAction, printAction, exitAction};
fileActions = actions; // Add toolbar icons
newAction.putValue(LARGE_ICON_KEY, NEW24);
openAction.putValue(LARGE_ICON_KEY, OPEN24);
saveAction.putValue(LARGE_ICON_KEY, SAVE24);
saveAsAction.putValue(LARGE_ICON_KEY, SAVEAS24);
printAction.putValue(LARGE_ICON_KEY, PRINT24); // Add menu item icons
newAction.putValue(SMALL_ICON, NEW16);
openAction.putValue(SMALL_ICON, OPEN16);
saveAction.putValue(SMALL_ICON, SAVE16);
saveAsAction.putValue(SMALL_ICON,SAVEAS16);
printAction.putValue(SMALL_ICON, PRINT16); // Add tooltip text
newAction.putValue(SHORT_DESCRIPTION, "Create a new sketch");
openAction.putValue(SHORT_DESCRIPTION, "Read a sketch from a file");
closeAction.putValue(SHORT_DESCRIPTION, "Close the current sketch");
saveAction.putValue(SHORT_DESCRIPTION, "Save the current sketch to file");
saveAsAction.putValue(SHORT_DESCRIPTION, "Save the current sketch to a new file");
printAction.putValue(SHORT_DESCRIPTION, "Print the current sketch");
exitAction.putValue(SHORT_DESCRIPTION, "Exit Sketcher");
} // Create the File menu
private void createFileMenu() {
JMenu fileMenu = new JMenu("File"); // Create File menu
fileMenu.setMnemonic('F'); // Create shortcut
createFileMenuActions(); // Create Actions for File menu item // Construct the file drop-down menu
fileMenu.add(newAction); // New Sketch menu item
fileMenu.add(openAction); // Open sketch menu item
fileMenu.add(closeAction); // Close sketch menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(saveAction); // Save sketch to file
fileMenu.add(saveAsAction); // Save As menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(printAction); // Print sketch menu item
fileMenu.addSeparator(); // Add separator
fileMenu.add(exitAction); // Print sketch menu item
menuBar.add(fileMenu); // Add the file menu
} // Create Element menu actions
private void createElementTypeActions() {
lineAction = new TypeAction("Line", LINE, 'L', CTRL_DOWN_MASK);
rectangleAction = new TypeAction("Rectangle", RECTANGLE, 'R', CTRL_DOWN_MASK);
circleAction = new TypeAction("Circle", CIRCLE,'C', CTRL_DOWN_MASK);
curveAction = new TypeAction("Curve", CURVE,'U', CTRL_DOWN_MASK); // Initialize the array
TypeAction[] actions = {lineAction, rectangleAction, circleAction, curveAction};
typeActions = actions; // Add toolbar icons
lineAction.putValue(LARGE_ICON_KEY, LINE24);
rectangleAction.putValue(LARGE_ICON_KEY, RECTANGLE24);
circleAction.putValue(LARGE_ICON_KEY, CIRCLE24);
curveAction.putValue(LARGE_ICON_KEY, CURVE24); // Add menu item icons
lineAction.putValue(SMALL_ICON, LINE16);
rectangleAction.putValue(SMALL_ICON, RECTANGLE16);
circleAction.putValue(SMALL_ICON, CIRCLE16);
curveAction.putValue(SMALL_ICON, CURVE16); // Add tooltip text
lineAction.putValue(SHORT_DESCRIPTION, "Draw lines");
rectangleAction.putValue(SHORT_DESCRIPTION, "Draw rectangles");
circleAction.putValue(SHORT_DESCRIPTION, "Draw circles");
curveAction.putValue(SHORT_DESCRIPTION, "Draw curves");
} // Create the Elements menu
private void createElementMenu() {
createElementTypeActions();
elementMenu = new JMenu("Elements"); // Create Elements menu
elementMenu.setMnemonic('E'); // Create shortcut
createRadioButtonDropDown(elementMenu, typeActions, lineAction);
menuBar.add(elementMenu); // Add the element menu
} // Create Color menu actions
private void createElementColorActions() {
redAction = new ColorAction("Red", RED, 'R', CTRL_DOWN_MASK|ALT_DOWN_MASK);
yellowAction = new ColorAction("Yellow", YELLOW, 'Y', CTRL_DOWN_MASK|ALT_DOWN_MASK);
greenAction = new ColorAction("Green", GREEN, 'G', CTRL_DOWN_MASK|ALT_DOWN_MASK);
blueAction = new ColorAction("Blue", BLUE, 'B', CTRL_DOWN_MASK|ALT_DOWN_MASK); // Initialize the array
ColorAction[] actions = {redAction, greenAction, blueAction, yellowAction};
colorActions = actions; // Add toolbar icons
redAction.putValue(LARGE_ICON_KEY, RED24);
greenAction.putValue(LARGE_ICON_KEY, GREEN24);
blueAction.putValue(LARGE_ICON_KEY, BLUE24);
yellowAction.putValue(LARGE_ICON_KEY, YELLOW24); // Add menu item icons
redAction.putValue(SMALL_ICON, RED16);
blueAction.putValue(SMALL_ICON, BLUE16);
greenAction.putValue(SMALL_ICON, GREEN16);
yellowAction.putValue(SMALL_ICON, YELLOW16); // Add tooltip text
redAction.putValue(SHORT_DESCRIPTION, "Draw in red");
blueAction.putValue(SHORT_DESCRIPTION, "Draw in blue");
greenAction.putValue(SHORT_DESCRIPTION, "Draw in green");
yellowAction.putValue(SHORT_DESCRIPTION, "Draw in yellow");
} // Create the Color menu
private void createColorMenu() {
createElementColorActions();
colorMenu = new JMenu("Color"); // Create Elements menu
colorMenu.setMnemonic('C'); // Create shortcut
createRadioButtonDropDown(colorMenu, colorActions, blueAction);
menuBar.add(colorMenu); // Add the color menu
} // Menu creation helper
private void createRadioButtonDropDown(JMenu menu, Action[] actions, Action selected) {
ButtonGroup group = new ButtonGroup();
JRadioButtonMenuItem item = null;
for(Action action : actions) {
group.add(menu.add(item = new JRadioButtonMenuItem(action)));
if(action == selected) {
item.setSelected(true); // This is default selected
}
}
} // Create toolbar buttons on the toolbar
private void createToolbar() {
for(FileAction action: fileActions){
if(action != exitAction && action != closeAction)
addToolbarButton(action); // Add the toolbar button
}
toolBar.addSeparator(); // Create Color menu buttons
for(ColorAction action:colorActions){
addToolbarButton(action); // Add the toolbar button
} toolBar.addSeparator(); // Create Elements menu buttons
for(TypeAction action:typeActions){
addToolbarButton(action); // Add the toolbar button
}
} // Create and add a toolbar button
private void addToolbarButton(Action action) {
JButton button = new JButton(action); // Create from Action
button.setBorder(BorderFactory.createCompoundBorder( // Add button border
new EmptyBorder(2,5,5,2), // Outside border
BorderFactory.createRaisedBevelBorder())); // Inside border
button.setHideActionText(true); // No label on the button
toolBar.add(button); // Add the toolbar button
} // Return the current drawing color
public Color getElementColor() {
return elementColor;
} // Return the current element type
public int getElementType() {
return elementType;
} // Set radio button menu checks
private void setChecks(JMenu menu, Object eventSource) {
if(eventSource instanceof JButton){
JButton button = (JButton)eventSource;
Action action = button.getAction();
for(int i = 0 ; i<menu.getItemCount() ; ++i) {
JMenuItem item = menu.getItem(i);
item.setSelected(item.getAction() == action);
}
}
} // Inner class defining Action objects for File menu items
class FileAction extends AbstractAction {
// Create action with a name
FileAction(String name) {
super(name);
} // Create action with a name and accelerator
FileAction(String name, char ch, int modifiers) {
super(name);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers)); // Now find the character to underline
int index = name.toUpperCase().indexOf(ch);
if(index != -1) {
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
}
} // Event handler
public void actionPerformed(ActionEvent e) {
// You will add action code here eventually...
}
} // Inner class defining Action objects for Element type menu items
class TypeAction extends AbstractAction {
// Create action with just a name property
TypeAction(String name, int typeID) {
super(name);
this.typeID = typeID;
} // Create action with a name and an accelerator
private TypeAction(String name,int typeID, char ch, int modifiers) {
this(name, typeID);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers)); // Now find the character to underline
int index = name.toUpperCase().indexOf(ch);
if(index != -1) {
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
}
} public void actionPerformed(ActionEvent e) {
elementType = typeID;
setChecks(elementMenu, e.getSource());
} private int typeID;
} // Handles color menu items
class ColorAction extends AbstractAction {
// Create an action with a name and a color
public ColorAction(String name, Color color) {
super(name);
this.color = color;
} // Create an action with a name, a color, and an accelerator
public ColorAction(String name, Color color, char ch, int modifiers) {
this(name, color);
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(ch, modifiers)); // Now find the character to underline
int index = name.toUpperCase().indexOf(ch);
if(index != -1) {
putValue(DISPLAYED_MNEMONIC_INDEX_KEY, index);
}
} public void actionPerformed(ActionEvent e) {
elementColor = color;
setChecks(colorMenu, e.getSource());
} private Color color;
} // File actions
private FileAction newAction, openAction, closeAction, saveAction, saveAsAction, printAction, exitAction;
private FileAction[] fileActions; // File actions as an array // Element type actions
private TypeAction lineAction, rectangleAction, circleAction, curveAction;
private TypeAction[] typeActions; // Type actions as an array // Element color actions
private ColorAction redAction, yellowAction,greenAction, blueAction;
private ColorAction[] colorActions; // Color actions as an array private JMenuBar menuBar = new JMenuBar(); // Window menu bar
private JMenu elementMenu; // Elements menu
private JMenu colorMenu; // Color menu private Color elementColor = DEFAULT_ELEMENT_COLOR; // Current element color
private int elementType = DEFAULT_ELEMENT_TYPE; // Current element type
private JToolBar toolBar = new JToolBar(); // Window toolbar
private Sketcher theApp; // The application object
}

5、自定义常量包:

 // Defines application wide constants
package Constants;
import java.awt.Color;
import javax.swing.*; public class SketcherConstants {
// Path for images
public final static String imagePath = "E:/JavaProject/BeginningJava/Images/"; // Toolbar icons
public final static Icon NEW24 = new ImageIcon(imagePath + "New24.gif");
public final static Icon OPEN24 = new ImageIcon(imagePath + "Open24.gif");
public final static Icon SAVE24 = new ImageIcon(imagePath + "Save24.gif");
public final static Icon SAVEAS24 = new ImageIcon(imagePath + "SaveAs24.gif");
public final static Icon PRINT24 = new ImageIcon(imagePath + "Print24.gif"); public final static Icon LINE24 = new ImageIcon(imagePath + "Line24.gif");
public final static Icon RECTANGLE24 = new ImageIcon(imagePath + "Rectangle24.gif");
public final static Icon CIRCLE24 = new ImageIcon(imagePath + "Circle24.gif");
public final static Icon CURVE24 = new ImageIcon(imagePath + "Curve24.gif"); public final static Icon RED24 = new ImageIcon(imagePath + "Red24.gif");
public final static Icon GREEN24 = new ImageIcon(imagePath + "Green24.gif");
public final static Icon BLUE24 = new ImageIcon(imagePath + "Blue24.gif");
public final static Icon YELLOW24 = new ImageIcon(imagePath + "Yellow24.gif"); // Menu item icons
public final static Icon NEW16 = new ImageIcon(imagePath + "new16.gif");
public final static Icon OPEN16 = new ImageIcon(imagePath + "Open16.gif");
public final static Icon SAVE16 = new ImageIcon(imagePath + "Save16.gif");
public final static Icon SAVEAS16 = new ImageIcon(imagePath + "SaveAs16.gif");
public final static Icon PRINT16 = new ImageIcon(imagePath + "print16.gif"); public final static Icon LINE16 = new ImageIcon(imagePath + "Line16.gif");
public final static Icon RECTANGLE16 = new ImageIcon(imagePath + "Rectangle16.gif");
public final static Icon CIRCLE16 = new ImageIcon(imagePath + "Circle16.gif");
public final static Icon CURVE16 = new ImageIcon(imagePath + "Curve16.gif"); public final static Icon RED16 = new ImageIcon(imagePath + "Red16.gif");
public final static Icon GREEN16 = new ImageIcon(imagePath + "Green16.gif");
public final static Icon BLUE16 = new ImageIcon(imagePath + "Blue16.gif");
public final static Icon YELLOW16 = new ImageIcon(imagePath + "Yellow16.gif"); // Element type definitions
public final static int LINE = 101;
public final static int RECTANGLE = 102;
public final static int CIRCLE = 103;
public final static int CURVE = 104; // Initial conditions
public final static int DEFAULT_ELEMENT_TYPE = LINE;
public final static Color DEFAULT_ELEMENT_COLOR = Color.BLUE;
}

6、应用程序主程序:

 // Sketching application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; public class Sketcher {
public static void main(String[] args) {
theApp = new Sketcher(); // Create the application object
SwingUtilities.invokeLater(new Runnable() {
public void run() {
theApp.createGUI(); // Call GUI creator
}
});
} // Method to create the application GUI
private void createGUI() {
window = new SketcherFrame("Sketcher", this); // Create the app window
Toolkit theKit = window.getToolkit(); // Get the window toolkit
Dimension wndSize = theKit.getScreenSize(); // Get screen size // Set the position to screen center & size to half screen size
window.setSize(wndSize.width/2, wndSize.height/2); // Set window size
window.setLocationRelativeTo(null); // Center window window.addWindowListener(new WindowHandler()); // Add window listener sketch = new SketcherModel(); // Create the model
view = new SketcherView(this); // Create the view
sketch.addObserver(view); // Register view with the model
window.getContentPane().add(view, BorderLayout.CENTER);
window.setVisible(true);
} // Return a reference to the application window
public SketcherFrame getWindow() {
return window;
} // Return a reference to the model
public SketcherModel getModel() {
return sketch;
} // Return a reference to the view
public SketcherView getView() {
return view;
} // Handler class for window events
class WindowHandler extends WindowAdapter {
// Handler for window closing event
@Override
public void windowClosing(WindowEvent e) {
// Code to be added here...
}
} private SketcherModel sketch; // The data model for the sketch
private SketcherView view; // The view of the sketch
private SketcherFrame window; // The application window
private static Sketcher theApp; // The application object
}

Java基础之在窗口中绘图——利用多态性使用鼠标自由绘图(Sketcher 7 with a crosshair cursor)的更多相关文章

  1. Java基础之在窗口中绘图——使用模型/视图体系结构在视图中绘图(Sketcher 1 drawing a 3D rectangle)

    控制台程序. 在模型中表示数据视图的类用来显示草图并处理用户的交互操作,所以这种类把显示方法和草图控制器合并在一起.不专用于某个视图的通用GUI创建和操作在SketcherFrame类中处理. 模型对 ...

  2. Java基础之在窗口中绘图——渐变填充(GradientApplet 1)

    Applet程序. import javax.swing.*; import java.awt.*; import java.awt.geom.*; @SuppressWarnings("s ...

  3. Java基础之在窗口中绘图——填充星型(StarApplet 2 filled stars)

    Applet程序. import javax.swing.*; import java.awt.*; import java.awt.geom.GeneralPath; @SuppressWarnin ...

  4. Java基础之在窗口中绘图——绘制星星(StarApplet 1)

    Applet程序. 可以把更复杂的几何形状定义为GeneralPath类型的对象.GeneralPath可以是直线.Quad2D曲线和Cubic2D曲线的结合体,甚至可以包含其他GeneralPath ...

  5. Java基础之在窗口中绘图——移动曲线的控制点(CurveApplet 3 moving the control points)

    Applet程序. import javax.swing.*; import java.awt.*; import java.awt.geom.*; import javax.swing.event. ...

  6. Java基础之在窗口中绘图——显示曲线的控制点(CurveApplet 2 displaying control points)

    Applet程序. import javax.swing.*; import java.awt.*; import java.awt.geom.*; @SuppressWarnings("s ...

  7. Java基础之在窗口中绘图——绘制曲线(CurveApplet 1)

    Applet程序. 定义自由曲线的类有两个,其中一个定义二次曲线,另一个定义三次曲线.这些自由曲线是用一系列线段定义的参数化曲线.二次曲线段用方程定义,方程包含独立变量x的平方.三次曲线也用方程定义, ...

  8. Java基础之在窗口中绘图——绘制圆弧和椭圆(Sketcher 3 drawing arcs and ellipses)

    控制台程序. import javax.swing.JComponent; import java.util.*; import java.awt.*; import java.awt.geom.*; ...

  9. Java基础之在窗口中绘图——绘制直线和矩形(Sketcher 2 drawing lines and rectangles)

    控制台程序. import javax.swing.JComponent; import java.util.*; import java.awt.*; import java.awt.geom.*; ...

随机推荐

  1. Eclipse 使用maven创建Dynamic Web Project

    今天看到spring的官网首页已经没有下载连接了,建议使用maven构建spring项目.虽然maven已经不是新技术,但是这个我还没用过,谷歌走起! 通常创建项目都是用Eclipse,前几年还是My ...

  2. linux下搭建svn代码库

    1.安装svn客户端 2.创建svn代码库 1.安装svn客户端 1.1.使用命令安装 1)CentOS $ yum install subversion 2)ubuntu sudo apt-get ...

  3. C# 非模式窗体show()和模式窗体showdialog()的区别(转)

    对话框不是模式就是无模式的.模式对话框,在可以继续操作应用程序的其他部分之前,必须被关闭(隐藏或卸载).例如,如果一个对话框,在可以切换到其它窗 体或对话框之前要求先单击“确定”或“取消”,则它就是模 ...

  4. [CareerCup] 18.13 Largest Rectangle of Letters

    18.13 Given a list of millions of words, design an algorithm to create the largest possible rectangl ...

  5. [zt]矩阵求导公式

    今天推导公式,发现居然有对矩阵的求导,狂汗--完全不会.不过还好网上有人总结了.吼吼,赶紧搬过来收藏备份. 基本公式:Y = A * X --> DY/DX = A'Y = X * A --&g ...

  6. Javascript杂记(一)

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. php读取html文件(或php文件)的方法

    一.使用fopen()函数   此函数主要传入的是头两个参数(第一个是文件地址,第二个是打开方式),可以读取任何一个文本文件,然后用while将fopen函数读取到的每一行数据循环输出.   如:   ...

  8. 数位DP bzoj1026

    1026: [SCOI2009]windy数 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 5809  Solved: 2589[Submit][Sta ...

  9. Linux磁盘及文件系统管理

    在LINUX中我们知道一个很重要的概念,那就是"一切皆文件",这里的一切表示所有在LINUX系统的对象,自然也包括了LINUX中的硬盘设备.在LINUX中所有设备都被抽象成一个文件 ...

  10. Java面试题大全(一)

    JAVA相关基础知识 1.面向对象的特征有哪些方面 1.抽象: 抽象就是忽略一个主题中与当前目标无关的那些方面,以便更充分地注意与当前目标有关的方面.抽象并不打算了解全部问题,而只是选择其中的一部分, ...