Java label.setVisible(true)在面板中显示正确的图像

Java label.setVisible(true)在面板中显示正确的图像,java,image,swing,jbutton,Java,Image,Swing,Jbutton,我认为这是个错误,对吗?因为它不执行 建议后编辑: label[n].setIcon((images[i*buttons.length+j])); for(i=0;i您似乎在向JButton添加JLabel??如果这是您正在做的事情,请不要这样做。相反,当您希望显示或更改按钮显示的图像(如果有)时,为什么不简单地设置JButton的ImageIcon呢?您可以通过myButton.setIcon(fooIcon)来完成此操作 编辑 您在评论中声明: 它将如何显示jbutton中的图像并将其隐

我认为这是个错误,对吗?因为它不执行

建议后编辑:

label[n].setIcon((images[i*buttons.length+j]));

for(i=0;i您似乎在向JButton添加JLabel??如果这是您正在做的事情,请不要这样做。相反,当您希望显示或更改按钮显示的图像(如果有)时,为什么不简单地设置JButton的ImageIcon呢?您可以通过
myButton.setIcon(fooIcon)
来完成此操作


编辑
您在评论中声明:


它将如何显示jbutton中的图像并将其隐藏

您可以简单地交换图标。如果要显示图像,请通过
setIcon(myIcon)
将其图像图标设置为JButton图标。完成后,通过
setIcon(otherIcon)
setIcon(null)
将其交换出去


您提供的链接没有将JLabels放在JButtons之上,而您似乎正在尝试这样做,这就是我告诉您此信息的原因。

我认为这篇文章与之相关。可能是作业

两个提示:

标签[n].setIcon((图像[i*buttons.length+j])

images
array中有多少图像?简单的计算一下,如果你有一个4x4数组,那么你需要
i*按钮。在上一次迭代中,lenght+j==4*4+4==20
图像。假设是配对游戏,你只需要
i*j/2==8
图像

若按钮有相同的图标,它们将保持打开状态。我在其中制作了框架 面板中的按钮,每个按钮都有标签

为什么需要标签?我认为如果两个按钮匹配,可以禁用这些按钮,这样用户就不能再次单击它们并发送
actionPerformed
事件

如果严格来说没有必要使用数组,您可以使用
ArrayList
,并从其方法中获益

更新

我之所以发布这段代码,是因为我认为您仍然坚持使用数组。我只是想告诉您,没有必要使用数组来保留引用,您只需要在对象范式下多考虑一点,并将此任务委托给适当的对象

 for(i=0; i<16; i++){

             images[i]=new ImageIcon(getClass().getResource("/images/1 ("+i+").jpg"));

    } //adding images to local variables

            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();
                //buttons[i][j].setIcon((images[i*buttons.length+j]));
    //if i make this code, all icons are displayed at first?

                    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();
            if(pressedButton.getIcon() == null){
                pressedButton.setIcon((images[i*buttons.length+j]));
            } else {
                pressedButton.setIcon(null);
            }
        }
    }
导入java.awt.Dimension;
导入java.awt.GridLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.ArrayList;
导入java.util.Collections;
导入java.util.List;
导入javax.swing.ImageIcon;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.SwingUtilities;
导入javax.swing.SwingWorker;
导入javax.swing.UIManager;
公共类演示{
/* 
*此变量将指向一个按下的按钮以保持引用。
*/
JButton_alreadyPressedButton=null;
/**
*初始化GUI
*/
私有void initGUI(){
/*
*创建所需的图标-由于本例使用6个按钮,因此我需要3个图标
*/
ImageIcon icon1=(ImageIcon)UIManager.getIcon(“OptionPane.errorIcon”);
ImageIcon icon2=(ImageIcon)UIManager.getIcon(“OptionPane.informationIcon”);
ImageIcon图标3=(ImageIcon)UIManager.getIcon(“OptionPane.warningIcon”);
/*
*列出6个图标(每个图标添加两次)
*/
List iconsList=新建ArrayList();
iconsList.add(icon1);
iconsList.add(icon1);
iconsList.add(icon2);
iconsList.add(icon2);
IConList.add(icon3);
IConList.add(icon3);
Collections.shuffle(iconsList);/*洗牌列表*/
ActionListener ActionListener=新建ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
如果(例如,JButton的getSource()instanceof){
最终JButton按下按钮=(JButton)e.getSource();
/* 
*在SwingWorker中执行此代码,以防止在“Thread.sleep(500)”行阻塞EDT
*Google for EDT(事件调度线程)
*/
SwingWorker sw=新SwingWorker(){
@凌驾
受保护对象doInBackground()引发异常{
如果(_alreadyPressedButton!=按下按钮){
pressedButton.setIcon(pressedButton.getPressedIcon());
如果(_alreadyPressedButton!=null){
睡眠(500);
如果(_alreadyPressedButton.getIcon()==pressedButton.getIcon()){
_alreadyPressedButton.setEnabled(false);
按下按钮。设置启用(错误);
}否则{
_设置图标(空);
按下按钮。设置图标(空);
}
_alreadyPressedButton=null;
}否则{
_alreadyPressedButton=按下按钮;
}
}
返回null;
}
};
sw.execute();
}
}
};
JPanel面板=新JPanel(新网格布局(3,2));
面板。设置首选尺寸(新尺寸(200200));
用于(图像图标:图标列表){
JButton button=新JButton();
按钮。设置按指令(图标);
addActionListener(actionListener);
面板。添加(按钮);
}
JFrame=新JFrame(“演示”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(面板);
frame.pack();
frame.setLocationRelativeTo(空);
frame.setVisible(true);
 for(i=0; i<16; i++){

             images[i]=new ImageIcon(getClass().getResource("/images/1 ("+i+").jpg"));

    } //adding images to local variables

            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();
                //buttons[i][j].setIcon((images[i*buttons.length+j]));
    //if i make this code, all icons are displayed at first?

                    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();
            if(pressedButton.getIcon() == null){
                pressedButton.setIcon((images[i*buttons.length+j]));
            } else {
                pressedButton.setIcon(null);
            }
        }
    }
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.UIManager;


