FirstSwingFrame.java Page 1 of 1

Similar documents
Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Graphic User Interfaces. - GUI concepts - Swing - AWT

H212 Introduction to Software Systems Honors

AnimatedImage.java. Page 1

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

AP CS Unit 11: Graphics and Events

Graphical User Interface (GUI)

APPENDIX. public void cekroot() { System.out.println("nilai root : "+root.data); }

// autor igre Ivan Programerska sekcija package mine;

encompass a group of features for building Graphical User Interfaces (GUI).

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2

User interfaces and Swing

G51PRG: Introduction to Programming Second semester Applets and graphics

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

INTRODUCTION TO (GUIS)

Lecture 5: Java Graphics

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

CSCI 201L Midterm Written Fall % of course grade

Graphical User Interfaces 2

CSCI 201L Midterm Written SOLUTION Fall % of course grade

Introduction to the JAVA UI classes Advanced HCI IAT351

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Part I: Learn Common Graphics Components

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Lecture 3: Java Graphics & Events

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

Window Interfaces Using Swing Objects

Using Several Components

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Dr. Hikmat A. M. AbdelJaber

Window Interfaces Using Swing Objects

Chapter 9 Designing Graphical User Interfaces (GUIs)

Graphical User Interface (GUI)

Advanced Java Unit 6: Review of Graphics and Events

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Final Examination Semester 2 / Year 2010

JFrame In Swing, a JFrame is similar to a window in your operating system

Programming Languages and Techniques (CIS120)

Java: Graphical User Interfaces (GUI)

CS 251 Intermediate Programming GUIs: Components and Layout

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

AP CS Unit 12: Drawing and Mouse Events

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Building Java Programs Bonus Slides

Java. GUI building with the AWT

Building Graphical User Interfaces. GUI Principles

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Computer Science 210: Data Structures. Intro to Java Graphics

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Top-Level Containers

Example: Building a Java GUI

Example: Building a Java GUI

GUI in Java TalentHome Solutions

Java Coordinate System

Final Examination Semester 2 / Year 2011

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

CIS 120 Programming Languages and Techniques. Final Exam, May 3, 2011

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Dr. Hikmat A. M. AbdelJaber

Building Graphical User Interfaces. Overview

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Packages: Putting Classes Together

Java Never Ends CHAPTER MULTITHREADING 1100 Example: A Nonresponsive GUI 1101

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

Graphical User Interfaces 2

Graphical User Interfaces (GUIs)

Java Never Ends MULTITHREADING 958 Example: A Nonresponsive GUI 959

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Graphical User Interfaces

Graphical User Interfaces 2

Advanced Java Programming

CSIS 10A Assignment 7 SOLUTIONS

2IS45 Programming

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Theory Test 3A. University of Cape Town ~ Department of Computer Science. Computer Science 1016S ~ For Official Use

GUI and its COmponent Textfield, Button & Label. By Iqtidar Ali

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Programming Mobile Devices J2SE GUI

IT101. Graphical User Interface

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

DM503 Programming B. Peter Schneider-Kamp.

Multiple Choice Questions: Identify the choice that best completes the statement or answers the question. (15 marks)

RobotPlanning.java Page 1

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

State Application Using MVC

JLayeredPane. Depth Constants in JLayeredPane

Java, Swing, and Eclipse: The Calculator Lab.

CSA 1019 Imperative and OO Programming

Graphical User Interfaces in Java - SWING

[module lab 2.2] GUI FRAMEWORKS & CONCURRENCY

JFrame & JLabel. By Iqtidar Ali

Transcription:

