13 Replies - 1008 Views - Last Post: 29 December 2015 - 06:33 AM Rate Topic: -----

#1 afranco527   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-May 14

How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 05:15 PM

Hello everyone,

I am stuck on the last step of my project. I need to make a nice GUI from scratch that shows my programs' output when it is running. When I run my program I get the correct result outputted into IntelliJ's console, but I am not sure how to get it into my GUI.

Background on the project:
I had to create an environment where herbivores, carnivores, and plants interact with each other. These objects are represented by:
& - Herbivore
@ - Carnivore
* - Plant
. - Empty space

EX.
. . . . . . .
. . . . . . .
. & . . . . .
. . . . . . .
. . * . . . .
& . . . * . .
. . . @ . . .

The carnivores and herbivores move around the grid. Carnivores eat herbivores, herbivores eat plants.

My approach to the project was to create an abstract Animal class that my Herbivore and Carnivore class extend, and create an Environment class that contains a grid with all the animals and plants. In my main class I have a For loop that prints the grid to the console and updates the locations of the animals with every iteration.

What I want to do:

I want to get the same exact output that goes in the console into my GUI. Not sure where to begin doing that. My guess is that I have to create a JLabel and put it into the GUI, but I'm not sure how to get my console text into a JLabel object.

My code:

Main class:
import java.awt.*;
import java.util.ArrayList;

