2

I've got some classes which include toString functions which work very well as:

snipped of declaration:

public String toString() {
        return "Port info: "+myPort.variable;
    }

snipped of main():

Port myPort;
myPort.fillInfo();
system.out.println(myPort);

output:

"Port info: 123"

I'm trying to replace all my system.out.println(myPort) calls with myWindow.println(myPort) calls where myWindow contains:

public void println(String toPrint)
{
    textArea.append(toPrint+"\n"); //or insert
}

However, I'm getting:

The method println(String) in the type window is not applicable for the arguments (Port)

In other words, my declaration is expecting the String type, and I'm trying to pass it the Port type.

Somehow, system.out.println() will take any class that's got a toString() declared.

How does system.out.println take any class and print it out, and run its toString() method if it exists? And, more to the point, how can I replicate this functionality for my own println() function?

Matt
  • 21
  • 1
  • 2
  • 1
    You could just redirect the `System.out` to your `JTextArea` directly (no need to replace the statements`), something like [this for example](http://stackoverflow.com/questions/12945537/how-to-set-output-stream-to-textarea/12945678#12945678) – MadProgrammer Feb 12 '16 at 01:49

4 Answers4

3

Change your Window to

public void println(Object obj)
{
    textArea.append(obj +"\n"); 
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
2

PrintStream.println has an overload that takes an Object argument. You can make your println do the same.

C. K. Young
  • 219,335
  • 46
  • 382
  • 435
2

First, please don't use \n as a line separator (it isn't portable). In addition to overloading println(Object), you could make your method generic. Something like

public <T> void println(T obj)
{
    textArea.append(String.format("%s%n", obj)); 
}

or

public void println(Object obj)
{
    textArea.append(String.format("%s%n", obj)); 
}

or

public void println(Object obj)
{
    textArea.append((obj == null ? "null" : obj.toString()) 
            + System.lineSeparator()); 
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

The problem is that System.out has a method to print to console an object as it contains for all primitive data types. The thing about this is that as all methods have the same name and just change the data type of the parameter you want to print, you think you can pass an object by a string and is not. The method .println() automatically takes which passes an object. Within this method .println() he takes the object that you indicated by parameters and calls his method .toString() to obtain the string representation of the object and printed on the console.

If you want to print any type of object you must declare your parameter as object type and invoke the method .toString() from the object and print that information.