FirstSwingFrame.java Page 1 of 1 2: * A first example of using Swing. A JFrame is created with 3: * a label and buttons (which don t yet respond to events). 4: * 5: * @author Andrew Vardy 6: */ 7: import javax.swing.*; 8: import java.awt.flowlayout; 9: 10: public class FirstSwingFrame extends JFrame { 11: public FirstSwingFrame() { 12: super("firstswingframe"); 13: setdefaultcloseoperation(jframe.exit_on_close); 14: setlayout(new FlowLayout()); 15: 16: // You can any Component to the JFrame 17: add(new JLabel("Label")); 18: add(new JButton("Button1")); 19: add(new JButton("Button2")); 20: 21: // Set the size of the JFrame and make it visible 22: setsize(300, 100); 23: setvisible(true); 24: } 25: 26: public static void main(string[] args) throws Exception { 27: // An anonymous inner class created to run on the event- 28: // dispatching thread. 29: SwingUtilities.invokeLater(new Runnable() { 30: public void run() { 31: new FirstSwingFrame(); 32: } 33: }); 34: } 35: }

SecondSwingFrame.java Page 1 of 1 2: * Just like FirstSwingFrame only we do not extend 3: * JFrame, we have a JFrame attribute instead. 4: * 5: * @author Andrew Vardy 6: */ 7: 8: import javax.swing.*; 9: import java.awt.flowlayout; 10: 11: public class SecondSwingFrame { 12: 13: JFrame frame = new JFrame("SecondSwingFrame"); 14: 15: public SecondSwingFrame() { 16: frame.setdefaultcloseoperation(jframe.exit_on_close); 17: frame.setlayout(new FlowLayout()); 18: 19: frame.add(new JLabel("Label")); 20: frame.add(new JButton("Button1")); 21: frame.add(new JButton("Button2")); 22: 23: frame.setsize(300, 100); 24: frame.setvisible(true); 25: } 26: 27: public static void main(string[] args) throws Exception { 28: SwingUtilities.invokeLater(new Runnable() { 29: public void run() { 30: new SecondSwingFrame(); 31: } 32: }); 33: } 34: }

LayoutPlay.java Page 1 of 2 2: * Demonstrates Swing s component layout features using three different 3: * layout managers: FlowLayout, GridLayout, and BoxLayout. 4: * 5: * The suggested layout manager is GridBagLayout but it is rather complicated. 6: * Alternatively, you can use a GUI-builder such as NetBeans. 7: * 8: * @author Andrew Vardy 9: */ 10: import javax.swing.*; 11: import java.awt.*; 12: 13: public class LayoutPlay extends JFrame { 14: 15: // RedPanel uses the default layout for JPanels --- FlowLayout 16: class RedPanel extends JPanel { 17: public RedPanel() { 18: setbackground(color.red); 19: setpreferredsize(new Dimension(200, 200)); 20: add(new JLabel("x")); add(new JButton("Set")); 21: add(new JLabel("y")); add(new JButton("Set")); 22: add(new JLabel("z")); add(new JButton("Set")); 23: } 24: } 25: 26: // GreenPanel uses GridLayout 27: class GreenPanel extends JPanel { 28: public GreenPanel() { 29: setbackground(color.green); 30: setpreferredsize(new Dimension(200, 200)); 31: setlayout(new GridLayout(3, 2)); 32: add(new JLabel("x")); add(new JButton("Set")); 33: add(new JLabel("y")); add(new JButton("Set")); 34: add(new JLabel("z")); add(new JButton("Set")); 35: } 36: } 37: 38: // BluePanel uses BoxLayout to layout three individual rows of 39: // (label, button) pairs. 40: class BluePanel extends JPanel { 41: public BluePanel() { 42: setbackground(color.blue); 43: setpreferredsize(new Dimension(200, 200)); 44: 45: // Layout the BluePanel vertically. 46: setlayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 47: 48: // Create three rows, each one a horizontally laid out 49: // JPanel with a label and a button. 50: JPanel row1 = new JPanel(), 51: row2 = new JPanel(), 52: row3 = new JPanel(); 53: row1.setlayout(new BoxLayout(row1, BoxLayout.X_AXIS)); 54: row2.setlayout(new BoxLayout(row2, BoxLayout.X_AXIS)); 55: row3.setlayout(new BoxLayout(row3, BoxLayout.X_AXIS)); 56: row1.add(new JLabel("x")); row1.add(new JButton("Set")); 57: row2.add(new JLabel("y")); row2.add(new JButton("Set")); 58: row3.add(new JLabel("z")); row3.add(new JButton("Set")); 59: 60: add(row1); 61: add(row2); 62: add(row3); 63: } 64: } 65: 66: public LayoutPlay() { 67: super("layoutplay"); 68: setdefaultcloseoperation(jframe.exit_on_close); 69: 70: // At the highest level we will use FlowLayout. 71: setlayout(new FlowLayout()); 72: 73: // Add three different panels with differing 74: // layouts, but the same set of labels + buttons 75: add(new RedPanel()); 76: add(new GreenPanel()); 77: add(new BluePanel());

LayoutPlay.java Page 2 of 2 78: 79: // The JFrame will choose its initial size 80: // based on its content. 81: pack(); 82: setvisible(true); 83: } 84: 85: public static void main(string[] args) throws Exception { 86: SwingUtilities.invokeLater(new Runnable() { 87: public void run() { 88: new LayoutPlay(); 89: } 90: }); 91: } 92: }

Paint1.java Page 1 of 2 2: * First cut at creating a paint program with Swing. This program works 3: * but does not separate the model from the GUI. This will be fixed in 4: * subsequent versions of PaintX. 5: * 6: * @author Andrew Vardy 7: */ 8: import java.awt.*; 9: import java.awt.event.actionevent; 10: import java.awt.event.actionlistener; 11: import java.awt.event.mouseadapter; 12: import java.awt.event.mouseevent; 13: 14: import javax.swing.*; 15: 16: public class Paint1 extends MouseAdapter implements ActionListener { 17: // The underlying model is a 2-D array of booleans. 18: // This grid represents the contents of the canvas. 19: boolean grid[][] = new boolean[400][400]; 20: 21: JFrame frame = new JFrame("Paint1"); 22: PaintPanel paintpanel = new PaintPanel(); 23: JButton clearbutton = new JButton("Clear"); 24: 25: public Paint1() { 26: // Initialize frame and add the paintpanel in the center 27: frame.setdefaultcloseoperation(jframe.exit_on_close); 28: frame.setlayout(new BorderLayout()); 29: frame.add(paintpanel); 30: 31: // Create a panel on the left for buttons and add 32: // the button to it 33: JPanel buttonpanel = new JPanel(); 34: buttonpanel.setlayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 35: buttonpanel.add(clearbutton); 36: frame.add(buttonpanel, BorderLayout.WEST); 37: 38: // Setup event listeners. In this case, Paint1 is the 39: // listener for all component events. 40: clearbutton.addactionlistener(this); 41: paintpanel.addmouselistener(this); 42: paintpanel.addmousemotionlistener(this); 43: 44: frame.pack(); 45: frame.setresizable(false); // Must not be resizable because we aren t 46: frame.setvisible(true); // handling changes in size. 47: } 48: 49: @Override 50: public void actionperformed(actionevent e) { 51: for (int i=0; i<grid.length; i++) 52: for (int j=0; j<grid[0].length; j++) 53: grid[i][j] = false; 54: 55: // The panel must be informed that a repaint is now required. 56: paintpanel.repaint(); 57: } 58: 59: public void mousepressed(mouseevent e) { 60: int cellx = e.getx() / paintpanel.cw; 61: int celly = e.gety() / paintpanel.ch; 62: 63: if (cellx >= 0 && cellx < grid.length && 64: celly >= 0 && celly < grid[0].length) { 65: // Set the cell content to true. 66: grid[cellx][celly] = true; 67: paintpanel.repaint(); 68: } 69: } 70: 71: public void mousedragged(mouseevent e) { 72: mousepressed(e); 73: } 74: 75: class PaintPanel extends JPanel { 76: // Width and height of an individual cell.

Paint1.java Page 2 of 2 77: int cw, ch; 78: 79: PaintPanel() { 80: int pw = 400, ph = 400; 81: setpreferredsize(new Dimension(pw, ph)); 82: 83: cw = pw / grid.length; 84: ch = ph / grid[0].length; 85: } 86: 87: public void paintcomponent(graphics g) { 88: // First fill the whole panel with white. 89: g.setcolor(color.white); 90: g.fillrect(0, 0, getwidth(), getheight()); 91: 92: // Now fill in all true grid entries with blue. 93: g.setcolor(color.blue); 94: for (int i=0; i<grid.length; i++) 95: for (int j=0; j<grid[0].length; j++) 96: if (grid[i][j]) 97: g.fillrect(i*cw, j*ch, cw, ch); 98: } 99: } 100: 101: public static void main(string[] args) throws Exception { 102: SwingUtilities.invokeLater(new Runnable() { 103: public void run() { 104: new Paint1(); 105: } 106: }); 107: } 108: }

Paint2.java Page 1 of 1 2: * Here we re-factor Paint1 to isolate the model as a separate 3: * class---gridmodel. Also we factor out PaintPanel and call it 4: * GridPanel and place it in a separate top-level class. 5: * 6: * @author Andrew Vardy 7: */ 8: import java.awt.*; 9: import java.awt.event.actionevent; 10: import java.awt.event.actionlistener; 11: import java.awt.event.mouseadapter; 12: import java.awt.event.mouseevent; 13: 14: import javax.swing.*; 15: 16: public class Paint2 extends MouseAdapter implements ActionListener { 17: 18: GridModel model = new GridModel(100, 100); 19: JFrame frame = new JFrame("Paint2"); 20: GridPanel gridpanel = new GridPanel(400, 400, model); 21: JButton clearbutton = new JButton("Clear"); 22: 23: public Paint2() { 24: // Initialize frame and add the paintpanel in the center 25: frame.setdefaultcloseoperation(jframe.exit_on_close); 26: frame.setlayout(new BorderLayout()); 27: frame.add(gridpanel); 28: 29: // Create a panel on the left for buttons and add 30: // the button to it 31: JPanel buttonpanel = new JPanel(); 32: buttonpanel.setlayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 33: buttonpanel.add(clearbutton); 34: frame.add(buttonpanel, BorderLayout.WEST); 35: 36: // Setup event listeners. In this case, Paint2 is the 37: // listener for all component events. 38: clearbutton.addactionlistener(this); 39: gridpanel.addmouselistener(this); 40: gridpanel.addmousemotionlistener(this); 41: 42: frame.pack(); 43: frame.setresizable(false); // Must not be resizable because we aren t 44: frame.setvisible(true); // handling changes in size. 45: } 46: 47: @Override 48: public void actionperformed(actionevent e) { 49: model.clearall(); 50: gridpanel.repaint(); 51: } 52: 53: public void mousepressed(mouseevent e) { 54: int cellx = e.getx() / gridpanel.getcellwidth(); 55: int celly = e.gety() / gridpanel.getcellheight(); 56: 57: if (cellx >= 0 && cellx < model.getwidth() && 58: celly >= 0 && celly < model.getheight()) { 59: model.setvalue(cellx, celly, true); 60: gridpanel.repaint(); 61: } 62: } 63: 64: public void mousedragged(mouseevent e) { 65: mousepressed(e); 66: } 67: 68: public static void main(string[] args) throws Exception { 69: SwingUtilities.invokeLater(new Runnable() { 70: public void run() { 71: new Paint2(); 72: } 73: }); 74: } 75: } 76:

GridModel.java Page 1 of 1 2: * Represents a 2-D array of boolean values. 3: * 4: * @author Andrew Vardy 5: */ 6: public class GridModel { 7: protected int width; 8: protected int height; 9: protected boolean grid[][]; 10: 11: GridModel(int width, int height) { 12: this.width = width; 13: this.height = height; 14: grid = new boolean[width][height]; 15: } 16: 17: void clearall() { 18: for (int i=0; i<width; i++) 19: for (int j=0; j<height; j++) 20: grid[i][j] = false; 21: } 22: 23: boolean getvalue(int i, int j) { 24: return grid[i][j]; 25: } 26: 27: void setvalue(int i, int j, boolean value) { 28: grid[i][j] = value; 29: } 30: 31: int getwidth() { 32: return width; 33: } 34: 35: int getheight() { 36: return height; 37: } 38: }

GridPanel.java Page 1 of 1 2: * A JPanel that provides a view of a GridModel. 3: */ 4: import java.awt.color; 5: import java.awt.dimension; 6: import java.awt.graphics; 7: import javax.swing.jpanel; 8: 9: public class GridPanel extends JPanel { 10: // Width and height of an individual cell. 11: int cw, ch; 12: GridModel model; 13: 14: GridPanel(int width, int height, GridModel model) { 15: setpreferredsize(new Dimension(width, height)); 16: this.model = model; 17: 18: cw = width / model.getwidth(); 19: ch = height / model.getheight(); 20: } 21: 22: public void paintcomponent(graphics g) { 23: super.paintcomponent(g); 24: 25: // First fill the whole panel with white. 26: g.setcolor(color.white); 27: g.fillrect(0, 0, getwidth(), getheight()); 28: 29: // Now fill in all true grid entries with blue. 30: g.setcolor(color.blue); 31: for (int i=0; i<model.getwidth(); i++) 32: for (int j=0; j<model.getheight(); j++) 33: if (model.getvalue(i,j)) 34: g.fillrect(i*cw, j*ch, cw, ch); 35: } 36: 37: public int getcellwidth() { 38: return cw; 39: } 40: 41: public int getcellheight() { 42: return ch; 43: } 44: }

GameOfLife.java Page 1 of 3 2: * Based on Paint2, this application implements Conway s Game of Life 3: * Cellular Automaton. For event listeners we use anonymous inner 4: * class which are defined directly in the constructor for 5: * GameOfLife. 6: * 7: * @author Andrew Vardy 8: */ 9: import java.awt.*; 10: import java.awt.event.actionevent; 11: import java.awt.event.actionlistener; 12: import java.awt.event.mouseadapter; 13: import java.awt.event.mouseevent; 14: 15: import javax.swing.*; 16: 17: public class GameOfLife { 18: 19: // The underlying model is an extension of GridModel 20: // and implements the rules for the Game of Life. 21: LifeModel model = new LifeModel(100, 100); 22: 23: JFrame frame = new JFrame("GameOfLife"); 24: GridPanel paintpanel = new GridPanel(800, 800, model); 25: JButton clearbutton = new JButton("Clear"), 26: startbutton = new JButton("Start"), 27: stopbutton = new JButton("Stop"); 28: 29: public GameOfLife() { 30: // Initialize frame and add the paintpanel in the center 31: frame.setdefaultcloseoperation(jframe.exit_on_close); 32: frame.setlayout(new BorderLayout()); 33: frame.add(paintpanel); 34: 35: // Create a panel on the left for buttons and add 36: // the button to it 37: JPanel buttonpanel = new JPanel(); 38: buttonpanel.setlayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS)); 39: buttonpanel.add(clearbutton); 40: buttonpanel.add(startbutton); 41: buttonpanel.add(stopbutton); 42: frame.add(buttonpanel, BorderLayout.WEST); 43: 44: // Setup event listeners. This time we will add the 45: // listeners as anonymous inner classes. 46: clearbutton.addactionlistener(new ActionListener() { 47: public void actionperformed(actionevent e) { 48: model.clearall(); 49: paintpanel.repaint(); 50: } 51: }); 52: startbutton.addactionlistener(new ActionListener() { 53: public void actionperformed(actionevent e) { 54: model.start(); 55: } 56: }); 57: stopbutton.addactionlistener(new ActionListener() { 58: public void actionperformed(actionevent e) { 59: model.stop(); 60: } 61: }); 62: 63: // For mouse events we also use an anonymous inner class 64: // only here we retain a reference to it so that it can 65: // be added as both a MouseListener and a MouseMotionListener 66: MouseAdapter mymouseadapter = new MouseAdapter() { 67: public void mousepressed(mouseevent e) { 68: int cellx = e.getx() / paintpanel.cw; 69: int celly = e.gety() / paintpanel.ch; 70: 71: if (cellx >= 0 && cellx < model.getwidth() && 72: celly >= 0 && celly < model.getheight()) { 73: model.setvalue(cellx, celly, true); 74: paintpanel.repaint(); 75: } 76: }

GameOfLife.java Page 2 of 3 77: 78: public void mousedragged(mouseevent e) { 79: mousepressed(e); 80: } 81: }; 82: paintpanel.addmouselistener(mymouseadapter); 83: paintpanel.addmousemotionlistener(mymouseadapter); 84: 85: // Create a timer object with a specific interval in 86: // milliseconds. Create a listener to update the model. 87: // Note that timer events require an ActionListener, just 88: // like JButton events. 89: Timer timer = new Timer(100, new ActionListener() { 90: public void actionperformed(actionevent e) { 91: model.step(); 92: paintpanel.repaint(); 93: } 94: }); 95: timer.start(); 96: 97: frame.pack(); 98: frame.setresizable(false); // Must not be resizable because we aren t 99: frame.setvisible(true); // handling changes in size. 100: } 101: 102: public static void main(string[] args) throws Exception { 103: SwingUtilities.invokeLater(new Runnable() { 104: public void run() { 105: new GameOfLife(); 106: } 107: }); 108: } 109: } 110: 111: class LifeModel extends GridModel { 112: // Used to store the new grid created on each call to step. 113: private boolean nextgrid[][]; 114: private boolean started = false; 115: 116: LifeModel(int width, int height) { 117: super(width, height); 118: nextgrid = new boolean[width][height]; 119: } 120: 121: // Allow the simulation to proceed. 122: void start() { 123: started = true; 124: } 125: 126: // Prevent the simulation from proceeding. 127: void stop() { 128: started = false; 129: } 130: 131: // Execute one iteration, updating grid according 132: // to the Game of Life rules. 133: void step() { 134: if (!started) 135: return; 136: 137: // Implement rules for Conway s Game of Life, for all grid 138: // cells not on the outside border. 139: for (int i=1; i<width-1; i++) 140: for (int j=1; j<height-1; j++) { 141: // Count the number of live neighbours. 142: int count = 0; 143: if (grid[i-1][j-1]) count++; 144: if (grid[i ][j-1]) count++; 145: if (grid[i+1][j-1]) count++; 146: if (grid[i-1][j ]) count++; 147: if (grid[i+1][j ]) count++; 148: if (grid[i-1][j+1]) count++; 149: if (grid[i ][j+1]) count++; 150: if (grid[i+1][j+1]) count++; 151: 152: if (grid[i][j]) 153: // A living cell will stays alive only if it

GameOfLife.java Page 3 of 3 154: // has exactly 2 or 3 living neighbours. 155: nextgrid[i][j] = count==2 count==3; 156: else 157: // A dead cell will only come back to life 158: // if it has exactly 3 living neighbours. 159: nextgrid[i][j] = count==3; 160: } 161: 162: // Swap the two grid references 163: boolean tmp[][] = grid; 164: grid = nextgrid; 165: nextgrid = tmp; 166: } 167: }