Search code examples
javaswinguser-interfacestackjlabel

How to print Stack in a JLabel?


I have a method that prints a stack, however, it prints via System.out.println and I need to print it to a JLabel instead, so that it's visible in my GUI.

I'm using the UI designer from Netbeans, so I have a JFrame file, a main class file, and a stack file where I wrote the showStack method. "Pila" is a class that extends Stack.

This is the method

public void showStack(Pila<Integer> s){  
        if (s.isEmpty())  
            return;  

        Integer x = s.peek();  
        s.pop();  
        showStack(s);  

        System.out.print(x + " ");  
        s.push(x);  
    }  

I want to get rid of the System.out.print and replace it with something I could use to print the stack in a Jlabel


Solution

  • you can make a function that returns a String, and put that String on your label's text. I think it would work with the same code you have for your console prints, but concatenating it in a String instead of printing it

    String output; // this one is to concatenate your String
    public String returnStack(Pila<Integer> s){
        if (s.isEmpty())  {
            return "";
        }
    
        Integer x = s.peek();  
        s.pop();  
        showStack(s);  
    
        output+= x + " ";  
        s.push(x);
        return output;
    }