JAVA小程序的离奇问题!添加Button及add.actionListener后,按键还是没反应!

来源:百度知道 编辑:UC知道 时间:2024/05/29 05:29:19
程序目的超简单,就是用appletviewer来看一个窗口。但奇怪的是窗口里面的两个按钮无论怎样按都是没有任何变化!烦死了!

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class temp extends Applet implements ActionListener
{
Button btn1,btn2;
public void init()
{
Button btn1=new Button("Button1");
Button btn2=new Button("Button2");
add(btn1);
add(btn2);
btn1.addActionListener(this);
btn2.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{

if(source==btn1)
{
btn1.setBackground(Color.red);
}
else if(source==btn2)
{
btn2.setBackground(Color.green);
}
}
}

你的抽象方法里的代码应该这样的:
public void actionPerformed(ActionEvent e)
{

if(e.getSource()==btn1)
{
btn1.setBackground(Color.red);
}
else if(e.getSource()==btn2)
{
btn2.setBackground(Color.green);
}
需要用getSourse来判断是哪个组件触发了事件,你再试试看看!

你确定你的程序能够编译?source是从哪里来的阿?