问题是这样的:
    我在一个容器,如JPanel里面加了很多相同的组件,如JButton,对每个JButton都注册了一个蜀标点击的监听器,
    但是在监听过程中我又想在外面的JPanel容器中监听是哪个控件发生了鼠标事件,
    并获取他的index(index是按添加顺序增加的嘛),不知道该怎么做...    我尝试了在JPanel里面也加鼠标点击事件,但是好象JButton的事件会"遮住"JPanel的,结果JPanel收不到...    请大家帮帮忙吧!希望我叙述的清楚,大家能看明白

解决方案 »

  1.   

    做一个boolean数组来标记按钮被按下的事件吧, 
      

  2.   

    你在jbutton点击的时候传一个消息给jpanel,比如:
    首先在jpanel里面定义一个变量和一个方法:
    int index;
    void setIndex(JButton button)
    {
        //这里去取得button的index并赋给index
        //同时在这里也可以知道是哪个button发生了事件
    }
    然后在JButton 的点击事件中加一句
    this.setIndex(e.getSouce());
    我没有调试,不知道有没有单词错误,反正基本思路就是这样了条件是你的这个jpanel得继承JPanel
      

  3.   

    给所有的JButton添加同一个事件,如下面这个事件监听类
    class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e) {
       JButton selected=(JButton)e.getSource(); //的到被点击的JButton引用

    }}
    要的到序号可以给button有序的text,在listener里调用getText()的到text
      

  4.   


    数组数组放在JPanel里面,那么在事件发生之后我设置相应的为ture作为该按钮被点击了吧那么我的JPanle怎么去监听什么时候,哪个下标所指的boolean值被修改了呢?
      

  5.   

    我用一个最野蛮的办法:让panel去监听鼠标事件,然后给panel传递一个不可能的event,如下程序:class MyAdapter extends MouseAdapter
    { public void mouseClicked(MouseEvent e)
    {
    if(e.getX()==0&&e.getY()==0)
    {
    System.out.println("clicked");
    }
    /*else
    {
    这里处理其它事件
    }*/

    }
    }这个是继承mouseadapter的类
    下面是主窗口里面的内容
    MyAdapter adapter=new MyAdapter();
    panel.addMouseListener(adapter);
    button.addActionListener
    (
    new ActionListener()
    {
    public  void actionPerformed(ActionEvent e) 
    {
    System.out.println("button");
    adapter.mouseClicked(new MouseEvent(panel,MouseEvent.BUTTON1,new Date().getTime(),MouseEvent.BUTTON1_DOWN_MASK,0,0,1,false));
    }
    }
    );
      

  6.   

    把panel实现成ActionListener,也作为按钮的监听器?
    public class MyPanel extends JPanel implements ActionListener {
        public MyPanel() {
            initialize();
        }    private  void initialize() {
            JButton btnConfirm = new JButton();
                btnConfirm.addActionListener( new Actionlistener(  ) {
                    public  void actionPerformed(ActionEvent e)  {
                        // you event handle code
                    } 
            }
            btnConfirm.addActionListener(this);
            // ... init other component
        }
                    
        public  void actionPerformed(ActionEvent e)  {
            JButton srcButton = (JButton)e.getSource()
            //  get index of srcButton
        } 
        
    }