检测单击哪个JLabel

时间:2014-07-11 04:14:06

标签: java swing compiler-errors jlabel mouselistener

我有一个JLabel[10],我想检测哪个标签已被点击,并打印出已点击的标签的哪个标签。

  1. 我创建了一个10 {/ 1}}数组。
  2. 写了一个for循环,将Image放到标签的每个位置。
  3. 添加JLabel以检查点击了哪个标签。
  4. 问题是我无法做到这一点来获取MouseListener的来源。该程序将要求我将其更改为最终版。

    jLabelArr

    完整代码

       if(e.getSource() == jLabelArr[i]) 
    

2 个答案:

答案 0 :(得分:3)

对于你想要的东西,只不过是创建一个等于for循环位置的最终int变量

import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JavaLabels extends JFrame {

private JLabel[] jLabelArr;
private JPanel jLabelPanel = new JPanel();

    public JavaLabels() {
        setLayout(new FlowLayout());
        jLabelArr = new JLabel[10];
        for(int i =0; i < 10; i++) {

            jLabelArr[i] = new JLabel(new ImageIcon("resources/image"));
            jLabelPanel.add(jLabelArr[i]); 
            final int p = i;
            jLabelArr[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Label" + p + "was clicked");
                }
            });
        }
        add(jLabelPanel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(400,600);
        setLocationRelativeTo(null);
        setVisible(true);
    }
    public static void main(String[] args) {
        new JavaLabels().setVisible(true);
    }
}

- &GT;在这种情况下不需要if(e.getSource() == jLabelArr[i])

答案 1 :(得分:2)

1

public class JavaLabels extends JFrame {

    private JLabel[] jLabelArr;
    private JPanel jLabelPanel = new JPanel();

    public JavaLabels() {
        setLayout(new FlowLayout());
        jLabelArr = new JLabel[10];
        for (int i = 0; i < 10; i++) {

            jLabelArr[i] = new JLabel(new ImageIcon("resources/image"));
            jLabelPanel.add(jLabelArr[i]);

            jLabelArr[i].addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    onMouseClicked(e);
                }
            });
        }
        add(jLabelPanel);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setSize(400, 600);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void onMouseClicked(MouseEvent e) {
        for (int i = 0; i < 10; i++)
            if (e.getSource() == jLabelArr[i]) {
                System.out.println("Label" + i + "was clicked");
            }
    }

    public static void main(String[] args) {
        new JavaLabels();
    }
}

2

实施MouseListenerJavaLabels班级和jLabelArr[i].addMouseListener(this);