| [縮小][拡大][元のサイズに戻す]ボタンで,さらにChoiceの<50%/75%/150%/200%>で画像サイズを変更できる。 マウスドラッグ操作で画像を移動できる。 MediaTrackerを利用(何故か,これを使わないと正常に拡大,縮小できない?) |
import java.applet.*;
import java.awt.*;
public class ja02a extends Applet
{
Button SB = new Button("縮小"); //ボタンの作成
Button LB = new Button("拡大");
Button DB = new Button("原サイズに戻す");
Choice CH = new Choice(); //Choiceコンポーネントの作成
MediaTracker mtr; //メディアトッラカー(画像のロード状態を監視する)
Image pic; //画像イメージ
int xpos = 95,ypos = 20; //表示する画像の左上座標
int wx,hy; //(画像の移動時)マウスクリック位置と,画像の左上座標との差
double picW,picH; //ロードした画像の幅と高さ
double scale = 1.0; //画像サイズの変更比率
double w,h; //サイズ変更後の画像の幅と高さ
public void init()
{
setLayout(null); //Layoutマネージャーは使わない
add(SB); //各ボタンを,位置とサイズを指定して配置
SB.reshape(5,5,40,20);
add(LB);
LB.reshape(5,30,40,20);
add(DB);
DB.reshape(5,55,85,20);
CH.addItem("50%"); //Choiceに項目を登録
CH.addItem("75%");
CH.addItem("150%");
CH.addItem("200%");
add(CH); //Choiceを,位置とサイズを指定して配置
CH.reshape(5,80,60,20);
mtr = new MediaTracker(this); //メディアトッラカーを作成
pic = getImage(getCodeBase(),"ja02a.jpg"); //画像イメージを取得
mtr.addImage(pic,0); //メディアトッラカーにロードする画像を登録
showStatus("画像の読み込み中です。Getting images:ja02a.jpg"); //プラウザのステータスバーに表示
try{
mtr.waitForID(0); //画像がロードされるまで待つ
}catch(InterruptedException e){}
picW = pic.getWidth(this); //画像のサイズを取得
picH = pic.getHeight(this);
}
public void paint(Graphics g)
{
if(!mtr.checkID(0)){ //画像のロードが終了しなかった場合
g.drawString("ja02a.jpgは未ロード",95,5);
return;
}
g.setColor(Color.red);
g.setFont(new Font("TimesRoman",Font.BOLD+Font.ITALIC,14)); //フォントを設定
g.drawString("画像を拡大/縮小できます", 95, 15);
w = scale * picW; //変更比率にしたがい,画像サイズを変更する
h = scale * picH;
g.drawImage(pic,xpos,ypos,(int)w,(int)h,this); //画像イメージを描画。(int)で整数型に型変換する
}
public boolean action(Event e,Object o){
if("縮小".equals(o)){ //[縮小]ボタンをクリックした場合
scale *= 0.9; //10&単位で縮小する
repaint();
return true;
}
if("拡大".equals(o)){
scale *= 1.1; //10%単位で拡大する
repaint();
return true;
}
if("原サイズに戻す".equals(o)){
scale = 1.0; //ロード時のサイズに戻す
repaint();
return true;
}
if(e.target instanceof Choice){ //Choiceが@された場合
if(o.equals("50%")){
scale = 0.5; //ロード時の50%サイズにする
repaint();
return true;
}
if(o.equals("75%")){
scale = 0.75;
repaint();
return true;
}
if(o.equals("150%")){
scale = 1.5;
repaint();
return true;
}
if(o.equals("200%")){
scale = 2.0;
repaint();
return true;
}
}
return false;
}
public boolean mouseDown(Event e,int x,int y){
wx = x - xpos; //マウスクリック位置と,画像の左上座標の差を計算
hy = y - ypos;
return true;
}
public boolean mouseDrag(Event e,int x,int y){
if(wx < (int)w && wx >= 0 && hy < (int)h && hy >= 0){ //マウスクリック位置が,画像内の場合
xpos = x -wx; //マウスドラッグ時の,画像の左上座標を計算
ypos = y -hy;
repaint();
}
return true;
}
}
末尾