keesjanbertus
keesjanbertus

Reputation: 402

Get swing label text and pass it to parent class

I have a program with a swing gui to order certain products. the class that handles orders has the JFrame which has a JPanel which has a JButton. When that button is pressed, I need the input in the class that handles the orders. But can't figure out how to get that input all the way up.

panel that contains the button:

public class PayPanel extends JPanel {

    private double paidAmount;
    private JButton payButton;

    public PayPanel() {

        setBorder(BorderFactory.createTitledBorder("Make Payment"));

        JLabel payLabel = new JLabel("Pay with: ");
        JTextField payField = new JTextField(12);
        this.payButton = new JButton("Pay");
        this.payButton.setPreferredSize(new Dimension(100, 20));

        this.payButton.addActionListener(new ActionListener() {

            public double paidAmount;

            public void actionPerformed(ActionEvent e) {
                this.paidAmount = Double.parseDouble(payField.getText());
            }

            public double getPaidAmount() {
                return this.paidAmount;
            }
        });
        setLayout(new GridBagLayout());
        GridBagConstraints gridBagConstraints = new GridBagConstraints();

        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        add(payLabel, gridBagConstraints);

        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        add(payField, gridBagConstraints);

        gridBagConstraints.weighty = 10;
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        add(payButton, gridBagConstraints);

    }

    public double getPaidAmount() {
        ActionListener[] payButtonListeners = this.payButton.getActionListeners();
        ActionListener payButtonActionListener = payButtonListeners[0];
        return payButtonActionListener.getPaidAmount(); // this function is not recognized even though i defined it in the action listener like shown above in the contructor. 
    }

i added the paidAmount variable in the ActionListener declaration so i would be able to get the ActionListener from the paybutton and then call the getPaidAmount() function. But when i get the ActionListener from payButton.getActionListeners() and then call the function I declared, java doesn't recognize the getPaidAmount() function.

My question is, how do i get that paidAmount and transfer it from the button to the panel and then from the panel to the frame and from the frame to the class which owns the frame?

Upvotes: 0

Views: 21

Answers (1)

isstiaung
isstiaung

Reputation: 611

Try putting the function outside the actionListener and in the class PayPanel

    public double getPaidAmount() {
            return this.paidAmount;
    }

and call it using payPanelObject.getPaidAmount()

Upvotes: 1

Related Questions