我有一個JButton
的矩陣n * n,在JPanel
中。目前,我在每個JButton
中設置ImageIcon
,隨時間變化。這不是一個簡單的ImageIcon,它是2倍的圖像,我用這個功能重疊:如何在Java中存儲ImageIcon
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);
}
你想調整圖像? (指'調整大小()') – ItamarG3
是的,我編輯我的帖子與'resize'代碼 – pioupiou1211
是的,我看到...試圖找出發生了什麼... – ItamarG3