Search code examples
javapopupjtextfield

How to print a string on the same window I typed and not in a popup in Java


So, this is my code:

import java.awt.*;
import javax.swing.*:

public class NewClass extends JFrame{
    private JTextField item1;
    private JTextField item3;
    private JTextField item4;

    public NewClass(){
        super("The title");
        setLayout(new FlowLayout());

        item3 = new JTextField("Agrega el nombre del evento y da Enter", 22);
        item3.setEditable(false);
        add(item3);

        item1 = new JTextField(22);
        add(item1);


        thehandler handler = new thehandler();
        item1.addActionListener(handler);
        item3.addActionListener(handler);
        item4.addActionListener(handler);

    }

    private class thehandler implements ActionListener{

        public void actionPerformed(ActionEvent event){

            String string = "";

            if(event.getSource()==item1)
                string=String.format("Process ready: %s", event.getActionCommand());
            else if(event.getSource()==item3)
                string=String.format("field 3:%s", event.getActionCommand());


            JOptionPane.showMessageDialog(null, string);
        }
    }

}

And this is my main:

import javax.swing.JFrame;

public class ProyectoSOD {
    public static void main(String[] args) {

        NewClass odioSOD = new NewClass();
        odioSOD.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        odioSOD.setSize(300, 350);
        odioSOD.setVisible(true);
    }

}

What I want to do, is to have the text in the TextField(from item3) saved unto another TextField with .setEditable(false) in the same window so I can write a text line(on item3), press enter, and have it saved in the same window, then rewrite the line, press enter, and have it shown with the previous text. I wanna be able to stack all this text everytime I press enter.

My current program has the message shown in a popup window, but I need to stack multiple lines.

Thanks :)


Solution

  • I'm not sure what you're looking to do. If you want to keep track of everything entered into the textfield, like a history of input, you could do what Eric Jablow said and use a JTextArea. So when the user enters input into the textfield and hits enter, it'll append the text from the textfield into the textarea.

    http://docs.oracle.com/javase/tutorial/uiswing/components/textarea.html

    That might be a good place to start.