Som Adhikari Som Adhikari - 7 months ago 21
Java Question

How to take value of JTextfield declared in main function from outside of main function?

I've declared text field as:

public class ContactInformation implements ActionListener {
private JTextField finame;
private JTextField laname;
private JTextField dist;
private JTextField cty;

public static void main(String [] args) throws Exception{
JTextField fname = new JTextField(20);
JTextField lname = new JTextField(20);
JTextField district = new JTextField(20);
JTextField city = new JTextField(20);

public void insertUser(){
try {
contains = DriverManager.getConnection("jdbc:mysql://localhost:3306/contact_info","root","");
System.out.println("Connection established");
stmt = contains.prepareStatement(insertUser);
int rowinserted = stmt.executeUpdate();
if (rowinserted>0){
System.out.println("Inserted successfully!!!");

So, my program structure is like above. In this code I have to take value from text box into
[in the field a there should be value of text field].

How I get value from text box to


If you want to have the value of your JTextField "finame" as a, you must write:

stmt.setString(1, finame.getText());

Also your creating new JTextFields in your main, not the ones you declared in your class! You must create an constructor and create them in it: Correct:

public static void ContactInformation(String [] args) throws Exception{
    finame = new JTextField(20);
    laname = new JTextField(20);
    dist = new JTextField(20);
    cty = new JTextField(20);

Notice the missing "JTextField" and the corrected names.

In your main-Method you have to call that constructor:

public static void main(String [] args) throws Exception{
    ContactInformation contactInformation = new ContactInformation();
    //TODO work with contactInformation