Can anyone help me use a JLabel to display a stack??? I've been searching and I can't seem to find the right way to do it. I get errors every time. I think everything is right in my program besides this. Thanks for looking. Here's what I have:
(Am I posting the code right?)

public class GraphicStackPanel extends JPanel {

    private JLabel inputLabel, outputLabel, resultLabel;
    private JTextField pushstring;
    private JButton push, pop;

    int count = 0;

    public GraphicStackPanel(){

        inputLabel = new JLabel ("Enter word here: ");

        pushstring = new JTextField (10);
        push = new JButton ("Push!");
        push.addActionListener (new ButtonListener());

        outputLabel = new JLabel ("Your Stack: ");
        resultLabel = new JLabel ("--");

        pop = new JButton ("Pop!");
        pop.addActionListener (new ButtonListener());


        setPreferredSize (new Dimension (400, 300));
        setBackground (Color.white);
        private class ButtonListener implements ActionListener{

            Stack stack = new Stack();

            public void actionPerformed (ActionEvent event){

            if (event.getSource() == push){
                stack.push (pushstring);

                    stack.pop ();


Edited 3 Years Ago by mike_2000_17: Fixed formatting

No you haven't posted the code right. The last code tag should have a forward slash like this: (/CODE)

For your problem, In your ActionListener you are passing a Stack object to the JLabel setText() method when it was expecting a String.

Instead of using this:


YOu should have this:


and don't forget to remove the extra space in between "pop" and parenthesis:

stack.pop ();

Edited 3 Years Ago by mike_2000_17: Fixed formatting

thanks for your reply jocamps; i actually thought the same thing and had the code like that at first; the program compiled and ran until i entered text into the text field and got the following print when i tried to push: ColorUIResource[r=0,g=0,b=0],disabledTextColor=javax.swing.plaf.Color...etc
and 'EmptyStackCollection' when i tried to pop.
any more suggestions???

set your stack as a global variable. In your code, what happens is, everytime you click a button you created a new Stack object it would work with push() since you have the initial value to be push but when click the pop button, a new Stack object is created which is empty (even if you click push() first).

also you could include an if statement to check if the stack is empty before using pop() method.

just noticed you were using a JTextField , so your stack.push(pushstring) should be :


Edited 7 Years Ago by Jocamps: n/a

This question has already been answered. Start a new discussion instead.