public class start implements ActionListener {
public void actionPerformed(ActionEvent aL) {
method(arguments);
}
}
method(arguments) {
//stuff
}
我希望JButton告诉程序使用参数“stuff”启动一个方法所以我把actionListener放在按钮上面但是actionListener没有访问参数,我不知道怎么给它他们(我查看了oracle文档并且无法弄明白)。我试过这个:
actionPerformed(ActionEvent aL, stuff) {
这不起作用,我收到错误
Compute.java:45: error: Compute.start is not abstract and does not override abstract method actionPerformed(ActionEvent) in ActionListener
public class start implements ActionListener {
^
我尝试使用@Override,但根据编译器你无法覆盖它。那么,我如何将参数提供给ActionListener或者让方法在按钮之外但只在按下按钮时才开始工作,但是我在JFrame中使用JProgressBar按钮所在的按钮是使用方法作为计时器的东西所以最好将参数传递给actionListener
此外,上面是动作侦听器,除此之外是具有使用actionListener的按钮的对象:
//imports
public class someObject extends JFrame {
//attributes
public someObject() {
//blah blah
go = new JButton("Compute!");
start c = new start();
go.addActionListener(c);
所以,基本上我如何将参数从Object传递给ActionListener?
答案 0 :(得分:0)
public class someObject extends JFrame {
// attributes
public someObject() {
// blah blah
JButton bt = new JButton("Compute!");
int obj = 4;
start c = new start((Object)obj);
bt.addActionListener(c);
this.add(bt);
}
public static void main(String[] args) {
someObject so = new someObject();
so.setVisible(true);
}
}
class start implements ActionListener {
private Object paramObj;
public start(Object param) {
this.paramObj = param;
if(param==null)
JOptionPane.showMessageDialog(null, "Param is null");
}
public void actionPerformed(ActionEvent al) {
method(paramObj);
}
private void method(Object obj) {
// stuff
if(obj!=null)
JOptionPane.showMessageDialog(null, "Method has been called successfully! obj="+ String.valueOf(obj));
}
}