[英]How to know on which Label I clicked [Java]
我試過.equals()
和==
,但沒有任何幫助。 我存儲在我自己的類的 ArrayList 中的所有標簽都有 JLabel。
如何在 ArrayList 或其他東西中獲取標簽的索引?
我在使用 ArrayList 時有問題嗎? 鼠標監聽器
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;
}
單擊的圖像必須更改圖像,但只更改最后一個標簽。
由於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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.