我有两个问题:
我创建了一个简单的记忆游戏,可以保存随机序列并期望来自玩家的相同输入,并且我试图更改JButton
ImageIcon
时使用img1
点击了setIcon()
的更亮版本,但在运行时没有任何变化。
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 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);
}
}
有更好的方法吗?
答案 0 :(得分:2)
首先,如果您不打算阻止它,请不要在主线程中使用睡眠,这将使您的应用程序等到睡眠结束,从而“阻止”您的主线程。
对于您的第一个问题,此代码将解决:
// 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
*/
}
}
});
嗯,你实际上并不需要明确告知你要添加元素的位置,特别是如果它是一个序列。 Arraylists不对项目进行排序。