我有一个JLabel[10]
,我想检测哪个标签已被点击,并打印出已点击的标签的哪个标签。
JLabel
以检查点击了哪个标签。 问题是我无法做到这一点来获取MouseListener
的来源。该程序将要求我将其更改为最终版。
jLabelArr
if(e.getSource() == jLabelArr[i])
答案 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)
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();
}
}
实施MouseListener
到JavaLabels
班级和jLabelArr[i].addMouseListener(this);