I want to close the program when the mause is clicked , but i don`t know how tu use these methods.
Thus is teh code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.applet.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
//import java.awt.event.*;
public class Life5 extends JApplet{
public static void main(String s[]) {
JFrame frame = new JFrame();
frame.setTitle("Game of Life");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new Life5();
applet.init();
frame.getContentPane().add(applet);
frame.pack();
frame.setVisible(true);
}
public void init() {
JPanel panel = new LifePanel();
getContentPane().add(panel);
}
}
class LifePanel extends JPanel implements ActionListener,MouseListener{
// MouseListener methods
public void mouseClicked(MouseEvent e){
//System.exit(0);
}
public void mouseEntered(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mousePressed(MouseEvent e){
}
public void mouseReleased(MouseEvent e){
}
int n = 221;
boolean[][] cells1;
boolean[][] cells2;
public LifePanel() {
setPreferredSize(new Dimension(400, 400));
setBackground(Color.white);
cells1 = new boolean[n][n];
cells2 = new boolean[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cells1[i][j] = false;
cells2[i][j] = false;
}
}
cells1[(n/2)][(n/2)] = true;
Timer timer = new Timer(1000, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.lightGray);
int p = 0;
int c = 2;
int len = 443;
for (int i = 0; i <= n; i++) {
g2.drawLine(0, p, len, p);
g2.drawLine(p, 0, p, len);
p += 2;
}
g2.setColor(Color.black);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (cells1[i][j]) {
int x = i*c;
int y = j*c;
g2.fillOval(x, y, c, c);
}
}
}
}
public void actionPerformed(ActionEvent e) {
boolean[][] cells = cells1;
for (int i = 0; i < n ; i++) {
for (int j = 0; j < n ; j++) {
cells2[i][j] = cells[i][j];
int nb = neighbors(cells,i, j);
if(cells2[i][j] == false && nb != 1)
cells2[i][j] = true;
else if( cells2[i][j] == true && (nb == 1 || nb == 3))
cells2[i][j] = true;
else{ cells2[i][j] = false;}
//System.out.println(nb);
}
}
cells1 = cells2;
cells2 = cells;
repaint();
}
private int countNeighbor(boolean[][] cells,int x, int y) {
if (x<0||x>n-1) { return 0; }
if (y<0||y>n-1) { return 0; }
return cells[x][y] ? 1 : 0;
}
private int neighbors(boolean[][] cells,int x, int y) {
return countNeighbor(cells,x, y-1)
+ countNeighbor(cells,x, y+1)
+ countNeighbor(cells,x-1, y)
+ countNeighbor(cells,x+1, y);
}
}
This post has been edited by drilli: 04 April 2010 - 03:02 PM

New Topic/Question
Reply




MultiQuote








|