简体   繁体   English

使用Java mouseClicked事件处理程序更改图标

[英]using Java mouseClicked event handler to change icons

I have tons of labels. 我有很多标签。 My problem is that I don't know how to write that if i click label2 , then set a new image on label2 but label1 doesnt change. 我的问题是,如果我单击label2 ,然后在label2上设置新图像,但label1不变,我不知道该怎么写。 labels are named like A1-A10. 标签的名称类似于A1-A10。 (I actually have 92 labels, so this is getting cumbersome.) Here's my code: (我实际上有92个标签,所以这变得很麻烦。)这是我的代码:

public void mouseClicked(MouseEvent event) {

    if (event.getSource()==A1 && (x==1)) {
        A1.setIcon(new ImageIcon("zoldgomb.jpg"));
        x=2;
    } else if(x==2) {
        A1.setIcon(new ImageIcon("sargagomb.jpg"));
        x=1;
    }
}

edit 编辑

ok, i solved it, thx everybody :) 好的,我解决了,谢谢大家:)

if (event.getSource() instanceof JLabel) {
                if (x == 1) {
                    ((JLabel)event.getSource()).setIcon(new ImageIcon("zoldgomb.jpg"));
                    x = 2;
                } else if (x == 2) {
                    ((JLabel)event.getSource()).setIcon(new ImageIcon("sargagomb.jpg"));
                    x = 1;
    }
}
  1. It sounds like you should be using either an array or ArrayList of JLabel. 听起来您应该使用JLabel的数组或ArrayList。
  2. Variable names should all begin with a lower letter while class names with an upper case letter. 变量名都应以小写字母开头,而类名应以大写字母开头。 Also you should avoid using trivial variable names such as b or s unless they are being used for trivial purposes such as the index of a for loop. 另外,除非将其用于琐碎的目的(例如for循环的索引),否则应避免使用琐碎的变量名(例如bs Instead use names that have some meaning so that your code becomes self-commenting. 而是使用具有一定含义的名称,以使您的代码变得自我注释。
  3. You can identify which JLabel was pressed by calling getSource() on the MouseEvent objevct passed into your method. 您可以通过在传递给您的方法的MouseEvent对象上调用getSource()来确定按下了哪个JLabel。 Your parameter is named event above. 您的参数在上面被命名为event
  4. Then after testing which JLabel is pressed, call its setIcon(...) method. 然后,在测试按下哪个JLabel之后,调用其setIcon(...)方法。
  5. You're better off reading in your images once and saving them to a variable, and not re-reading them in on each mouse click. 最好只读取一次图像并将其保存到变量中,而不要在每次单击鼠标时重新读取它们。

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

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