Menampilkan Gambar dengan Class Java GraphPanel


Untuk menampilkan gambar atau foto, dapat menggunakan class GraphPanel.

GraphPanel adalah class turunan JPanel yang penulis modifikasi untuk keperluan menampilkan gambar 2D.

Image yang akan ditampilkan, perlu dimasukkan dulu sebagai class Gambar, dan GraphPanel akan menampilkan dengan titik pusat koordinat berada ditengah.

Berikut ini adalah beberapa kode Java dalam bentuk file, untuk menampilkan gambar, sekaligus transformasi besar kecilnya menggunakan JSlider.

SimpleImageViewer.java

package simpleimageviewer; 
 
import java.awt.Dimension; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.Image; 
import java.awt.Toolkit; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.File; 
import java.io.IOException; 
import javax.imageio.ImageIO; 
import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JSlider; 
import javax.swing.WindowConstants; 
import javax.swing.event.ChangeEvent; 
import javax.swing.event.ChangeListener; 
 
/** 
 * 
 * @author Edugame 
 */ 
public class SimpleImageViewer extends JFrame 
{ 
    private GraphPanel workspace; 
    private JSlider hbar=new JSlider(JSlider.HORIZONTAL,0,200,100); 
    private String Filepath=""; 

    public void setup() 
    { 
        Filepath=System.getProperty("user.dir"); 

        setTitle("Simple Image Viewer"); 

        setLayout(new GridBagLayout()); 
        GridBagConstraints con = new GridBagConstraints(); 

        con.fill = GridBagConstraints.BOTH; 
        con.weightx=1; 
        con.weighty=1; 
        con.gridx=0; 
        con.gridy=0; 

        workspace=new GraphPanel(); 
        add(workspace,con); 

        JPanel panel=new JPanel(); 
        panel.setLayout(new GridBagLayout()); 
        GridBagConstraints subcon = new GridBagConstraints(); 

        subcon.fill = GridBagConstraints.BOTH; 
        subcon.weightx=1; 
        subcon.weighty=0; 
        subcon.gridx=0; 
        subcon.gridy=0; 
        JButton btn = new JButton("Set Image"); 
        btn.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent event){ 
                openFile(); 
            } 
        }); 
        panel.add(btn,subcon); 

        con.gridheight=2; 
        con.weightx=0; 
        con.gridx++; 
        add(panel,con); 

        con.weighty=0; 
        con.gridheight=1; 
        con.gridy++; 
        con.gridx=0; 
        hbar.addChangeListener(new ChangeListener(){ 
            public void stateChanged(ChangeEvent e) { 
                workspace.setScaleFactor(2.0*hbar.getValue()/hbar.getMaximum()); 
                workspace.repaint(); 
            } 
        }); 
        add(hbar,con); 

        con.gridy++; 
        panel=new JPanel(); 
        panel.add(new JLabel("")); 
        add(panel,con); 

        setSize(800,600); 

        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
        setLocation((int)(0.5*(screenSize.getWidth()-getWidth())),(int)(0.5*(screenSize.getHeight()-getHeight()))); 
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
        getContentPane().requestFocusInWindow(); 
        setVisible(true); 
    } 

    public Image getImageFromPath(String path) 
    { 
        try{ 
            return ImageIO.read(new File(path)); 
        }catch (IOException e){ 
            e.printStackTrace(); 
        } 
        return null; 
    } 

    public void strecth() 
    { 
        if(workspace.getNumImage()<=0)return; 
        double scale=1.0*workspace.getImage(0).getHeight(null)/workspace.getHeight(); 
        workspace.setScaleFactor(1.0/scale); 
        hbar.setValue((int)(1.0*workspace.getScaleFactor()*hbar.getMaximum()/2)); 
    } 

    private void openFile() 
    { 
        JFileChooser chooser = new JFileChooser(); 
        String fileBuf=Filepath; 
        if(fileBuf!=null){ 
            File home=new File(fileBuf); 
            if(home.isDirectory()){ 
                chooser.setCurrentDirectory(home); 
            }else{ 
                chooser.setCurrentDirectory(home.getParentFile()); 
            } 
        } 
        chooser.setDialogTitle("Select File"); 
        int returnVal = chooser.showOpenDialog(this); 
        if(returnVal == JFileChooser.APPROVE_OPTION) 
        { 
            File file = chooser.getSelectedFile(); 
            if (file != null) { 
                Filepath=file.getParentFile().getAbsolutePath(); 
                Image image=getImageFromPath(file.getAbsolutePath()); 
                if(image!=null){ 
                    if(workspace.getNumImage()==0)workspace.addImage(image,0,0); 
                    else workspace.setImage(0,image); 
                    strecth(); 
                    workspace.repaint(); 
                }else{ 
                    JOptionPane.showMessageDialog(this,"Cannot open "+file.getName()+"!","Alert",JOptionPane.INFORMATION_MESSAGE); 
                } 
            } 
        } 
    } 

    public static void main(String[] args) { 
        SimpleImageViewer main=new SimpleImageViewer(); 
        main.setup(); 
    } 

} 

