Setting the text in jTextField and then retrieving that text

120 views Asked by At
package test2;
public class NewJFrame extends javax.swing.JFrame {

private static void valueGen(javax.swing.JTextField jTextField1) {

    String x = jTextField1.getText();
    System.out.println(x);
}
public NewJFrame() {
    initComponents();
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){                                         
    jTextField1.setText("Hello");

}                                        

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            

}                                           

public javax.swing.JTextField getTextField() {
    jTextField1.getText();
    return this.jTextField1;
}

public static void main(String args[]) {

     NewJFrame myFrame = new NewJFrame();
     valueGen(myFrame.getTextField());

     java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });

}

private javax.swing.JButton jButton1;
private javax.swing.JTextField jTextField1;

}

I have a program as shown above. I need to set the text "hello" in a text field when the submit button is clicked. It works. But then i need to use that text in a function called valueGen where it is printed. But the text doesn't get printed by executing the above code. What is wrong with this code?

2

There are 2 answers

0
chalitha geekiyanage On

In netbeans out put of the System.out.println(); will be displayed in the output window as shown in the bellow picture. If you want to display it as a message replace the following method with your valueGen() method.

private static void valueGen(javax.swing.JTextField jTextField1) {

String x = jTextField1.getText();
System.out.println(x);
JOptionPane.showMessageDialog(null, x);
}

And use myFrame.setVisible(true); to make visible your JFrame.

public void run() {

            NewJFrame myFrame = new NewJFrame();
            myFrame.setVisible(true);
 valueGen(myFrame.getTextField());
        }

Out put of System.out.println()

1
Blue On
  1. It's unorganized. Always put class variables at the top.

  2. Like Cool Guy said, put myFrame instead of new NewJTest()

  3. valueGen is actually being called before you can click the button. Put it in the jTextField1ActionPerformed; that might fix it.