我有一個帶有 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 回答

元芳怎么了
TA貢獻1798條經驗 獲得超7個贊
嘗試將函數放在 actionListener 之外并放在類中PayPanel
public double getPaidAmount() { return this.paidAmount; }
并使用payPanelObject.getPaidAmount()
添加回答
舉報
0/150
提交
取消