0 Replies - 1381 Views - Last Post: 18 February 2013 - 01:33 PM Rate Topic: -----

#1 GoosieLoosie   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 18-February 13

GUI Life Lab, need to display each generation

Posted 18 February 2013 - 01:33 PM

I have gotten my program to draw stuff, save and open in ppm, and use the buttons
I just need the gui to show the changing of each generation and what the next result will be
Thanks peoples

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.Timer.*;
public class LIFEGUI {
    public static void main(String[] args) {
        MyGUI gui = new MyGUI();
    }
}
class MyGUI implements ActionListener {
    Timer timer;
    Color color = Color.RED;
    MyDrawingPanel drawingPanel;
    int h = 40; //height
    int w = 40; //width
    //array for specifications of each click; 3 stands for the 3 positions R,G,B
    int [][][] specArr = new int[w][h][3];
    JButton clearButton = new JButton("Clear");
    JButton startButton = new JButton("Start");
    JButton stopButton = new JButton("Stop");
    JRadioButton single = new JRadioButton();
    JRadioButton cont = new JRadioButton();
    JLabel genLabel = new JLabel("Generation: 0");
    JSlider slider = new JSlider(0, 5000);
    private boolean gameInProgress = false;
    private int genCount = 0;
    LifeArray mouse; 
    LifeArray[][] game;
    
