gpt4 book ai didi

java - 将 JRadioSelection 传递给 ActionLIstener 类

转载 作者:行者123 更新时间:2023-12-01 17:30:49 26 4
gpt4 key购买 nike

对于我的应用程序,我创建了两个 JRadioButton分组为“选择”ButtonGroup 。我添加了ActionListener称为“选择监听器”。当我检查我的 RadioButton 是否使用 isSelected() 选择,看来我的选择没有被传递到 ActionListener .

public static void main(String[] args) {
JRadioButton monthlyRadioButton = new JRadioButton("Monthly Payment", true);
JRadioButton loanAmountButton = new JRadioButton("Loan Amount");
ButtonGroup selection = new ButtonGroup();
selection.add(monthlyRadioButton);
selection.add(loanAmountButton);
monthlyRadioButton.addActionListener(new SelectionListener());
loanAmountButton.addActionListener(new SelectionListener());
}

SelectionListener.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class SelectionListener implements ActionListener {
public void actionPerformed(ActionEvent event){
if(event.getSource() == monthlyRadioButton)
System.out.println("You clicked Monthly");
else
System.out.println("You clicked Loan Amount");

}
}

参数monthlyRadioButton没有被传递给我的 SelectionListener类(class)。我收到一条错误,表明该问题尚未解决。

如何通过 monthlyRadioButton在我的主要方法中转到我的 SelectionListener类?

最佳答案

您可以检索正在处理的事件的发送者。

类似于:

class SelectionListener implements ActionListener {
private JComponent monthlyRadioButton;
private JComponent loanAmountButton;

public SelectionListener(JComponent monthlyRadioButton, JComponent loanAmountButton) {
this.monthlyRadioButton = monthlyRadioButton;
this.loanAmountButton = loanAmountButton;
}

public void actionPerformed(ActionEvent event){
if(event.getSource() == monthlyRadioButton)
System.out.println("You clicked Monthly");
else if(event.getSource() == loanAmountButton)
System.out.println("You clicked Loan Amount");
}
}

在你的主要方法上,你可以像这样实例化它:

    monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton));

关于java - 将 JRadioSelection 传递给 ActionLIstener 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11144143/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com