Skip to content
Advertisement

How to get text from same Text Field used multiple times in Java Swing

I’m trying to get text from a JTextField iterated through my code (apparently, I can’t add a different text field from a button). Here’s what the “Add Items” button do:

addButton.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
        tf = new JTextField("Name",20);
        tfv = new JTextField("Value", 7); 
        
        p.revalidate();
        p.repaint();   
        
        p.add(tf);
        p.add(tfv);
    }
});

It adds two new text fields in the panel using FlowLayout. Now, I want to get the text given by the user from text fields with each one assigned to a different variable or maybe into an ArrayList by clickin the “OK” button but the getText() method doesn’t seem to work.

okButton.addActionListener( e -> {
    
        String txt = tfv.getText(); //only captures the text from the last field in the panel

});

Can’t seem to think of anything right now.

enter image description here

Advertisement

Answer

in this code when you are reinitializing tf and tfv in addButton you lost the reference to previous defined textfiels

tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);

so to solve this problem you need to define an ArrayList to hold reference to all defined textfields and then you can access to all of them:

ArrayList<JTextField> arrayNames  = new ArrayList<JTextField>();
ArrayList<JTextField> arrayValues = new ArrayList<JTextField>();

addButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        tf = new JTextField("Name",20);
        tfv = new JTextField("Value", 7); 
        
        p.revalidate();
        p.repaint();   
        
        p.add(tf);
        p.add(tfv);

        arrayNames.add(tf);
        arrayValues.add(tfv);
    }
});

accessing

okButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        for (JTextField txtValue : arrayValues) {
            System.out.println(txtValue.getText());
        }
    }
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement