gpt4 book ai didi

java - 期间更改 ImageIcon

转载 作者:行者123 更新时间:2023-12-02 04:14:09 28 4
gpt4 key购买 nike

我有两个问题:

  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 List 来保存输入和随机序列,这是动态大小的原因:

    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);
    }
    }

有更好的方法吗?

最佳答案

首先,如果您不想阻塞它,切勿在主线程中使用 sleep ,这将使您的应用程序等待直到 sleep 结束,从而“阻塞”您的主线程。

  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. 好吧,您实际上不需要明确告知要添加元素的位置,特别是如果它是一个序列。数组列表不对项目进行排序。

关于java - 期间更改 ImageIcon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33498455/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com