java - 获取swing标签文本并将其传递给父类

标签 java swing

我有一个带有 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. 
    }

我在 ActionListener 声明中添加了 paidAmount 变量,这样我就能够从 paybutton 获取 ActionListener ,然后调用 getPaidAmount()函数。但是当我从 payButton.getActionListeners() 获取 ActionListener 然后调用我声明的函数时,java 无法识别 getPaidAmount()功能。

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

最佳答案

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

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

并使用payPanelObject.getPaidAmount()调用它

关于java - 获取swing标签文本并将其传递给父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56733809/

相关文章:

java - hadoop/emr如何存储键值对

java - 如何使 drawString 居中?

java - 无法将数据填充/更新到另一个 JTable "B"onclick JTable "A"中的特定行

java - 带有行过滤器的 JTable - 如何仅迭代过滤的行

java - 加载文件时,SplitPane 中的 JTextArea 不显示文本

Java多线程: thread safe data structure vs.同步方法

java - 使用 Java 的 HTTP OPTIONS 方法

java - 您可以使用 Gradle 有条件地准备任务吗?

java - 我应该使用不同的包还是相同的包来执行此操作

java - 测试 Swing 应用