Gambar.java

package myscanner; 
 
import java.awt.Image; 
 
public class Gambar 
{ 
    private Image gambar=null; 
    private double posx=0.0,posy=0.0; 

    public Gambar() 
    { 

    } 

    public Gambar(Image image) 
    { 
        gambar=image; 
    } 
 
    public Image getImage() { 
        return gambar; 
    } 
 
    public void setImage(Image gambar) { 
        this.gambar = gambar; 
    } 
 
    public double getX() { 
        return posx; 
    } 

    public void setPos(double posx,double posy) { 
        this.posx = posx; 
        this.posy = posy; 
    } 
 
    public void setPosx(double posx) { 
        this.posx = posx; 
    } 
 
    public double getY() { 
        return posy; 
    } 
 
    public void setPosy(double posy) { 
        this.posy = posy; 
    } 
} 

GraphPanel.java

package simpleimageviewer; 
 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Image; 
import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.awt.event.MouseEvent; 
import java.awt.event.MouseListener; 
import java.awt.event.MouseMotionListener; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JPanel; 
 
public class GraphPanel extends JPanel implements KeyListener,MouseListener, MouseMotionListener 
{ 
    protected List<Gambar> gambar = new ArrayList<Gambar>(); 
    private int mWidtho=0,mHeighto=0; 

    protected int mLastMouseX=0,mPosX=0,omPosX=0,oposx=0; 
    protected int mLastMouseY=0,mPosY=0,omPosY=0,oposy=0; 
    protected double mScaleFactor=1.0; 

    private Color backcolor=Color.WHITE; 

    protected int MODEDRAGWORLD=1; 
    public static int NODRAGABLEWORLD=0; 
    public static int DRAGABLEWORLD=1; 
 
    public GraphPanel() 
    { 
        this.addMouseListener(this); 
        this.addMouseMotionListener(this); 
        this.addMouseMotionListener(this); 
        this.setFocusable(true); 
        this.requestFocusInWindow(); 
    } 
 
    public final void addImage(Image image,double x,double y) { 
        Gambar gam=new Gambar(image); 
        gam.setPos(x,y); 
        gambar.add(gam); 
    } 

    public final Image getImage(int i) 
    { 
        return gambar.get(i).getImage(); 
    } 

    public final void setImage(int i,Image image) 
    { 
        gambar.set(i,new Gambar(image)); 
    } 

    public int getNumImage() 
    { 
        if(gambar==null)return 0; 
        return gambar.size(); 
    } 
 
    public void paintComponent(Graphics g) 
    { 
        if(mWidtho!=getWidth() || mHeighto!=getHeight()){ 
            onChangedWidthHeight(g); 
            mWidtho=getWidth(); 
            mHeighto=getHeight(); 
        } 
        g.setColor(backcolor); 
        g.fillRect(0,0,getWidth(),getHeight()); 

        Graphics2D g2d = (Graphics2D) g.create(); 
        g2d.translate((int)(0.5*getWidth()+mPosX),(int)(0.5*getHeight()+mPosY)); 
        g2d.scale(mScaleFactor,mScaleFactor); 
        if (gambar != null && gambar.size()>0) { 
            for(int i=0;i<gambar.size();i++){ 
                int pox=(int)Math.round(gambar.get(i).getX()-0.5*gambar.get(i).getImage().getWidth(null)); 
                int poy=(int)Math.round(gambar.get(i).getY()-0.5*gambar.get(i).getImage().getHeight(null)); 
                g2d.drawImage(gambar.get(i).getImage(),pox,poy,gambar.get(i).getImage().getWidth(null),gambar.get(i).getImage().getHeight(null), null); 
            } 
        } 
        addDrawing(g2d); 
        g2d.dispose(); 

        //g.setColor(Color.BLACK); 
        //g.drawString(mLastMouseX+" "+mLastMouseY, 10, 20); 
    } 

