简体   繁体   English

将mouseListener添加到数组循环中的标签

[英]Add mouseListener to Labels in Array Loop

I want to add mouseListener to all labels in the array. 我想将mouseListener添加到数组中的所有标签。 Every label should show an other card of the layout. 每个标签应显示布局的另一张卡片。 If I use below code, all labels show card6. 如果我使用以下代码,则所有标签均显示card6。 What is wrong? 怎么了?

sorry this is correct code.. 抱歉,这是正确的代码。

    panList = new JPanel();
    panList.setBounds(0, 0, 206, 517);
    panList.setLayout(null);
    cs.add(panList);

    CreateCards();

    int y = 0;  

        for(i = 0 ; i < 6; i++) {
        String lblName = getString("lbl"+String.valueOf(i));
        lblSettingTitle[i] = new JLabel("  "+lblName);
        lblSettingTitle[i].setBounds(0, y+10, 206, 26);
        lblSettingTitle[i].addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent e) {

                CardLayout cardLayout = (CardLayout) cards.getLayout();
                cardLayout.show(cards, "card"+String.valueOf(i));
            }
        });
        panList.add(lblSettingTitle[i]);
        y+=26;
        }
}

private void CreateCards() {
    card1 = new JPanel();
    card2 = new JPanel();
    cards = new JPanel(new CardLayout());
    cards.setBounds(206, 35, 814-206, 546-120);
    cs.add(cards);
    cards.add(card1, "card1");
    cards.add(card2, "card2");

}

the problem is when mouse-event fire value of i have value 6 or last value of for-loop 问题是,当mouse-event的火值i有值6或最后一个值for-loop

for (i = 0; i < 6; i++){}

you can create a jlable class and give a instance variable like lableindex so when mouse-event occurs you first get the lable index and then show corresponding card. 您可以创建一个jlable class并提供一个像lableindex这样的instance variable这样在发生mouse-event时,您首先会获得lable index ,然后显示相应的卡片。

or 要么

you can getname of the jlable and get index by removing lbl part of the jlable name and show corresponding card.for example if jlable name is lb12 then take 2 out and show card named card + 2 or card2 您可以通过删除jlable名称的lbl部分来获取jlable名称并获取索引并显示相应的卡。例如,如果jlable名称为lb12则取出2并显示名为card + 2card2 card + 2

for example consider this example 例如考虑这个例子

public void mouseClicked(java.awt.event.MouseEvent e) {

        String index = ((JLabel)e.getSource()).getText().substring(xx,yy); // here xx , yy  depend on how you are naming jlables .this should return 2 if your lable is lbl2
        CardLayout cardLayout = (CardLayout) cards.getLayout();
        cardLayout.show(cards, "card" + index);
        System.out.println("card" + index);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM