Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • tintas/cs349_w18_examples
  • aycheng/cs349_w18_examples
  • j95he/cs349_w18_examples
  • skantor/cs349_w18_examples
  • ss22kim/cs349_w18_examples
  • w43wei/cs349_w18_examples
  • kkatsura/cs349_w18_examples
7 results
Show changes
Showing
with 731 additions and 30 deletions
include ':app'
## Android Demos
> Note: all code requires [Android Studio](https://developer.android.com/studio) to compile and run
......@@ -34,21 +34,17 @@ public class BarExercise {
class Canvas extends JComponent {
// the house shape (model position is centred at top left corner)
private Polygon shape = new Polygon(new int[] { -50, 50, 50, 0, -50},
new int[] { 75, 75, -25, -75, -25}, 5);
int step = 0;
Canvas() {
// only mouse clicked events
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
public void mouseClicked(MouseEvent me) {
step ++;
repaint();
}
});
}
});
}
// custom graphics drawing
......@@ -68,11 +64,12 @@ class Canvas extends JComponent {
// save the current transform matrix
AffineTransform M = g2.getTransform();
// the shape will get transformed into "world" coordinates
// transfrom at one time
if (true) {
g2.translate(50, 100);
g2.rotate(Math.toRadians(30));
g2.translate(-50, -100);
g2.setColor(Color.BLUE.darker());
drawBar(g2, 50, 100, 150, 100);
......@@ -82,23 +79,23 @@ class Canvas extends JComponent {
switch (step % 4) {
case 1:
g2.translate(-50, -100);
drawBar(g2, 50, 100, 150, 100);
g2.setTransform(M);
break;
g2.translate(-50, -100);
drawBar(g2, 50, 100, 150, 100);
g2.setTransform(M);
break;
case 2:
g2.rotate(Math.toRadians(30));
g2.translate(-50, -100);
drawBar(g2, 50, 100, 150, 100);
g2.setTransform(M);
break;
g2.rotate(Math.toRadians(30));
g2.translate(-50, -100);
drawBar(g2, 50, 100, 150, 100);
g2.setTransform(M);
break;
case 3:
g2.translate(50, 100);
g2.rotate(Math.toRadians(30));
g2.translate(-50, -100);
drawBar(g2, 50, 100, 150, 100);
g2.setTransform(M);
break;
g2.translate(50, 100);
g2.rotate(Math.toRadians(30));
g2.translate(-50, -100);
drawBar(g2, 50, 100, 150, 100);
g2.setTransform(M);
break;
}
}
}
......
......@@ -54,7 +54,7 @@ class Canvas extends JComponent {
// the shape will get transformed when rendered
g2.translate(M.x, M.y);
g2.rotate(45);
g2.rotate(Math.toRadians(45));
g2.scale(2, 1);
g2.setStroke(new BasicStroke(3));
......
......@@ -27,6 +27,7 @@ class Shape {
// add a point to end of shape
public void addPoint(double x, double y) {
if (points == null) clearPoints();
addPoint(new Point2d(x, y));
}
......@@ -78,9 +79,16 @@ class Shape {
// shape's transform
// quick hack, get and set would be better
float scale = 1.0f;
public float getScale(){
return scale;
}
public void setScale(float scale){
this.scale = scale;
}
// some optimization to cache points for drawing
Boolean pointsChanged = false; // dirty bit
int[] xpoints, ypoints;
......@@ -129,7 +137,7 @@ class Shape {
}
// reset the transform to what it was before we drew the shape
g2.setTransform(M);
// g2.setTransform(M);
}
......
......@@ -23,12 +23,12 @@ public class ShapeDemo extends JPanel {
shape = new Shape();
// change shape type
// shape.setIsClosed(true);
// shape.setIsFilled(true);
// shape.setIsClosed(true);
// shape.setIsFilled(true);
shape.setColour(Color.BLUE);
// try setting scale to something other than 1
shape.scale = 1.0f;
shape.setScale(1.0f);
repaint();
}
......@@ -57,7 +57,7 @@ public class ShapeDemo extends JPanel {
Graphics2D g2 = (Graphics2D) g; // cast to get 2D drawing methods
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // antialiasing look nicer
RenderingHints.VALUE_ANTIALIAS_ON);
if (shape != null)
shape.draw(g2);
}
......
/*
* CS 349 Java Code Examples
*
* ClosestPoint Uses two methods to compute distance from
mouse to closest point on line. Double click
to generate new line.
*
*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseAdapter;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.vecmath.*;
import java.lang.Math.*;
import java.util.Random;
// create the window and run the demo
public class ClosestPoint extends JPanel {
Point P0 = new Point();
Point P1 = null;
Point M = new Point(); // mouse point
public static void main(String[] args) {
// create the window
ClosestPoint canvas = new ClosestPoint();
JFrame f = new JFrame("ClosestPoint"); // jframe is the app window
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400, 400); // window size
f.setContentPane(canvas); // add canvas to jframe
f.setVisible(true); // show the window
}
ClosestPoint() {
setBackground(Color.WHITE);
// add listeners
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent arg0) {
// generate new line on double click
if (arg0.getClickCount() == 2)
randomLine();
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
M.x = arg0.getX();
M.y = arg0.getY();
repaint();
}
});
}
// custom graphics drawing
public void paintComponent(Graphics g) {
super.paintComponent(g); // JPanel paint
Graphics2D g2 = (Graphics2D)g;
if (P1 == null) {
P1 = new Point();
randomLine();
}
// antiliasing
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(2));
// draw line
g2.setColor(Color.BLACK);
g2.drawLine(P0.x, P0.y, P1.x, P1.y);
// draw mouse point
g2.setColor(Color.BLACK);
int s = 7;
g2.drawOval(M.x - s, M.y - s, 2 * s, 2 * s );
// get closest point using the vector projection method
Point2d M2 = new Point2d(M.x, M.y);
Point2d I1 = closestPoint(M2,
new Point2d(P0.x, P0.y),
new Point2d(P1.x, P1.y));
// draw closest point
g2.setColor(Color.RED);
g2.drawOval((int)I1.x - s, (int)I1.y - s, 2 * s, 2 * s );
// use that to get distance
double d1 = M2.distance(I1);
// get distance using Java2D method
double d2 = Line2D.ptSegDist(P0.x, P0.y, P1.x, P1.y, M.x, M.y);
g2.setColor(Color.BLACK);
g2.drawString(String.format("%.1f %.1f", d1, d2), M.x + 10,M.y);
}
// find closest point using projection method
static Point2d closestPoint(Point2d M, Point2d P0, Point2d P1) {
Vector2d v = new Vector2d();
v.sub(P1,P0); // v = P1 - P0
// early out if line is less than 1 pixel long
if (v.lengthSquared() < 0.5)
return P0;
Vector2d u = new Vector2d();
u.sub(M,P0); // u = M - P1
// scalar of vector projection ...
double s = u.dot(v) / v.dot(v);
// find point for constrained line segment
if (s < 0)
return P0;
else if (s > 1)
return P1;
else {
Point2d I = P0;
Vector2d w = new Vector2d();
w.scale(s, v); // w = s * v
I.add(w); // I = P0 + w
return I;
}
}
// random numbers
static Random rand = new Random();
int random(int min, int max) {
return rand.nextInt(max - min + 1) + min;
}
void randomLine()
{
// create random line
int m = 50; // margin
P0.x = m;
P0.y = random(m, getHeight() - m);
P1.x = getWidth() - m;
P1.y = random(m, getHeight() - m);
}
}
/*
* CS 349 Java Code Examples
*
* PolygonHittest Uses built-in method to hit-test closed polygon.
*
*/
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class PolygonHittest extends JPanel{
Point M = new Point(); // mouse point
Polygon poly = new Polygon();
public static void main(String args[]){
JFrame window = new JFrame("PolygonHittest");
window.setSize(300, 300);
window.setContentPane(new PolygonHittest());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public PolygonHittest(){
this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
poly.addPoint(e.getX(), e.getY());
repaint();
}
});
this.addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
M.x = e.getX();
M.y = e.getY();
repaint();
}
});
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (poly.contains(M.x, M.y))
g2.setColor(Color.BLUE);
else
g2.setColor(Color.RED);
g2.fillPolygon(poly);
g2.setColor(Color.BLACK);
g.drawPolyline(poly.xpoints, poly.ypoints, poly.npoints);
}
}
/*
* CS 349 Java Code Examples
*
* CompositionOrder Demo of different concatenation orders of matrix transforms.
* Click the window to change the order.
*
*/
import javax.swing.JFrame;
import javax.swing.JComponent;
import java.awt.*;
import java.awt.geom.*;
import java.lang.Math.*;
import java.awt.event.*;
// create the window and run the demo
public class TransformHittest {
public static void main(String[] args) {
// create the window
Canvas canvas = new Canvas();
JFrame f = new JFrame("CompositionOrder"); // jframe is the app window
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500, 700); // window size
f.setContentPane(canvas); // add canvas to jframe
f.setBackground(Color.WHITE);
f.setVisible(true); // show the window
}
}
class Canvas extends JComponent {
Point M = new Point(); // mouse point
AffineTransform AT1; // transform matrix for shape1
AffineTransform AT2; // transform matrix for shape2
// the house shape (model position is centred at top left corner)
private Polygon shape = new Polygon(new int[] { -50, 50, 50, 0, -50},
new int[] { 75, 75, -25, -75, -25}, 5);
// a larger font for displaying the concatenation order
private Font font = new Font("SansSerif", Font.PLAIN, 30);
// the concatenation order
private int order = 0;
Canvas() {
// create transformation matrix for shape1
AT1 = new AffineTransform();
AT1.translate(350, 100);
AT1.rotate(Math.toRadians(30));
// create another transformation matrix for shape2
AT2 = new AffineTransform();
AT2.translate(200, 300);
AT2.rotate(Math.toRadians(30));
AT2.scale(2, 2);
this.addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
M.x = e.getX();
M.y = e.getY();
repaint();
}
});
System.out.println("click to change transformation composition order");
}
// custom graphics drawing
public void paintComponent(Graphics g) {
super.paintComponent(g); // JPanel paint
Graphics2D g2 = (Graphics2D)g;
// save the current transform matrix
AffineTransform ATG = g2.getTransform();
// draw the original shape in "model" coordinates
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(3));
g2.drawPolygon(shape.xpoints, shape.ypoints, shape.npoints);
// Shape1
g2.setTransform(AT1); // Use Transform Matrix AT1 for shape1
g2.setColor(Color.RED);
g2.drawPolygon(shape.xpoints, shape.ypoints, shape.npoints);
// hit testing
Point MT = new Point();
try{
// create an inverse matrix of AT1
AffineTransform IAT1 = AT1.createInverse();
// apply the inverse transformation to the mouse position
IAT1.transform(M, MT);
// check if original shape contains transformed mouse position
if (shape.contains(MT.x, MT.y))
g2.setColor(Color.RED);
else
g2.setColor(Color.WHITE);
g2.fillPolygon(shape);
} catch (NoninvertibleTransformException e){
// error
}
// Shape2
g2.setTransform(AT2); // Use Transform Matrix AT2 for shape2
g2.setColor(Color.BLUE);
g2.drawPolygon(shape.xpoints, shape.ypoints, shape.npoints);
// hit test
try{
// create an inverse matrix of AT2
AffineTransform IAT2 = AT2.createInverse();
// apply the inverse transformation to the mouse position
IAT2.transform(M, MT);
// check if original shape contains transformed mouse position
if (shape.contains(MT.x, MT.y))
g2.setColor(Color.BLUE);
else
g2.setColor(Color.WHITE);
g2.fillPolygon(shape);
} catch (NoninvertibleTransformException e){
// error
}
// reset to transform
g2.setTransform(ATG);
}
}
# super simple makefile
# call it using 'make NAME=name_of_code_file_without_extension'
# (assumes a .java extension)
NAME = ClosestPoint
# you may need to pass OS=win to run on windows
OS =
# HACK: vecmath is included regardless if needed
all:
@echo "Compiling..."
javac -cp vecmath.jar $(NAME).java
run: all
# windows needs a semicolon
ifeq ($(OS),win)
@echo "Running on windows ..."
java -cp "vecmath.jar;." $(NAME)
# everyone else likes a colon
else
@echo "Running ..."
java -cp "vecmath.jar:." $(NAME)
endif
clean:
rm -rf *.class
File added
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
// (C) Joseph Mack 2011, jmack (at) wm7d (dot) net, released under GPL v3 (or any later version)
import java.awt.event.*;
class Controller implements ActionListener {
Model model;
Controller(Model model) {
this.model = model;
}
// event from the view's button
public void actionPerformed(java.awt.event.ActionEvent e){
System.out.println("Controller: changing Model");
model.incrementCounter();
}
}
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
/**
* One view. Separate controller.
*/
import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.*;
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame("HelloMVC1");
// create Model and initialize it
Model model = new Model();
// create Controller, tell it about model
Controller controller = new Controller(model);
// create View, tell it about model and controller
View view = new View(model, controller);
// tell Model about View.
model.setView(view);
// add view (view is a JPanel)
frame.getContentPane().add(view);
// setup window
frame.setPreferredSize(new Dimension(300,300));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
// View interface
interface IView {
public void updateView();
}
public class Model {
// the data in the model, just a counter
private int counter;
// the view (note, only supports 1 view!)
IView view;
// set the view observer
public void setView(IView view) {
this.view = view;
// update the view to current state of the model
view.updateView();
}
public int getCounterValue() {
return counter;
}
public void incrementCounter() {
if (counter < 5) {
counter++;
System.out.println("Model: increment counter to " + counter);
notifyObserver();
}
}
// notify the IView observer
private void notifyObserver() {
System.out.println("Model: notify View");
view.updateView();
}
}
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
class View extends JPanel implements IView {
// the view's main user interface
private JButton button;
// the model that this view is showing
private Model model;
View(Model model, Controller controller) {
// create the view UI
button = new JButton("?");
button.setMaximumSize(new Dimension(100, 50));
button.setPreferredSize(new Dimension(100, 50));
// a GridBagLayout with default constraints centres
// the widget in the window
this.setLayout(new GridBagLayout());
this.add(button, new GridBagConstraints());
// set the model
this.model = model;
// setup the event to go to the controller
button.addActionListener(controller);
}
// IView interface
public void updateView() {
System.out.println("View: updateView");
button.setText(Integer.toString(model.getCounterValue()));
}
}
# super simple makefile
# call it using 'make NAME=name_of_code_file_without_extension'
# (assumes a .java extension)
NAME = "Main"
all:
@echo "Compiling..."
javac *.java
run: all
@echo "Running..."
java $(NAME)
clean:
rm -rf *.class
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
// (C) Joseph Mack 2011, jmack (at) wm7d (dot) net, released under GPL v3 (or any later version)
import java.awt.event.*;
class Controller implements ActionListener, MouseListener {
Model model;
Controller(Model model) {
this.model = model;
}
// event from the view's button
public void actionPerformed(java.awt.event.ActionEvent e){
System.out.println("Controller: changing Model (actionPerformed)");
model.incrementCounter();
}
public void mouseClicked(MouseEvent e) {
System.out.println("Controller: changing Model (mouseClicked)");
model.incrementCounter();
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
/**
* Two views coordinated with the observer pattern. Separate controller.
* The mechanics of a separate controller are starting to break down.
*/
import javax.swing.*;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
public class Main {
public static void main(String[] args){
JFrame frame = new JFrame("HelloMVC2");
// create Model and initialize it
Model model = new Model();
// create Controller, tell it about model
Controller controller = new Controller(model);
// create View, tell it about model and controller
View view = new View(model, controller);
// tell Model about View
model.addView(view);
// create second view ...
View2 view2 = new View2(model, controller);
model.addView(view2);
// create a layout panel to hold the two views
JPanel p = new JPanel(new GridLayout(2,1));
frame.getContentPane().add(p);
// add views (each view is a JPanel)
p.add(view);
p.add(view2);
// setup the window
frame.setPreferredSize(new Dimension(300,300));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
import java.util.ArrayList;
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
// View interface
interface IView {
public void updateView();
}
public class Model {
// the data in the model, just a counter
private int counter;
// all views of this model
private ArrayList<IView> views = new ArrayList<IView>();
// set the view observer
public void addView(IView view) {
views.add(view);
view.updateView();
}
public int getCounterValue() {
return counter;
}
public void incrementCounter() {
if (counter < 5) {
counter++;
System.out.println("Model: increment counter to " + counter);
notifyObservers();
}
}
// notify the IView observer
private void notifyObservers() {
for (IView view : this.views) {
System.out.println("Model: notify View");
view.updateView();
}
}
}
// HelloMVC: a simple MVC example
// the model is just a counter
// inspired by code by Joseph Mack, http://www.austintek.com/mvc/
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.*;
class View extends JPanel implements IView {
// the view's main user interface
private JButton button;
// the model that this view is showing
private Model model;
View(Model model, Controller controller) {
// create the view UI
button = new JButton("?");
button.setMaximumSize(new Dimension(100, 50));
button.setPreferredSize(new Dimension(100, 50));
// a GridBagLayout with default constraints centres
// the widget in the window
this.setLayout(new GridBagLayout());
this.add(button, new GridBagConstraints());
// set the model
this.model = model;
// setup the event to go to the controller
button.addActionListener(controller);
}
// IView interface
public void updateView() {
System.out.println("View: updateView");
button.setText(Integer.toString(model.getCounterValue()));
}
}