我有一个带有秋千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
并将其从按钮转移到面板,然后从面板转移到框架,再从框架转移到拥有框架的类?
答案 0 :(得分:1)
尝试将函数放在actionListener之外并放在类PayPanel
public double getPaidAmount() {
return this.paidAmount;
}
并使用payPanelObject.getPaidAmount()