Search code examples
javaswingcardlayoutnull-layout-manager

Take JTextArea and add entered contents to a label


Basically I have a program with cards(I'm using the CardLayout), when the user types a sentance or what ever they type I would like that to be added to a label on the following page when they hit a button named create. I'm not sure how i would get the entered field to be saved and placed as a variable into the label. any ideas? I can provide my code if necessary.

createButton2.addActionListener(new ActionListener() {   //Back button listener, switches back to ADMIN fixtures panel
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.show(container, "6");
                String theText = descriptionField.getText();
                fixtureDescLabel.setText( theText );
                fixtureDescLabel.setBounds(250, 150, 200, 40);
                add(fixtureDescLabel);
            }
        });

Solution

  • It's pretty straight forward.

    Take the text from the textArea:

    String theText = myTextArea.getText();
    

    Put in a label:

    myLabel.setText( theText );
    

    In a button listener:

    myButton.addActionListener( new ActionListener() {
        @override public actionPerformed( ActionEvent event )
        {
            String theText = myTextArea.getText();
            myLabel.setText( theText );
        }
    } );
    

    EDIT

    Looking at your edit, your problem is that you add a component to your frame without revalidating (JFrame#revalidate()) it.