    MyGUI() {
        // Create Java Window
        JFrame window = new JFrame("The Game of Life");
        window.setBounds(100, 100, 445, 600);
        window.setResizable(false);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        //MenuBar elements
        JMenuBar myBar = new JMenuBar();
        JMenu fileMenu = new JMenu("file", true);
        JMenu editMenu = new JMenu("edit", true);
        JMenuItem open = new JMenuItem("open", 'o');
        JMenuItem save = new JMenuItem("save", 's');
        JMenuItem clear = new JMenuItem("clear", 'c');
        fileMenu.add(open);
        fileMenu.add(save);
        editMenu.add(clear);
        myBar.add(fileMenu);
        myBar.add(editMenu);
        open.addActionListener(this);
        save.addActionListener(this);
        clear.addActionListener(this);
        window.setJMenuBar(myBar);

        //MouseListener and MouseMotionListener
        LifeArray mouse = new LifeArray();
        //array of current game
        game = new LifeArray[w+2][h+2];//the +2's act as buffer
        //give the cells a coordinate point (kind of like initializing)
        for (int p = 0; p < w + 2; p++) {
            for (int q = 0; q < h + 2; q++) {
                game[p][q] = new LifeArray();
            }
        }
        
        // JPanel to draw in
        drawingPanel = new MyDrawingPanel();
        drawingPanel.setBounds(20, 20, 400,400);
        drawingPanel.setBorder(BorderFactory.createEtchedBorder());
        drawingPanel.addMouseListener(mouse);
        drawingPanel.addMouseMotionListener(mouse);
        
        JLabel sliderLabel = new JLabel("Pick a speed");
        sliderLabel.setBounds(40, 500, 85, 20);
        slider.setBounds(140, 500, 250, 20);
        genLabel.setBounds(325, 430, 75, 40);
        
        startButton.setBounds(50, 430, 75, 20);
        stopButton.setBounds(50, 460, 75, 20);
        clearButton.setBounds(330, 460, 75, 20);
        
        JLabel singleLabel = new JLabel("Single Step");
        JLabel contLabel = new JLabel("Continuous");
        
        single.setBounds(160, 430, 20, 20);
        cont.setBounds(160, 455, 20, 20);
        singleLabel.setBounds(180, 430, 75, 20);
        contLabel.setBounds(180, 455, 75, 20);
        
        ButtonGroup radioGroup = new ButtonGroup();
        radioGroup.add(single);
        radioGroup.add(cont);
        
        listener select = new listener();
        clearButton.addActionListener(select);
        startButton.addActionListener(select);
        stopButton.addActionListener(select);
        timer = new javax.swing.Timer(5000-slider.getValue(), select);
        //if bar is set to 1 (or slider value 1000), the delay is 4000
        //if set to 4 (or 4000), the delay is less, so its inverted

        // Add GUI elements to the Java window's ContentPane
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(null);

        mainPanel.add(drawingPanel);
        mainPanel.add(clearButton);
        mainPanel.add(startButton);
        mainPanel.add(stopButton);
        mainPanel.add(single);
        mainPanel.add(cont);
        mainPanel.add(singleLabel);
        mainPanel.add(contLabel);
        mainPanel.add(slider);
        mainPanel.add(genLabel);
        mainPanel.add(sliderLabel);

        window.getContentPane().add(mainPanel);
        resetArray();
        window.setVisible(true);
    }
    public class listener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            System.out.println("HI");
            Object option = e.getSource();
            if(option == clearButton) {
                timer.stop();//at beginning so that stops and then does other stuff
                gameInProgress = false;
                //read about enabling in JComponent API, visually easier
                clearButton.setEnabled(false);
                startButton.setEnabled(true);
                clearDraw();
                genCount = 0;
                genLabel.setText("Generation: 0");
                return;//so that it exits
            }
            if(option == startButton) {
                System.out.println("START");
                stopButton.setEnabled(true);//do opposite
                startButton.setEnabled(false);
                gameInProgress = true;
                timer.setDelay(5000-slider.getValue());
                timer.start();//sets all specifications and then only starts
                return;
            }
            if(option == stopButton) {
                System.out.println("STOP");
                timer.stop();
                gameInProgress = false;
                stopButton.setEnabled(false);
                startButton.setEnabled(true);
                return;
            }
            timer.setDelay(5000-slider.getValue());
            //you have to do that to be ready for the next timer value
            //if game is not in progress
            if (gameInProgress == false)
                return;
            //if game IS in  progress, update label
            genCount++;
            //System.out.println("Generation: " + genCount);
            genLabel.setText("Generation: " + genCount);
            //and now check whether cells should be alive/update accordingly
            for(int row = 0; row < game.length; row++) {
                for(int col = 0; col < game[row].length; col++) {
                    game[row][col].checkIfAlive();
                }
            }
            for(int row = 0; row < game.length; row++) {
                for(int col = 0; col < game[row].length; col++) {
                    game[row][col].changeColor();
                }
            }
        }
    }
    //re-initializing all to white when called
    private void resetArray(){
        for (int a = 0; a < w; a++) {
            for (int b = 0; b < h; b++) {
                for (int c = 0; c < 3; c++) {
                    specArr[a][b][c] = 255;
                }
            }
        }
    }
    public void saveFile() {
        JFileChooser saving = new JFileChooser();
        int option = saving.showSaveDialog(null);
        if (option == JFileChooser.APPROVE_OPTION) {
            if (saving.getSelectedFile() != null) {
                File file = saving.getSelectedFile();
                try {
                    //ppm is pretty much like writing to a text file...
                    FileWriter fw = new FileWriter(file);
                    fw.write("P3\r\n" + "#breakpoint\r\n" + w +" "+ h + "\r\n");
                    fw.write(255 + "\r\n");//first value
                    //backwards nest
                    for (int y = 0; y < h; y++) {
                        for (int x = 0; x < w; x++) {
                            fw.write(specArr[x][y][0] +"\t" + specArr[x][y][1] +"\t" + specArr[x][y][2] + "\t"); 
                        }
                        fw.write("\r\n");
                    }
                    fw.close();
                    System.out.println("Now saved as: " + file.getName());
                } catch(Exception ex) {System.out.println("Error: " + ex.getMessage());   
                }
            }
        }
    }
    public void openFile() {
        clearDraw();//initialize the board
        JFileChooser opening = new JFileChooser();
        int op = opening.showOpenDialog(null);
        File file = opening.getSelectedFile();
        try {
            Scanner input = new Scanner(file);
            //this next stuff is pretty much wiki translated..
            if (input.nextLine().equals("P3")) {
                while(input.hasNextLine() == true) {
                    if (input.nextLine().contains("#"))
                        break;
                }
                w = input.nextInt();//they are the next 2 numbers in the output
                h = input.nextInt();
                input.nextInt();
                try {//extract the colors with this try
                    for (int y = 0; y < h; y++) {
                        for (int x = 0; x < w; x++) {
                            color = new Color(input.nextInt(), input.nextInt(), input.nextInt());
                            Graphics g = drawingPanel.getGraphics();
                            g.setColor(color);
                            int ps = 400/w; //doesnt matter whether w or h since square
                            g.fillRect(x*ps, y*ps, ps, ps);
                            g.setColor(Color.LIGHT_GRAY);
                            g.drawRect(x*ps, y*ps, ps, ps);
                            try {//stores the color
                                specArr[x][y][0] = color.getRed();
                                specArr[x][y][1] = color.getGreen();
                                specArr[x][y][2] = color.getBlue();
                            } catch(Exception ex) {System.out.println("Error: " + ex.getMessage());}
                        }
                    }
                } catch(Exception e) {System.out.println("Error: " + e.getMessage());
                }                
            } else {
                System.out.println("Incorrect file type (wrong ext)");
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
    public void actionPerformed(ActionEvent e) {
        //System.out.println("Action -> " + e.getActionCommand());
        JFileChooser fc = new JFileChooser();
        if (e.getActionCommand().equals("clear"))
            clearDraw();
        if (e.getActionCommand().equals("save"))
            saveFile();
        if (e.getActionCommand().equals("open"))
            openFile();
    }
    public void clearDraw() {
        drawingPanel.repaint();
        drawingPanel.paintComponent(drawingPanel.getGraphics());
        resetArray(); //have to reset here too so you can add new color
    }
    private class MyDrawingPanel extends JPanel {
        // Not required, but gets rid of the serialVersionUID warning.  Google it, if desired.
        static final long serialVersionUID = 1234567890L;
        public void paintComponent(Graphics g) {
            g.setColor(Color.white);
            g.fillRect(2, 2, this.getWidth()-2, this.getHeight()-2);
            g.setColor(Color.lightGray);
            for (int x = 0; x < this.getWidth(); x += 400/h)
                g.drawLine(x, 0, x, this.getHeight());
            for (int y = 0; y < this.getHeight(); y += 400/w)
                g.drawLine(0, y, this.getWidth(), y);
        }
    }  
    public class LifeArray implements MouseListener, MouseMotionListener {
        private int curCon = 0, newCon = 0, around, numAlive = 0;
        //current condition, new condition, and surrounding bacteria
        LifeArray[] surrounding = new LifeArray[8];//check all sides
        
        //brainstorm list of the methods I would use with gui
        //need a method to add a surrounding bacteria
        //need to check if alive or not, and increase number if yes
        //change the color according to dead/alive state
        
        public void addSurrounding(LifeArray x) {
            surrounding[around++] = x;//x is an array
        }
        public void checkIfAlive() {
            numAlive = 0;
            for (int n = 0; n < around; n++) {
                numAlive += surrounding[n].curCon;
            }
            if (curCon == 1) {
                if ((numAlive > 3) || (numAlive < 2)) {
                    newCon = 0;//0 is dead
                }
            }
            else if (numAlive == 3) {
                newCon = 1; //1 is alive
            }
        }
        public void changeColor() {
            if (newCon == curCon)
                ;
            else {
                curCon = newCon;
                if (curCon == 0) {
                    color = Color.WHITE;
                } else {
                    color = Color.RED;
                }
            }
        }
        public void mouseClicked(MouseEvent e) { }
        public void mouseEntered(MouseEvent e) { }
        public void mouseExited(MouseEvent e) { }
        public void mousePressed(MouseEvent e) {
            int ps = 400/w; //pixel size
            Graphics g = drawingPanel.getGraphics();
            if ((e.getModifiersEx() & e.BUTTON1_DOWN_MASK) == e.BUTTON1_DOWN_MASK) {
                g.setColor(color);
            }
            else if ((e.getModifiersEx() & e.BUTTON3_DOWN_MASK) == e.BUTTON3_DOWN_MASK) {
                g.setColor(Color.WHITE);
            }
            try {//stores the color
                specArr[e.getX()/ps][e.getY()/ps][0] = color.getRed();
                specArr[e.getX()/ps][e.getY()/ps][1] = color.getGreen();
                specArr[e.getX()/ps][e.getY()/ps][2] = color.getBlue();
            } catch(Exception ex) {System.out.println("Error: " + ex.getMessage());}
            g.fillRect(e.getX()/ps*ps, e.getY()/ps*ps, ps, ps);
            g.setColor(Color.LIGHT_GRAY);
            g.drawRect(e.getX()/ps*ps, e.getY()/ps*ps, ps, ps);
        }
        public void mouseReleased(MouseEvent e) { }
        public void mouseMoved(MouseEvent e) { }
        public void mouseDragged(MouseEvent e) {
            int ps = 400/w; //pixel size
            Graphics g = drawingPanel.getGraphics();
            if ((e.getModifiersEx() & e.BUTTON1_DOWN_MASK) == e.BUTTON1_DOWN_MASK) {               
                    g.setColor(color);
            }
            else if ((e.getModifiersEx() & e.BUTTON3_DOWN_MASK) == e.BUTTON3_DOWN_MASK) {
                g.setColor(Color.WHITE);
            }
            try {//stores the color
                specArr[e.getX()/ps][e.getY()/ps][0] = color.getRed();
                specArr[e.getX()/ps][e.getY()/ps][1] = color.getGreen();
                specArr[e.getX()/ps][e.getY()/ps][2] = color.getBlue();
            } catch(Exception ex) {System.out.println("Error: " + ex.getMessage());}
            g.fillRect(e.getX()/ ps*ps, e.getY()/ ps*ps, ps, ps);
            g.setColor(Color.LIGHT_GRAY);
            g.drawRect(e.getX()/ ps*ps, e.getY()/ ps*ps, ps, ps);
        }  
    }
}



Is This A Good Question/Topic? 0
  • +

Page 1 of 1