    public void addDrawing(Graphics2D g2d) 
    { 

    } 

    public void setScaleFactor(double value) 
    { 
        mScaleFactor=value; 
    } 

    public void setDragMode(int a) 
    { 
        MODEDRAGWORLD=a; 
    } 

    public double getScaleFactor() 
    { 
        return mScaleFactor; 
    } 
 
    public int getPosX() { 
        return mPosX; 
    } 
 
    public int getPosY() { 
        return mPosY; 
    } 

    public void onChangedWidthHeight(Graphics g) 
    { 

    } 

    public void keyPressed(KeyEvent e) { 

    } 
 
    public void keyReleased(KeyEvent e){ 

    } 

    public void keyTyped(KeyEvent e){ 

    } 
 
    public void mousePressed(MouseEvent e) 
    { 
        setLastMouse(e.getX(),e.getY()); 
        if (gambar != null && gambar.size() > 0 && MODEDRAGWORLD == DRAGABLEWORLD) { 
            oposx = e.getX(); 
            oposy = e.getY(); 
            omPosX = mPosX; 
            omPosY = mPosY; 
        } 
    } 
 
    public void mouseMoved(MouseEvent e) { 
        setLastMouse(e.getX(),e.getY()); 
    } 

    public void mouseDragged(MouseEvent e) { 
         setLastMouse(e.getX(),e.getY()); 
         if(gambar!=null && gambar.size()>0 && MODEDRAGWORLD==DRAGABLEWORLD){ 
             mPosX=omPosX+(e.getX()-oposx); 
             mPosY=omPosY+(e.getY()-oposy); 
             repaint(); 
         } 
    } 
 
    public void mouseReleased(MouseEvent e) { 

    } 
 
    public void mouseEntered(MouseEvent e) { 
 
    } 
 
    public void mouseExited(MouseEvent e) { 
 
    } 
 
    public void mouseClicked(MouseEvent e) { 
 
    } 

    public void setLastMouse(int ax,int ay){ 
        mLastMouseX=ax; 
        mLastMouseY=ay; 
    } 

    public int getLastMouseX() 
    { 
        return mLastMouseX; 
    } 

    public int getLastMouseY() 
    { 
        return mLastMouseY; 
    } 

    public double getScaleMouseX() 
    { 
        double pembagi=mScaleFactor; 
        if(mScaleFactor==0)pembagi=0.000001; 
        return (0.5*getWidth()+mPosX-mLastMouseX)/pembagi; 
    } 

    public double getScaleMouseY() 
    { 
        double pembagi=mScaleFactor; 
        if(mScaleFactor==0)pembagi=0.000001; 
        return (0.5*getHeight()+mPosY-mLastMouseY)/pembagi; 
    } 

    public void setBackColor(Color clr) 
    { 
        backcolor=clr; 
    } 

    public Color getBackColor() 
    { 
        return backcolor; 
    } 
 
    public List<Gambar> getGambar() { 
        return gambar; 
    } 

    public void removeGambar() 
    { 
        gambar=new ArrayList<Gambar>(); 
    } 
} 

Komentar



Postingan populer dari blog ini

Apps Script untuk Cetak Sertifikat

Kumpulan Source Code Greenfoot

Menyembunyikan Failed Load Images di Blogger

Kode Greenfoot Game Flappy Bird

Algorithma Coretan Abstrak dengan HTML5 Canvas

Kebodohan Karyawan Menyalahkan Sistem

Algorithma Bilangan Prima dengan Javascript

Checking Data yang Belum Dimasukkan dalam Daftar Menggunakan Query Google Sheet

Mencoba Submit Theme di Wordpress.org

Generate Karakter Acak dan Menempatkannya di Sel Google Sheets dengan Apps Script