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

Add mouseListener to Labels in Array Loop

我想将 mouseListener 添加到数组中的所有标签。每个标签都应该显示布局的另一张卡片。如果我使用下面的代码,所有标签都会显示 card6。怎么了?

抱歉,这是正确的代码..

    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");

}

问题是当 imouse-event 火值具有值 6for-loop 的最后一个值时

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

你可以创建一个 jlable class 并给一个 instance variable 比如 lableindex 所以当 mouse-event 出现时,你首先得到标签 index 然后显示相应的卡片。

你可以获取 jlable 的名称并通过删除 jlable 名称的 lbl 部分来获取索引并显示相应的 card.for 示例,如果 jlable 名称是 lb12 然后取2 出示名为 card + 2card2

的卡片

例如考虑这个例子

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);
}