This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2011-12-17 11:53:00

matthew8092001
Scratcher
Registered: 2010-09-12
Posts: 100+

Java- Image import help? (2D graphics)

Yeah, so as you can probably guess from the code below, I'm trying to get a picture inside a frame. I've got the frame part done, but I'm not sure how to import an image into the actual graphical interface. All I could really figure out was what to import xD
Can someone give me the code for importing an image?
Thank you in advance!

Code:

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.Image;
public class graphics extends JPanel{
    
  public void paintComponent(Graphics g){
 
    Graphics2D g2 = (Graphics2D) g;
    g2.draw3DRect(100, 200, 300, 350, true); //<--idk what the true means
    g2.setColor(Color.BLUE);
    g2.fill3DRect(100, 200, 300, 350, true);
    g2.setColor(Color.green);
    g2.fill (new Ellipse2D.Double(100, 200, 300, 350));
  }
  
  
  public static void main(String args[]){
    JFrame stuff = new JFrame();
    stuff.add(new graphics());
 
    
    stuff.setSize(600,600);
    stuff.setVisible(true);
    
  }
}

http://1.bp.blogspot.com/_GVA115I1I8Y/TMGwbJ056kI/AAAAAAAABHs/kpvg0oCKV2g/s1600/happy.gif
lol

Offline

 

#2 2011-12-17 12:11:45

ZeroLuck
Scratcher
Registered: 2010-02-23
Posts: 500+

Re: Java- Image import help? (2D graphics)

Here is an example...

Code:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class PictureViewer extends JPanel {
    
    BufferedImage img;

    public PictureViewer(BufferedImage img) {
        this.img = img;
    }

    public void paint(Graphics g) {
        // draw the image at x: 0 y: 0
        int x = 0;
        int y = 0;
        g.drawImage(img, x, y, null);
    }
    
    public Dimension getPreferedSize() {
        return new Dimension(img.getWidth(), img.getHeight());
    }

    public static void main(String[] args) throws IOException {
        // Load the image
        BufferedImage image = javax.imageio.ImageIO.read(
               new java.io.File("C:/JTest/image.png"));
        // Create a frame
        JFrame frm = new JFrame("Test");
        frm.setSize(500, 500);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setLayout(new BorderLayout());
        
        // Add the PictureViewer to the frame
        frm.add(new PictureViewer(image), BorderLayout.CENTER);
        frm.validate();
        
        // Show the frame
        frm.setVisible(true);
    }
}

Last edited by ZeroLuck (2011-12-17 12:16:35)


http://3.bp.blogspot.com/-oL2Atzp0Byw/T465vIQ36dI/AAAAAAAAADo/1vqL4PvhkM0/s1600/scratchdachwiki.png

Offline

 

Board footer