日期:2014-05-20  浏览次数:20739 次

关于事件的一个简单代码,兄弟们,帮我调试下.
Java code
import java.awt.*;
import java.awt.event.*;
public class Cen
{
   public static void main(String args[])
  {
        Frame f=new Frame("Test");
        final Button b=new Button("press me");
        f.setLayout(new FlowLayout());
        f.add(b);
        f.setSize(200,100);
        f.setVisible(true);
  class ButtonHandler implements ActionListener
     {
    public void actionPerformed(ActionEvent e)
       {
        System.out.println("Action occurred");
        if(e.getSource().equals(b))
            System.out.println("sdf");
       }
     }
   }
}



------解决方案--------------------
你想问什么呢??晕,你的事件处理代码都没有加进去。
------解决方案--------------------
LS说得真对。
------解决方案--------------------

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

public class Test {

public static void main(String args[]) {
Frame f = new Frame("Test");
final Button b = new Button("press me");
b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
System.out.println("Action occurred");
if (e.getSource().equals(b)) {
System.out.println("sdf");
}
}
});
f.setLayout(new FlowLayout());
f.add(b);
f.setSize(200, 100);
f.setVisible(true);
}
}
不知道你为什么要在main方法里面定义内部类,如何访问?
------解决方案--------------------
Java code

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

import javax.swing.JButton;
import javax.swing.JFrame;

public class Cen
{
    private static JButton b;

    public static void main(String args[])
    {
        JFrame f = new JFrame("Test");
        b = new JButton("press me");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        b.addActionListener(new Cen().new ButtonHandler());
        f.setLayout(new FlowLayout());
        f.add(b);
        f.setSize(200, 100);
        f.setVisible(true);
    }

    private class ButtonHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Action occurred");

            if(e.getSource().equals(b))
            {
                System.out.println("sdf");
            }
        }
    }
}

------解决方案--------------------
内部类??
------解决方案--------------------
还是用swing的组件比较好,直到awt组件的事件模型就够了,基本没有什么地方会使用到awt了。