onclick我想获得JFrame上存在的JPanel的名称

时间:2013-05-03 15:35:27

标签: java swing jframe awt mouselistener

以下是我试图实施的内容,但它在提到的行上给出错误;这是因为函数没有得到哪个Component.getName()...     String name = new String();

                mntmOneToOne.addMouseListener(new MouseAdapter()
               {
                    @Override
                    public void mouseClicked(MouseEvent arg0)
                    {
                        String name=new String();
                        int count = arg0.getClickCount();
                        if (count == 1)
                        {
                          Component panel = (Component) arg0.getSource();   


                          System.out.println(panel.getName());
                        }

                    }
                 });

2 个答案:

答案 0 :(得分:1)

通过MouseEvent的getSource()方法获取点击的对象。然后调用其getName()方法。

mntmOneToOne.addMouseListener(new MouseAdapter() {
     @Override
     public void mouseClicked(MouseEvent mouseEvent) {
         int count = mouseEvent.getClickCount();
         if (count == 1) {
           Component panel = (Component)mouseEvent.getSource();
           name = panel.getName(); 
         }
     }
});

答案 1 :(得分:1)

见这个例子:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

    public class PanelTest extends JFrame {
        List<JPanel> panels;
        public PanelTest(){
            panels = new ArrayList<>();
            setLayout(new GridLayout(2,3));
            Color [] color = {Color.white,Color.black,Color.blue,Color.red,Color.orange,Color.gray};
            for(int i = 0 ; i < 6;i++)
            {
                panels.add(new JPanel());
                panels.get(i).setName("Panel "+i);
                panels.get(i).addMouseListener(new MouseAdapter(){
                    public void mouseClicked(MouseEvent ev){
                                        //JPanel p = (JPanel)ev.getSource();
                        System.out.println(((JPanel)ev.getSource()).getName());
                        }
                    });
                panels.get(i).setBackground(color[i]);
                getContentPane().add(panels.get(i));
            }
            setVisible(true);
            setDefaultCloseOperation(3);
            setSize(400,400);
        }

        public static void main(String...args){
            new PanelTest();
            }

    }