java - 将 e.getsource 中的 jbutton 保存在数组中

标签 java arrays swing jbutton actionlistener

public int open=0;
private JButton  opens[]=new JButton[1];

  for( i=0; i<buttons.length; i++){
            for (j=0; j<buttons[i].length;j++){ 
                n=i*buttons.length+buttons[i].length;
                buttons[i][j]=new JButton();

                panel.add(buttons[i][j]);
                buttons[i][j].addActionListener(this);
            }
        }


        public void actionPerformed(ActionEvent e) {
        if(e.getSource() instanceof JButton){
            JButton pressedButton = (JButton) e.getSource();
            opens[open]=(JButton) e.getSource();
            if((pressedButton.getIcon() == null)){
                pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));
                open=open++;
            } else {   
                //pressedButton.setIcon(null);
            }

            }
        if (open==1){
            opens[0].setIcon(null);
            opens[1].setIcon(null);
        }
    }

我想按住 2 个 JButton 单击,然后关闭或保持打开状态。我如何保存数组或其他东西?

我的数组持有错误?

使用此代码,我可以打开无限的图像,并且它们都不会被关闭。

最佳答案

I am trying to hold 2 images in array, then it will close them if they are not same. It is a memory game. Only 2 images can be opened

  • 将图像加载到局部变量 Icon/ImageIcons ,以避免任何 FileIO 含义代码行 pressedButton.setIcon(new ImageIcon(getClass().getResource("/images/2.jpg")));

  • 将此Icon/ImageIcons添加到JButton.setPressedIcon(myIcon) ,

  • 然后有无用的代码行用 pressedButton.setIcon(null); 重置 Icon 回来

关于java - 将 e.getsource 中的 jbutton 保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18959561/

相关文章:

javascript - 试图从数组中检索对象的颜色

c++ - 指针数组声明的问题

java - 使用 Keybind 和 MouseInfo 获取 Label

java - 空数组和空数组有什么区别?

php - 多维数组转对象,具体方式

java - JScrollBar 在 JTextPane 中突出显示所选文本的位置

java - CardLayout 在调用 next() 时不切换面板

java - 仅在子类上为列添加唯一约束

java - 如何防止Java为较新的SDK编译部分代码?

java - 我该如何执行正常关机 (Java)?