【问题标题】:Holding jbuttons in array from e.getsource从 e.getsource 在数组中保存 jbuttons
【发布时间】:2013-09-23 12:43:16
【问题描述】:
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 然后关闭或保持打开状态。我怎样才能保存数组或其他东西?

我的数组持有错误?

使用此代码,我可以打开无限的图像,并且没有一个被关闭。

【问题讨论】:

  • 你想在这里做什么?
  • 可能是我在SO上读到的最不清楚的问题之一。
  • 我试图在数组中保存 2 个图像,如果它们不同,它将关闭它们。这是一个记忆游戏。只能打开 2 张图片。

标签: java arrays swing jbutton actionlistener


【解决方案1】:

我正在尝试将 2 个图像保存在数组中,如果它们会关闭它们 不一样。这是一个记忆游戏。只能打开 2 张图片

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

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

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

【讨论】:

  • 还可以考虑JToggleButton,提到here
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多