期间更改 ImageIcon

Change ImageIcon during

我有两个问题:

  1. 我正在创建一个简单的记忆游戏,它保存一个随机序列并期望来自玩家的相同输入,我正在尝试更改 JButton ImageIcon使用 setIcon() 单击 img1 的更亮版本,但在 运行 期间没有任何变化。

    private final JButton btnImg1 = new JButton("");
    ImageIcon img1 = new ImageIcon("C:\Users\vide\Desktop\img1.png");
    ImageIcon img1_b = new  ImageIcon("C:\Users\vide\Desktop\img1_b.png");
    
    try {
         btnImg1.setIcon(img1);
         Thread.sleep(2000);
         btnImg1.setIcon(img1_b);
     }
    
  2. 我做了 2 int Lists 来保存输入和随机序列,动态大小的原因:

    List<Integer> seqAlea =  new ArrayList<Integer>();
    List<Integer> seqInsere =  new ArrayList<Integer>();
    int placar = 0;
    
    Random geraNumero = new Random();
    
    public void comecaJogo(){
    
        for(int i = 0; i < 3; i++){
            int numero = geraNumero.nextInt(4) + 1;             
            seqAlea.add(i, numero);
        }
    }
    

有更好的方法吗?

首先,如果您不想阻塞主线程,切勿在主线程中使用睡眠,这将使您的应用程序等待直到睡眠结束,因此 "blocking" 您的主线程。

  1. 对于您的第一个问题,此代码将解决:

    // Assuming that your image will be within your package
    final URL resource = getClass().getResource("/com/mypackage/myimage.png");
    
    final JButton btn = new JButton("My Button");
    final Image image = ImageIO.read(resource);
    final ImageIcon defaultIcon = new ImageIcon(image);
    
    btn.setIcon(defaultIcon);
    btn.addActionListener(new ActionListener() {
    
        public void actionPerformed(ActionEvent e) {
            try {
                //This will do the trick to brighten your image
                Graphics2D g2 = (Graphics2D) image.getGraphics();
    
                // Here we're creating a white color with 50% of alpha transparency
                g2.setColor(new Color(255, 255, 255, 50));
                // Fill the entire image with the new color
                g2.fillRect(0, 0, defaultIcon.getIconWidth(), defaultIcon.getIconHeight());
                g2.dispose();
                btnBtn.setIcon(new ImageIcon(image));
            } catch (Exception ex) {
                /*Although this is a bad practice, my point here is not 
                 * to explain exceptions. 
                 * But it's a good practice to always capture as many exceptions as you can
                */
            }
        }
    });
    
  2. 好吧,您实际上不需要明确告知要在哪个位置添加元素,特别是如果它是一个序列。数组列表不对项目进行排序。