Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to resize image while resize frame using drawImage

Tags:

java

I have a little problem. I'm learning about Java forms and I want to resize my Image while I resize my form. But unfortunately I only resize form. Image have still these same dimensions. How can i rescale image? What should i change? What i do wrong? I enclose the code:

    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();
        }
    }
}
like image 807
Blackchart Avatar asked May 09 '13 22:05

Blackchart


1 Answers

First when you do the drawImage you'll have to not only set x and y but also set width and height. Only then will you be able to scale the image.

drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) 

Your canvas should get repainted when you re-size your form, but if it doesn't you can force it with .repaint();

ADDITION: You told me that you wanted it to be the same size as your form. You'll have to do 2 things then. First you use the method mentioned above with as width this.getWidth() and as height this.getHeight where this refers to the canvas. You'll have to make sure that your canvas scales with your frame you can simply do that by choosing an appropriate layoutmanager.

frame.setLayout(...)
like image 56
Daan Luttik Avatar answered Dec 12 '22 02:12

Daan Luttik