我有两个问题:


我正在创建一个简单的记忆游戏,该游戏可以保存随机序列并期望玩家输入相同的内容,并且尝试使用JButton单击ImageIcon img1的较亮版本时更改setIcon() int >但在运行时没有任何变化。

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



有更好的方法吗?

最佳答案

首先,如果您不打算阻塞睡眠,则切勿在主线程中使用睡眠,这会使您的应用程序等待睡眠结束,从而“阻塞”您的主线程。


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

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

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

07-24 19:01
查看更多