J-한솔넷

간단한 이미지 뷰어 본문

프로그래밍/JAVA

간단한 이미지 뷰어

jhansol 2012. 9. 28. 19:25

학생들의 수업용으로 만든 프로그램입니다.

창의 크기를 조절할 때 이벤트가 발생하고 paint 함수를 호출 하는 것은 맞는데 update 함수는 호출 하지 않는 것 같다.

쩝....


imgVier.java


ImageViewFrame


ImageViewFrame$2.class


ImageViewFrame.class


imgVier.class


MyPanel.class


파일의 내용은 아래와 같다.


import java.awt.*;

import java.awt.event.*;


class imgVier 

{

public static void main(String[] args) 

{

new ImageViewFrame();

}

}


class ImageViewFrame extends Frame implements ActionListener 

{

MyPanel viewer;

Button btnOpen;

Image img;

TextField file;

String filename;


public ImageViewFrame() {

super( "이미지 뷰어" );

file = new TextField( 256 );

add( file, BorderLayout.NORTH );


viewer = new MyPanel();

add( viewer, BorderLayout.CENTER );


btnOpen = new Button( "열기" );

add( btnOpen, BorderLayout.SOUTH );

btnOpen.addActionListener( this );


setSize( 300, 300 );

setVisible( true );


addWindowListener( new WindowAdapter() {

public void windowClosing( WindowEvent e ) {

dispose();

System.exit( 0 );

}

}

);

addComponentListener(new ComponentAdapter() {

public void componentResized(ComponentEvent e) {

viewer.repaint();

}

}

);

}


public void actionPerformed( ActionEvent e ) {

FileDialog f = new FileDialog( this, "이미지 열기", FileDialog.LOAD );

String dir, name;


f.show();

dir = f.getDirectory();

name = f.getFile();


if( dir != null && name != null ) {

filename = dir + name;

file.setText( filename );

img = Toolkit.getDefaultToolkit().getImage( filename );

viewer.drawImage( img );

}

}

}


class MyPanel extends Panel {

Image img;

Image mem;


public void drawImage( Image img ) {

this.img = img;

repaint();

}


public void update( Graphics g ) {

int iwidth, iheight;

int width, height;


iwidth = iheight = 0;


width = getWidth();

height = getHeight();


try

{

do

{

iwidth = img.getWidth(null);

iheight = img.getHeight(null);

}

while (iwidth <= 0 || iheight <= 0 );


float r;


r = (float)width / iwidth;

iwidth *= r;

iheight *= r;


if( iheight > height ) {

r = (float)height / iheight;

iwidth *= r;

iheight *= r;

}


mem = createImage( width, height );

Graphics mg = mem.getGraphics();

mg.setColor( getBackground() );

mg.fillRect( 0, 0, width, height );


while( !mg.drawImage( img, 0, 0, iwidth, iheight, null ) );

}

catch ( Exception e) {}

paint( g );

}


public void paint( Graphics g ) {

try

{

g.drawImage( mem, 0, 0, this );

}

catch (Exception e) {}

}

}