【发布时间】:2017-03-25 18:14:04
【问题描述】:
我在JPanel 中有一个JButton 的矩阵n*n。目前,我在每个随时间变化的JButton 中设置ImageIcon。这不是一个简单的 ImageIcon,它是我与此功能重叠的 2 个图像:
public ImageIcon DoubleImage(BufferedImage eau, BufferedImage img){
// Create a new image.
finalIcon = new BufferedImage(
eau.getWidth(), eau.getHeight(),
BufferedImage.TYPE_INT_ARGB); // start transparent
// Get the graphics object. This is like the canvas you draw on.
Graphics g = finalIcon.getGraphics();
// Now we draw the images.
g.drawImage((Image) eau, 0, 0, null); // start at (0, 0)
img = resize((BufferedImage) img, eau.getWidth(), eau.getHeight());
g.drawImage((Image) img, eau.getWidth()/2-img.getHeight()/2, eau.getHeight()/2-img.getWidth()/2, null); // start at (10, 10)
// Once we're done drawing on the Graphics object, we should
// call dispose() on it to free up memory.
g.dispose();
// Finally, convert to ImageIcon and apply.
ImageIcon icon = new ImageIcon(finalIcon);
return icon;
}
我现在的问题是,在每次迭代时,我都必须更改JButtons 中的图标。这意味着我必须重新绘制图标,而我没有超过 10 个不同的最终图像。但这需要太多时间(应用程序滞后于一个小的 10*10 矩阵;由于迭代每 1 秒发生一次,我必须解决这个问题)。我一开始就有创建所有图像并将它们存储在某个地方的想法,但我真的不知道如何执行此操作?也许有一个枚举?就在我的类的构造函数中?
我必须明确我的主类扩展了JButton,并为我的最终矩阵实例化了它的 n*n。
编辑:函数resize的代码
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
EDIT2:我在每次迭代中执行的代码
public void iteration(){
final Vue vue = marreGraphique.lireVue();
final Presenter presenter = vue.lirePresenter();
try{ //here I'm just instantiating my BufferedImage
eau = ImageIO.read(new File("Icones/mosaique.jpg"));
if(grenouille){
img = ImageIO.read(new File(presenter.getGrenouilleImg()));
}
else{
img = ImageIO.read(new File(presenter.getImg(ligne, colonne)));
}
}
catch (IOException e){}
icon = DoubleImage(eau,img);
setIcon(icon);
setHorizontalAlignment(SwingConstants.CENTER);
setVerticalAlignment(SwingConstants.CENTER);
}
【问题讨论】:
-
您是否要调整图像大小? (参考
resize()) -
是的,我用
resize的代码编辑了我的帖子 -
是的,我看到了...试图弄清楚发生了什么...
-
你正在绘制图像两次
-
什么意思?我正在绘制两个我想在
finalIcon中重叠的图像。我在调整图像大小时也在重新绘制图像,这是你的意思吗?
标签: java image swing icons jbutton