public class GameMain
{
    public static void main(String[] args)
    {
        //size of the map
        final int xCoordinate = 7;
        final int yCoordinate = 7;
        Environment environment = new Environment(xCoordinate, yCoordinate);

        GuiDisplay gui = new GuiDisplay();

        //adding herbivores, carnivores, and plants to the environment
        environment.addToObjList(new Herbivore(1, 2));
        environment.addToObjList(new Herbivore(0, 5));

        environment.addToObjList(new Carnivore(3, 6));

        environment.addToObjList(new Plant(4,5));
        environment.addToObjList(new Plant(2,4));

        environment.listToMap();
        environment.print();
        System.out.println();

        ArrayList list = environment.getObjList();
        environment.clearMap();

        ((Carnivore)list.get(2)).setEnergy(20);
        ((Carnivore)list.get(2)).setAge(20);

        for (int j = 0; j < 5; j++)
        {
            for (int i = 0; i < environment.objListSize(); i++)
            {
                //if the animal has an energy of 0, then the animal is dead
                //remove it from the list

                if (list.get(i) instanceof Animal)
                {
                    if (((Animal) list.get(i)).getEnergy() <= 0)
                    {
                        list.remove(i);
                        //break;
                    }

                    else
                    {
                        ((Animal) list.get(i)).randomMove(environment);

                        if (list.get(i) instanceof Animal)
                        {
                            ((Animal) list.get(i)).increaseAge();
                            ((Animal) list.get(i)).decreaseEnergy();
                        }
                    }

                }
            }

            environment.listToMap();
            environment.print();
            System.out.println();
            environment.clearMap();
            list = environment.getObjList();
            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}



Abstract Animal class:
import java.awt.*;

public abstract class Animal
{
    public final int NORTH = 0;
    public final int SOUTH = 1;
    public final int EAST = 2;
    public final int WEST = 3;

    private int energy;
    private int age;
    private Point location;

    public Animal()
    {
        energy = 10;
        age = 1;
        location = new Point();
    }

    public Animal(int x, int y)
    {
        energy = 10;
        age = 1;
        location = new Point(x, y);
    }

    abstract void eat(Object obj);

    abstract boolean targetedMove(Environment environment);

    public int getEnergy() {
        return energy;
    }

    public void setEnergy(int energy) {
        this.energy = energy;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Point getLocation() {
        return location;
    }

    public void setNewLocation(Point point)
    {
        this.location.setLocation(point);
    }

    public void increaseAge() {
        age++;
    }

    public void decreaseEnergy() {
        energy--;
    }

    public void randomMove(Environment environment)
    {
        Point temporaryPoint = location;

        boolean didMove = targetedMove(environment);

        if (didMove == false)
        {
            int x = (int) location.getX();
            int y = (int) location.getY();

            int randomMove = (int) (Math.random() * 4);

            switch (randomMove)
            {
                case NORTH:
                    location.setLocation(x, y + 1);
                    break;
                case SOUTH:
                    location.setLocation(x, y - 1);
                    break;
                case WEST:
                    location.setLocation(x - 1, y);
                    break;
                case EAST:
                    location.setLocation(x + 1, y);
                    break;
            }

            if (location.getX() > environment.getX() - 1 || location.getY() > environment.getY() - 1 || location.getX() < 0 || location.getY() < 0)
                location.setLocation(x, y);
        }
    }

    public Point giveBirth(int maxX, int maxY)
    {
        //original location of the animal
        int x = (int) location.getX();
        int y = (int) location.getY();

        int newX = ((int) (Math.random() * 3) - 1);
        int newY = ((int) (Math.random() * 3) - 1);

        //new location around current animal
        int finalX = x + newX;
        int finalY = y + newY;

        //if the final values for the coordinates are out of the map
        //try again
        while (finalX > maxX - 1 || finalX < 0)
        {
            newX = ((int) (Math.random() * 3) - 1);
            finalX = x + newX;
        }

        while (finalY > maxY - 1 || finalY < 0)
        {
            newY = ((int) (Math.random() * 3) - 1);
            finalY = y + newY;
        }

        //set the new coordinates for the animal
        Point birthCoord = new Point(finalX, finalY);
        return birthCoord;
    }
}



Herbivore class:
import java.awt.*;
import java.lang.reflect.Array;
import java.util.ArrayList;

public class Herbivore extends Animal
{
    public Herbivore(int x, int y)
    {
        super(x,y);
    }

    public void eat(Object obj)
    {
       if (obj instanceof Plant)
       {
           Plant plant = (Plant) obj;

           int plantEnergy = plant.getEnergy();
           int herbEnergy = getEnergy();
           int total = plantEnergy + herbEnergy;

           setEnergy(total);
       }
    }

    public boolean targetedMove(Environment environment)
    {
        Point currentAnimal = getLocation();

        int lowerX = (int)currentAnimal.getX() - 1;
        int lowerY = (int)currentAnimal.getY() - 1;

        int upperX = (int)currentAnimal.getX() + 1;
        int upperY = (int)currentAnimal.getY() + 1;

        if(lowerX < 0)
            lowerX = 0;
        if(lowerY < 0)
            lowerY = 0;

        if (upperX >= environment.getX())
            upperX = environment.getX() - 1;

        if (upperY >= environment.getY())
            upperY = environment.getY() - 1;

        Point searchPoint = new Point(lowerX,lowerY);

        ArrayList objList = environment.getObjList();

        //search:
        for (int y = lowerY; y <= upperY; y++)
        {
            for (int x = lowerX; x <= upperX; x++)
            {
                searchPoint.setLocation(x, y);

                for (int i = 0; i < objList.size(); i++)
                {
                    if (objList.get(i) instanceof Plant)
                    {
                        if (((Plant) objList.get(i)).getLocation().equals(searchPoint))
                        {
                            eat(objList.get(i));
                            environment.removeFromObjList(i);
                            setNewLocation(searchPoint);
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
}




Carnivore class:
import java.awt.*;
import java.util.ArrayList;

public class Carnivore extends Animal
{
    public Carnivore(int x, int y)
    {
        super(x,y);
    }

    public void eat(Object obj)
    {
       if (obj instanceof Herbivore)
       {
           Herbivore herbivore = (Herbivore) obj;

           int herbEnergy = herbivore.getEnergy();
           int carnEnergy = getEnergy();
           int total = herbEnergy + carnEnergy;

           setEnergy(total);
       }
    }

    public boolean targetedMove(Environment environment)
    {
        Point currentAnimal = getLocation();

        int lowerX = (int)currentAnimal.getX() - 1;
        int lowerY = (int)currentAnimal.getY() - 1;

        int upperX = (int)currentAnimal.getX() + 1;
        int upperY = (int)currentAnimal.getY() + 1;

        if (lowerX < 0)
            lowerX = 0;
        if (lowerY < 0)
            lowerY = 0;

        if (upperX >= environment.getX())
            upperX = environment.getX() - 1;

        if (upperY >= environment.getY())
            upperY = environment.getY() - 1;

        Point searchPoint = new Point(lowerX,lowerY);

        ArrayList objList = environment.getObjList();

        //search:
        for (int y = lowerY; y <= upperY; y++)
        {
            for (int x = lowerX; x <= upperX; x++)
            {
                searchPoint.setLocation(x, y);

                for (int i = 0; i < objList.size(); i++)
                {
                    if (objList.get(i) instanceof Herbivore)
                    {
                        if (((Herbivore) objList.get(i)).getLocation().equals(searchPoint))
                        {
                            eat(objList.get(i));
                            environment.removeFromObjList(i);
                            setNewLocation(searchPoint);
                            return true;
                        }
                    }
                }

            }
        }
        return false;

    }

}



Environment class:
import java.awt.*;
import java.util.ArrayList;

public class Environment
{
    private final int x;
    private final int y;
    private Object[][] map;
    private ArrayList objList;

    //constructor
    public Environment(int x, int y)
    {
        this.x = x;
        this.y = y;
        map = new Object[y][x];
        objList = new ArrayList();
    }

    public int getX()
    {
        return x;
    }

    public int getY()
    {
        return y;
    }

    public int objListSize()
    {
        return objList.size();
    }

    public ArrayList getObjList()
    {
        return objList;
    }

    //adds an animal to the objList array
    public void addToObjList(Object obj)
    {
        objList.add(obj);
    }

    public void removeFromObjList(int index)
    {
        objList.remove(index);
    }

    //clears the map to be ready to be written again
    public void clearMap()
    {
        for (int i = 0; i < this.y; i++)
        {
            for (int j = 0; j < this.x; j++)
            {
                map[i][j] = null;
            }
        }
    }

    //adds all the animals from the objList to the Map
    public void listToMap()
    {
        for (int i = 0; i < objList.size(); i++)
        {
            if (objList.get(i) instanceof Carnivore)
            {
                Point coord = ((Carnivore) objList.get(i)).getLocation();

                map[(int)coord.getY()][(int)coord.getX()] = objList.get(i);
            }

            else if (objList.get(i) instanceof Herbivore)
            {
                Point coord = ((Herbivore) objList.get(i)).getLocation();

                map[(int)coord.getY()][(int)coord.getX()] = objList.get(i);
            }

            else if (objList.get(i) instanceof Plant)
            {
                Point coord = ((Plant) objList.get(i)).getLocation();

                if(map[(int)coord.getY()][(int)coord.getX()] instanceof Carnivore)
                {
                    //Don't do anything if there is a carnivore in the spot already
                }

                else
                    map[(int)coord.getY()][(int)coord.getX()] = objList.get(i);
            }
        }
    }

    //print everything in the map to the screen
    public void print()
    {
        for (int i = 0; i < this.y; i++)
        {
            for (int j = 0; j < this.x; j++)
            {
                if (map[i][j] instanceof Plant)
                    System.out.print(" *");

                else if (map[i][j] instanceof Herbivore)
                    System.out.print(" &");

                else if (map[i][j] instanceof Carnivore)
                    System.out.print(" @");

                else if (map[i][j] == null)
                    System.out.print(" .");

                else
                    System.out.print(" .");
            }
            System.out.println();
        }
    }

    public boolean isOccupied(Point location)
    {
        boolean occupied = false;

        for (int i = 0; i < objList.size(); i++)
        {
            if (objList.get(i) instanceof Animal)
            {
                Point coord = ((Animal) objList.get(i)).getLocation();

                if (coord.equals(location))
                {
                    occupied = true;
                    return occupied;
                }
            }

            else if(objList.get(i) instanceof Plant)
            {
                Point coord = ((Plant) objList.get(i)).getLocation();

                if (coord.equals(location))
                {
                    occupied = true;
                    return occupied;
                }
            }
        }

        return occupied;
        /*boolean occupied = false;

        int i = 0;

        while (objList[i] != null)
        {
            if (objList[i].getLocation().equals(location))
            {
                occupied = true;
                break;
            }
            i++;
        }

        return occupied;*/
    }
}



GUI class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GuiDisplay extends JFrame
{
    JFrame frame;
    JPanel westPanel;
    JPanel eastPanel;

    JButton nextIteration;
    JTextArea map;

    public GuiDisplay()
    {
        frame = new JFrame();
        westPanel = new JPanel();
        eastPanel = new JPanel();

        frame.setTitle("Animal Simulation");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        nextIteration = new JButton("Next Iteration");
        eastPanel.setBackground(Color.CYAN);
        eastPanel.add(nextIteration);
        frame.getContentPane().add(BorderLayout.EAST, eastPanel);

        map = new JTextArea(10, 20);
        westPanel.add(map);
        frame.getContentPane().add(BorderLayout.WEST, westPanel);

        frame.setVisible(true);
    }

    class ButtonListner implements ActionListener
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {

        }
    }
}



What should I look into to get the answer I want? I appreciate any input.

Thank you

Is This A Good Question/Topic? 0
  • +

Replies To: How can I make my output from the console appear in my GUI?

#2 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,436
  • Joined: 25-December 13

Re: How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 05:42 PM

Quote

I want to get the same exact output that goes in the console into my GUI.

If that is what you really mean, there might be a way to trap all the print outs sent via System.out
to come to your code which can then put it into the GUI. The System class has a method to change where print out sent via System.out goes. See the setOut() method.
Was This Post Helpful? 1
  • +
  • -

#3 afranco527   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-May 14

Re: How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 06:08 PM

View PostNormR, on 26 December 2015 - 05:42 PM, said:

Quote

I want to get the same exact output that goes in the console into my GUI.

If that is what you really mean, there might be a way to trap all the print outs sent via System.out
to come to your code which can then put it into the GUI. The System class has a method to change where print out sent via System.out goes. See the setOut() method.


Well that is not what I really mean. In the console the grid is printed every iteration of the for loop as the animals change their location. What I want in my gui is to show the current iteration only. The previous printed grid should be erased and replaced with the new iteration.

Thanks for your reply. I will look into the setOut() now.
Was This Post Helpful? 0
  • +
  • -

#4 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,436
  • Joined: 25-December 13

Re: How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 06:18 PM

Sounds like you should rewrite the code to use GUI vs the console.
The setOut() method would allow you to intercept what is printed to the console so that it would still be printed on the console as well as shown somewhere else.
If the code could detect the start of a new display, it could clear the old one before displaying the new one.

This post has been edited by NormR: 26 December 2015 - 06:20 PM

Was This Post Helpful? 1
  • +
  • -

#5 afranco527   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-May 14

Re: How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 06:52 PM

So wherever I have System.out.println I should replace with text.append()?

And I think I can make it clear the old one when it finishes updating all the locations of the animals. Since that is when I print the new display to the console anyway.
Was This Post Helpful? 0
  • +
  • -

#6 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,436
  • Joined: 25-December 13

Re: How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 06:59 PM

Quote

System.out.println I should replace with text.append()

Try it and see if it does what you want.

However you said this:

Quote

gui is to show the current iteration only

So what you suggested won't show you only one iteration at a time.

You can either add a delay between the showing of the iterations
or you could change the logic to allow the user to move to the next iteration by pressing a button.

This post has been edited by NormR: 26 December 2015 - 07:04 PM

Was This Post Helpful? 1
  • +
  • -

#7 afranco527   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-May 14

Re: How can I make my output from the console appear in my GUI?

Posted 26 December 2015 - 09:25 PM

I was able to get it to work by converting the grid into a string and using append(string). The format and spacing got a little messed up in the process though.

[quote name='NormR' date='26 December 2015 - 06:59 PM' timestamp='1451181556' post='2215259']

Quote

or you could change the logic to allow the user to move to the next iteration by pressing a button.


That is what I was planning to do next. How would I do that from main? I would have to implement an action listner, correct? How would I get to pause?
Was This Post Helpful? 0
  • +
  • -

#8 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 834
  • View blog
  • Posts: 6,436
  • Joined: 25-December 13

Re: How can I make my output from the console appear in my GUI?

Posted 27 December 2015 - 05:10 AM

Quote

I would have to implement an action listner, correct? How would I get to pause?

Yes you would need a listener for the button.

The "pause" would be waiting for the user to press the button, not in a loop inside the program. The code would do an iteration on every press of the button. The state of the "loop" would need to be saved by the program and used and updated when the button is pressed.
Was This Post Helpful? 1
  • +
  • -

#9 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: How can I make my output from the console appear in my GUI?

Posted 27 December 2015 - 10:33 AM

Your print contains all your logic. Get it out of there.

Something like:
// ....
// environment.print();
gui.setMap(environment.toString());

class Environment {
    public char getCharAt(int x, int y) { /* your code here */ }
    public String getLine(int y) { /* your code here */ }
    public String [] getLines() { /* your code here */ }

    @Override
    public String toString() {
        return String.join("\n", getLines());
    }

    //print everything in the map to the screen
    public void print() {
        System.out.println(this.toString());
    }
}



There are a number of issues in this code. Any time your find instanceof and casting to be central to you process, you may want to take a step back.

Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#10 afranco527   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-May 14

Re: How can I make my output from the console appear in my GUI?

Posted 27 December 2015 - 05:56 PM

View PostNormR, on 27 December 2015 - 05:10 AM, said:

The "pause" would be waiting for the user to press the button, not in a loop inside the program. The code would do an iteration on every press of the button. The state of the "loop" would need to be saved by the program and used and updated when the button is pressed.


Thanks! My code works perfect now and get the correct output on the gui.


View Postbaavgai, on 27 December 2015 - 10:33 AM, said:

There are a number of issues in this code. Any time your find instanceof and casting to be central to you process, you may want to take a step back.

Hope this helps.


Thanks for your help. Is it because the possible errors this may cause? Should I have kept all the objects in their own arrays of their object type?
Was This Post Helpful? 0
  • +
  • -

#11 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: How can I make my output from the console appear in my GUI?

Posted 28 December 2015 - 04:13 AM

View Postafranco527, on 27 December 2015 - 07:56 PM, said:

Should I have kept all the objects in their own arrays of their object type?


Rather the opposite. Keep one 2D array and actually use a class hierarchy.

e.g.
enum EntityType {
    None('.'), Plant('*'), Herbivore('&'), Carnivore('@');
    private final char symbol;
    EntityType(char symbol) { this.symbol = symbol; }
    public char getSymbol() { return this.symbol; }
}

// yes, Point is nice, but not if you're always casting it
// it's simple, so no need to drag in awt for it
class Location {
    public final int x, y;
    public Location(int x, int y) { this.x = x; this.y = y; }
    public Location() { this(-1,-1); }
}

interface World {
    int getHeight();
    int getWidth();
    void set(Location loc, Entity e);
    Entity get(Location loc);
    public Location [] getPossibleMoves(Location loc);
    // for that reproduction thing
    public Location [] getPossibleMoves(Location loc, int distance);
}

interface Entity {
    EntityType getEntityType();
    boolean eats();
    boolean canEat(Entity food);
    boolean eat(Entity food);
    boolean canReproduce();
    int getEnergy();
    int getAge();
    void next(World world);
    // just a helper
    char getSymbol();
}

class NoEntity implements Entity { }
class Plant implements Entity { }
class Herbivore implements Entity { }
class Carnivore implements Entity { }



Rather than testing:
public void print() {
    for (int i = 0; i < this.y; i++) {
        for (int j = 0; j < this.x; j++) {
            if (map[i][j] instanceof Plant) {
                System.out.print(" *");
            } else if (map[i][j] instanceof Herbivore) {
                System.out.print(" &");
            } else if (map[i][j] instanceof Carnivore) {
                System.out.print(" @");
            } else if (map[i][j] == null) {
                System.out.print(" .");
            } else {
                System.out.print(" .");
            }
        }
        System.out.println();
    }
}



You just print:
public void print(World w) {
    for (int y=0; y<w.getHeight(); y++) {
        for (int x=0; x<w.getWidth(); x++) {
            Entity e = w.get(x,y);
            System.out.print(" " + e.getSymbol());
        }
        System.out.println();
    }
}



Notice that your world iteration should work basically the same way.
    for (int y=0; y<w.getHeight(); y++) {
        for (int x=0; x<w.getWidth(); x++) {
            w.get(x,y).next(w);
        }
    }



Hope this helps.
Was This Post Helpful? 3
  • +
  • -

#12 afranco527   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 11-May 14

Re: How can I make my output from the console appear in my GUI?

Posted 28 December 2015 - 09:20 PM

Ah I didn't know about enums until now. Much better way, thanks. But if I am reading the code correctly, the world is an interface. How would I be able to use it to get the height and width methods?

Thanks again
Was This Post Helpful? 0
  • +
  • -

#13 g00se   User is online

  • D.I.C Lover
  • member icon

Reputation: 3703
  • View blog
  • Posts: 16,975
  • Joined: 20-September 08

Re: How can I make my output from the console appear in my GUI?

Posted 29 December 2015 - 05:44 AM

You really ought to rethink your display. Shoving a console output into a windowed text control is not really using the gui well at all.
Was This Post Helpful? 0
  • +
  • -

#14 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7507
  • View blog
  • Posts: 15,558
  • Joined: 16-October 07

Re: How can I make my output from the console appear in my GUI?

Posted 29 December 2015 - 06:33 AM

View Postafranco527, on 28 December 2015 - 11:20 PM, said:

the world is an interface. How would I be able to use it to get the height and width methods?


Well, you'd implement it. e.g:
class WorldImpl implements World {
    private final int height;
    // ...
    public WorldImpl(int width, int height) {
         this.height = height;
        // your code here
    }
    public int getHeight() { return height; }
    // ...



An interface describes the public methods a class must offer to implement that interface. One advantage to this is that your can list the minimal methods you need to offer to other classes. It also allows you to conceptualize how your classes should talk to each over.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1