Andrei
Andrei

Reputation: 3588

Swing get JTextField upon JButton press

Apparently my Google-fu skills are bit lacklustre and I can't figure out how to get JTextField when pressing a JButton.

Please note that I've removed some parts of the code for ease of reading.

If you see some variable that's not defined assume that it was part of that code.

As it stands, the code works fine.

public final class Main {
    // Some removed code was here
    private void prepareGUI() {

        // Top right stuff
        JPanel topRightPanel = new JPanel();
        topRightPanel.setLayout(new FlowLayout());
        JLabel topRightLabel = new JLabel("Address");
        JTextField topRightTextField = new JTextField("", 15);
        topRightTextField.setName("add_address");
        JButton topRightButton = new JButton("Add");
        topRightButton.setName("add_btn");

        topRightPanel.add(topRightLabel);
        topRightPanel.add(topRightTextField);
        topRightPanel.add(topRightButton);
        mainFrame.add(topRightPanel);

        // The button in question. Very suggestive name, I know.
        topRightButton.addActionListener(new GenericButtonListener());

        genericButtonListener.setKernel(kernel);

        // some other non relevant stuff here

        mainFrame.setVisible(true);
    }

}

public class GenericButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton btn = (JButton) e.getSource();
        String btnName = btn.getName();

        if(btnName.toLowerCase().contains("add_btn")) {
            addBtn(btn);
        }
    }

    public void addBtn(JButton button){
        SshFileIO sshFileIO = kernel.getFileIO();
        // Get field text here
    }
}

My current dilemma is how to get said textfield value inside GenericButtonListener.

I realize that I can use getText to get the text field value, however I don't have access to that variable inside the actionPerformed function.

I suppose this is more of a scoping problem rather than anything else.

I just need some pointing in the right direction, no hand holding required.

It's painfully obvious that I'm very new to Java.

Upvotes: 0

Views: 53

Answers (1)

Level_Up
Level_Up

Reputation: 824

Please try to get a reference of topRightTextField with the constructor of GenericButtonListener. Store as property of the class and use it inside actionPerformed.

Change this one:

 topRightButton.addActionListener(new GenericButtonListener());

To this:

 topRightButton.addActionListener(new GenericButtonListener(topRightTextField));

And inside class GenericButtonListener add field:

private JTextField topRightTextField;// set it in the constructor

And then use it inside of your method actionPerformed.

Have a nice coding and good luck!

Upvotes: 1

Related Questions