Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: Java
java swings program
 
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 15-Dec-12 23:19pm
Edited 15-Dec-12 23:26pm
v2
Comments
paonerockstar at 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

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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:
 
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:
 
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.
  Permalink  
v2
Comments
paonerockstar at 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. at 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 at 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. at 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 at 18-Dec-12 8:22am
   
please mention a example for that...............
TorstenH. at 18-Dec-12 11:54am
   
same here:
 
no.
If you can't figure how to do that - try this
Seriously, this is just basic stuff.
You should understand my above code (that I commented 100% more than usually!), and be able to work with it.
You will get into serious trouble if that is already to complicated.
 
The ActionListener asks for the name of the txtField - so please refer to that.
If you need more specific names for the textField - try to use an Enum.
 
did you run my code? did it run?
Or to ask back: what is the problem?
paonerockstar at 1-Jan-13 12:01pm
   
Thank You for helping me to solve this problem.............,

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 645
1 OriginalGriff 335
2 CPallini 250
3 PIEBALDconsult 150
4 Fredrik Bornander 130
0 OriginalGriff 5,835
1 Sergey Alexandrovich Kryukov 5,198
2 CPallini 4,740
3 George Jonsson 3,167
4 Gihan Liyanage 2,470


Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 1 Jan 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100