首页 > 解决方案 > 获取摆动标签文本并将其传递给父类

问题描述

我有一个带有摆动 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()函数。但是当我得到ActionListenerfrompayButton.getActionListeners()然后调用我声明的函数时,java 无法识别该getPaidAmount()函数。

我的问题是,我如何获得它paidAmount并将其从按钮传输到面板,然后从面板传输到框架,从框架传输到拥有框架的类?

标签: javaswing

解决方案


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

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

并使用payPanelObject.getPaidAmount()


推荐阅读