subas chandran
subas chandran

Reputation: 13

How to get data from a textfield in java and display it into a jlabel on the second form

I was trying to build a simple java GUI application to get the data from the user and display it to the label.

I got this code from the internet but it is using a separate pane for displaying the result.

     import javax.swing.*;
     import java.awt.*;
     import java.awt.event.*;
     public class JTextFieldDemo extends JFrame {

//Class Declarations
JTextField jtfText1, jtfUneditableText;
String disp = "";
TextHandler handler = null;
//Constructor
public JTextFieldDemo() {
    super("TextField Test Demo");
    Container container = getContentPane();
    container.setLayout(new FlowLayout());
    jtfText1 = new JTextField(10);
    jtfUneditableText = new JTextField("Uneditable text field", 20);
    jtfUneditableText.setEditable(false);
    container.add(jtfText1);
    container.add(jtfUneditableText);
    handler = new TextHandler();
    jtfText1.addActionListener(handler);
    jtfUneditableText.addActionListener(handler);
    setSize(325, 100);
    setVisible(true);
}
//Inner Class TextHandler
private class TextHandler implements ActionListener {

            @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jtfText1) {
            disp = "text1 : " + e.getActionCommand();
        } else if (e.getSource() == jtfUneditableText) {
            disp = "text3 : " + e.getActionCommand();
        }
        JOptionPane.showMessageDialog(null, disp);
    }
}
//Main Program that starts Execution
public static void main(String args[]) {
    JTextFieldDemo test = new JTextFieldDemo();
    test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Upvotes: 1

Views: 23428

Answers (1)

cafebabe1991
cafebabe1991

Reputation: 5176

  1. Get the text from the TextField (textField).

    String text=textField.getText().toString();

  2. Now set it to the label using setText on the JLabel.

    jlabel.setText(text);

  3. new SecondForm(jlabel,text).setVisible(true);

If the Label exists on the next form say SecondForm. Skip Step2 and Do Step 3 after step 1

public class SecondForm  extends JFrame{


    public SecondForm(JLabel label,String text){

    label.setText(text); }

}

Upvotes: 1

Related Questions