2
我有一點問題。我正在學習Java表單,並在調整表單大小時調整圖像大小。但不幸的是,我只是調整形式。圖像仍然具有相同的尺寸。我如何重新調整圖像?我應該改變什麼?我做錯了什麼? 我附上代碼:如何在調整圖像大小時調整圖像大小使用drawImage
package przegladarka;
import java.io.*;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
public class view extends JPanel {
Image imag;
Dimension size;
public static int framew=300;
public static int frameh=300;
static String[] children;
static ArrayList<String> sciezki = new ArrayList<String>();
public static void main(String[] args) {
File folder = new File("./zdjecia/");
visitAllFiles(folder);
JFrame frame = new JFrame("Przegladarka");
frame.setSize(300, 300);
frame.setVisible(true);
frame.getContentPane().add(new MyCanvas());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void visitAllFiles(File dir) {
if (dir.isDirectory()) {
children = dir.list();
for (int i = 0; i < children.length; i++) {
visitAllFiles(new File(dir, children[i]));
System.out.println(""+children[i]);
Image imag = Toolkit.getDefaultToolkit().getImage(children[i]);
}
} else {
System.out.println(dir.getAbsolutePath() + " is being processed.");
sciezki.add(dir.getAbsolutePath());
}
}
}
class MyCanvas extends JComponent{
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D) g;
for(int i=0; i<view.sciezki.size();i++){
Image imag = Toolkit.getDefaultToolkit().getImage(view.sciezki.get(i));
g2d.drawImage(imag, 0, 0, this);
g2d.finalize();
}
}
}
看看[這裏](http://stackoverflow.com/questions/12876615/how-do-i-resize-images-inside-an-application-when-the-application-window- 12876799#12876799)[this](http://stackoverflow.com/questions/11959758/java-maintaining-aspect-ratio-of-jpanel-background-image/11959928#11959928) – MadProgrammer 2013-05-10 00:10:17
1)自定義繪畫是通過覆蓋'paintComponent()'方法而不是paint()方法來完成的。 2)不要在繪畫方法中從磁盤讀取圖像。當類創建或作爲參數傳遞給類時,應該讀取圖像。 3)你創建一個循環後,你的代碼沒有意義。只有最後一幅圖像會被繪製。 4)不要對Graphics對象執行finalize()。該對象由框架上的所有組件共享。 – camickr 2013-05-10 00:13:35