如何知道我在哪个标签上单击了[Java]

时间:2019-04-24 18:04:56

标签: java swing arraylist jlabel mouselistener

我尝试了.equals()==,但没有帮助。我将所有标签存储在我自己的类的ArrayList中,它们具有JLabel。

如何获取ArrayList中标签的索引或其他内容?

我在使用ArrayList时遇到问题吗? MouseListener


  private static MouseListener clicklvl1=new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                for (int i=0;i<shahtars.size();i+=1){
                     if (e.getSource()==shahtars.get(i).uiShahtar){
                         IDofClickedObject=i;
                    } 
                }
                if (IDofClickedObject!=-1){
                    if (counter == 0) {
                        shahtars.get(IDofClickedObject).uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1(Clicked).png"));
                        counter = 1;
                    } else if (counter == 1) {
                        // uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1.png"));
                        shahtars.get(IDofClickedObject).uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1.png"));
                        counter = 0;
                    }
                }
                System.out.print("x "+shahtars.get(IDofClickedObject).uiShahtar.getX()+" y  "+shahtars.get(IDofClickedObject).uiShahtar.getY());

            }

我的课


class  FillShahtar implements Cloneable {
    static JLabel uiShahtar;
    static int energy;
    static double power;
    static double speed;
    String name;

最后一个

 FillShahtar(int chose) {
switch (chose){
    case 1:{

        plankaDown = 1;
        plankaUp = 11;

        int xRand = (int) ( 0+Math.random()*1000);
        int yRand =(int) (0+Math.random()*600);
         int counter=0;

        /////////////////////////debug/////////////////
        System.out.print(xRand+"   "+yRand+"\n");
        //////////////////////////////////////////////

        energy = (int) (plankaDown + Math.random() * plankaUp  );
        power = (int) (plankaDown + Math.random() * plankaUp  );
        speed = (int) (plankaDown + Math.random() * plankaUp  );


        uiShahtar = new JLabel();

        uiShahtar.setIcon(new ImageIcon("E:\\aaa\\ShahtarLvL1.png"));
        uiShahtar.setLayout(new FlowLayout());

        uiShahtar.setSize(50,50);
        uiShahtar.setLocation(xRand,yRand);

        uiShahtar.setVisible(true);
        uiShahtar.addMouseListener(clicklvl1);



//        mainPanel.add(shahtars.get(counter).uiShahtar);
        counter+=1;

        break;
    }

单击的图像必须更改图像,但只能更改最后一个标签。

1 个答案:

答案 0 :(得分:1)

由于JLabel继承了swing的Component类,因此可以向每个可点击标签添加MouseListener(或MouseAdapter)。使用此EventListener,您可以找到单击的标签,如下所示:

        JLabel l = new JLabel();
        l.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                JLabel clickedLabel = (JLabel) e.getComponent();
            }
        });

为了获取ArrayList中单击的标签的索引,请使用ArrayList提供的indexOf(Object)方法:

int index = list.indexOf(clickedLabel);