public class Demo {    
    /* 
     * This variable will point to a pressed button to keep reference.
     */
    JButton _alreadyPressedButton = null;

    /**
     * Initializes the GUI
     */
    private void initGUI(){
        /*
         * Create needed icons - As this example uses 6 buttons, then I need 3 icons 
         */
        ImageIcon icon1 = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
        ImageIcon icon2 = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
        ImageIcon icon3 = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
        /*
         * Make a list with 6 icons (add each icon twice)
         */
        List<ImageIcon> iconsList = new ArrayList<>();
        iconsList.add(icon1);
        iconsList.add(icon1);
        iconsList.add(icon2);
        iconsList.add(icon2);
        iconsList.add(icon3);
        iconsList.add(icon3);
        Collections.shuffle(iconsList); /* Shuffle the list */

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if(e.getSource() instanceof JButton){                    
                    final JButton pressedButton = (JButton) e.getSource();              
                    /* 
                     * Execute this code in a SwingWorker to prevent block EDT at "Thread.sleep(500)" line
                     * Google for EDT (Event Dispatch Thread)
                     */
                    SwingWorker sw = new SwingWorker() {
                        @Override
                        protected Object doInBackground() throws Exception {
                            if(_alreadyPressedButton != pressedButton){
                                pressedButton.setIcon(pressedButton.getPressedIcon());

                                if(_alreadyPressedButton != null){ 
                                    Thread.sleep(500);
                                    if(_alreadyPressedButton.getIcon() == pressedButton.getIcon()){
                                        _alreadyPressedButton.setEnabled(false);
                                        pressedButton.setEnabled(false);
                                    } else {
                                        _alreadyPressedButton.setIcon(null);
                                        pressedButton.setIcon(null);
                                    }
                                    _alreadyPressedButton = null;
                                } else {
                                    _alreadyPressedButton = pressedButton;
                                }

                            }
                            return null;
                        }

                    };

                    sw.execute();
                }
            }
        };

        JPanel panel = new JPanel(new GridLayout(3, 2));
        panel.setPreferredSize(new Dimension(200, 200));

        for(ImageIcon icon : iconsList){
            JButton button = new JButton();
            button.setPressedIcon(icon);
            button.addActionListener(actionListener);
            panel.add(button);
        }

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 new Demo().initGUI();
            }
        });        

    }
}