62,623
社区成员
发帖
与我相关
我的任务
分享
不好意思,我上面的方法记错了getSource()是e.getActionCommand()...
应该是:
比如说你有很多按钮
JButton ok = new JButton("ok");
JButton cancel = new JButton("cancel");
你要这个类的监听器 如果你这个类中就只为JButton添加事件,最好是实现ActionListener接口就OK了.
如果还有其他的事件就要使用内部类,如果事件的是与一个例如与数据库或者文件系统等相关联的话,还需要
使这个内部类extends Thread使他成为一个单独的线程,我就以简单的实现ActionListener为例吧
class MyFrame extends Frame inplements ActionListener{
JButton ok = new JButton("ok");
JButton cancel = new JButton("cancel");
public MyFrame {
ok = new JButton("ok");
cancel = new JButton("cancel");
ok.addActionListener(thgis);
cancel. addActionListener(this);
.........
.........
}
public void actionPerformed(ActionEvent e){
if( (e.getActionCommand().trim()).equals("ok")){
// 要操作的内容
}
if( (e.getActionCommand().trim()).equals("cancel")){
}
class YourFrame extends Frame {
JButton btn = new JButton("test");
btn.addActionListener(new ActionListener1(this)); //here
}
class ActionListener1{
Frame frame;
public ActionListener1(Frame frame) { //here
this.frame = frame;
}
public void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if (frame instanceof YourFrame) {
YourFrame f = (YourFrame)frame;
if(obj==f.btn){
--------------------
}
}
}
}
class Frame{
JButton;
JButton.addActionListener(ActionListener1);
}
class ActionListener1{
public void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if(obj==new Frame().JButton){
--------------------
}
}
LZ :
Object obj=e.getSource();
if(obj==new Frame().JButton){
--------------------
}
你这个代码是什么东东啊 ,我怎么看不到.. 你用e.getSource()得到的是一个String哦 你
拿他和一个new Frame().JButton 能这样比吗?
比如说你有很多按钮
JButton ok = new JButton("ok");
JButton cancel = new JButton("cancel");
你要这个类的监听器 如果你这个类中就只为JButton添加事件,最好是实现ActionListener接口就OK了.
如果还有其他的事件就要使用内部类,如果事件的是与一个例如与数据库或者文件系统等相关联的话,还需要
使这个内部类extends Thread使他成为一个单独的线程,我就以简单的实现ActionListener为例吧
class MyFrame extends Frame inplements ActionListener{
JButton ok = new JButton("ok");
JButton cancel = new JButton("cancel");
public MyFrame {
ok = new JButton("ok");
cancel = new JButton("cancel");
ok.addActionListener(thgis);
cancel. addActionListener(this);
.........
.........
}
public void actionPerformed(ActionEvent e){
if( (e.getSource().trim).equals("ok")){
// 要操作的内容
}
if( (e.getSource().trim).equals("cancel")){
// 要操作的内容
}
}
}