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