获取秋千标签文本并将其传递给父类

时间:2019-06-24 09:39:13

标签: java swing

我有一个带有秋千gui的程序来订购某些产品。 处理订单的类具有JFrame,其中JPanel具有JButton。当按下该按钮时,我需要处理订单的类中的输入。但是无法弄清楚如何一直获得输入。

包含按钮的面板:

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. 
    }

我在paidAmount声明中添加了ActionListener变量,因此我可以从付款按钮获取ActionListener,然后调用getPaidAmount()函数。但是,当我从ActionListener获取payButton.getActionListeners()并调用我声明的函数时,java无法识别getPaidAmount()函数。

我的问题是,我如何获取那个paidAmount并将其从按钮转移到面板,然后从面板转移到框架,再从框架转移到拥有框架的类?

1 个答案:

答案 0 :(得分:1)

尝试将函数放在actionListener之外并放在类PayPanel

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

并使用payPanelObject.getPaidAmount()

对其进行调用