Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
java swings program

Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JFrameExample
{   
    private JFrame frame;
    private JButton button;
    private JTextField tfield;
    private String nameTField;
    private int count;

    public JFrameExample()
    {
        nameTField = "tField";
        count = 0;
    }

    private void displayGUI()
    {
        frame = new JFrame("JFrame Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(0, 1, 2, 2));
        button = new JButton("Add JTextField");
        button.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                tfield = new JTextField();
                tfield.setName(nameTField + count);
                count++;
                frame.add(tfield);
                frame.revalidate();  // For JDK 1.7 or above.
                //frame.getContentPane().revalidate(); // For JDK 1.6 or below.
                frame.repaint();
            }
        });
        frame.add(button);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new JFrameExample().displayGUI();
            }
        });
    }
}


here i generate text fields dynamically i have problem here, i don't get the values entered in text fields because of text fields names are dynamically generated please suggest me .................,


[edit]Code block added - OriginalGriff[/edit]
Posted
Updated 15-Dec-12 23:26pm
v2
Comments
paonerockstar 16-Dec-12 9:58am    
when i use tfield.getText(); it shows error and i don't get any value from it,and i want store this values in individual variables to use further validations,
please suggest me to use it...............................................,,

1 solution

You are setting the name of the JTextField - fine. You should be able to refer to that:

Version 1:
A FocusListener reacts when you leave the textfield:

Java
public class JFrameExample {
	private JFrame frame;
	private JButton button;
	private final String nameTField = "tField"; // fix that sh*t
	private int count;

	public JFrameExample() {
		count = 0;
	}

	private void displayGUI() {
		frame = new JFrame("JFrame Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLayout(new GridLayout(0, 1, 2, 2));
		button = new JButton("Add JTextField");
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				// only to be created at runtime, does not need to be a variable
				// much saver
				JTextField tfield = new JTextField(); 
				tfield.setName(nameTField + count);
				tfield.addFocusListener(new MyFocusListener());
				count++;
				frame.add(tfield);
				// frame.revalidate(); // For JDK 1.7 or above.
				frame.getContentPane().validate(); // For JDK 1.6 or below.
				frame.repaint();
			}
		});
		frame.add(button);
		frame.pack();
		frame.setLocationByPlatform(true);
		frame.setVisible(true);
	}

	public static void main(String... args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new JFrameExample().displayGUI();
				
			}
		});
	}
	
	private class MyFocusListener implements FocusListener{

		@Override
		public void focusLost(FocusEvent event) {
			if(event.getSource() instanceof JTextField){ // component is JTextfield
				JTextField txtField = (JTextField)event.getSource();
				System.out.println("Hello, I'm TextField " + txtField.getName());
				System.out.println("My Value is:" + txtField.getText());
				// ACCESS txtField.getText() HERE!!!

			}
		}

		@Override
		public void focusGained(FocusEvent event) { }
	}
}


Version 2:
A KeyListener reacts when you type. Benefit: you can refer to the value at any time. Only use this version when you need to refer to it any time (e.g. instant search), cause it fires an event on every button stroke:

Java
public class JFrameExample {
	private JFrame frame;
	private JButton button;
	private final String nameTField = "tField"; // fix that sh*t
	private int count;

	public JFrameExample() {
		count = 0;
	}

	private void displayGUI() {
		frame = new JFrame("JFrame Example");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setLayout(new GridLayout(0, 1, 2, 2));
		button = new JButton("Add JTextField");
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				// only to be created at runtime, does not need to be a variable
				// much saver
				JTextField tfield = new JTextField(); 
				tfield.setName(nameTField + count);
				tfield.addKeyListener(new MyKeyListener());
				count++;
				frame.add(tfield);
				// frame.revalidate(); // For JDK 1.7 or above.
				frame.getContentPane().validate(); // For JDK 1.6 or below.
				frame.repaint();
			}
		});
		frame.add(button);
		frame.pack();
		frame.setLocationByPlatform(true);
		frame.setVisible(true);
	}

	public static void main(String... args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new JFrameExample().displayGUI();
				
			}
		});
	}
	
	private class MyKeyListener implements KeyListener{

		@Override
		public void keyReleased(KeyEvent event) {
			if(event.getSource() instanceof JTextField){ // component is JTextfield
				JTextField txtField = (JTextField)event.getSource();
				System.out.println("Hello, I'm TextField " + txtField.getName());
				System.out.println("My Value is:" + txtField.getText());
				// ACCESS txtField.getText() HERE!!!
			}
		}

		@Override
		public void keyTyped(KeyEvent e) { }

		@Override
		public void keyPressed(KeyEvent e) { }
	}
}


The code in the Listener is the same.
I hope you see that I've changed the TextField only to be created local in the Actionlistener - that one does not need to be a member. Also the String nameTField - that one is not allowed to change at all, so it's supposed to be final to prevent that.

Finally the general Lik to using Listeners - http://docs.oracle.com/javase/tutorial/uiswing/events/index.html[^]
I recommend to bookmark that, the Tutorials have pretty much info and are written great.
 
Share this answer
 
v2
Comments
paonerockstar 16-Dec-12 9:13am    
when i use tfield.getText(); it shows error and i don't get any value from it,and i want store this values in individual variables to use further validations,
please suggest me to use it...............................................,,
TorstenH. 16-Dec-12 10:28am    
You did not understand - you need to access the information in the Listener, not in the function displayGUI():
I will add comments at those places. PLease look out for "// ACCESS txtField.getText() HERE!!!"


Please follow the link at the end and read about Listeners.
paonerockstar 16-Dec-12 10:44am    
i want store this values in individual and different variables to use further validations,and if i use a single variable the data get from text field is gets overided,so
please suggest me to use it...............................................,,
TorstenH. 17-Dec-12 1:36am    
Then use different variables!

What's the problem? You can identify the textfield - by getName(). Ever thought about if/else conditions?

Come on, THIS is your part.
paonerockstar 18-Dec-12 8:22am    
please mention a example for that...............

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900