java applet mouseClicked&Paint

2010-12-02 6:59 pm
Java程式很難…完全不明白..會的人請幫幫忙>< 謝謝 import java.awt.*;import java.awt.event.*;import java.applet.Applet;public class Marble extends Applet { public void init(){ MsListener mouseListener=new MsListener(); setBackground(Color.white); addMouseListener(mouseListener); } class MsListener extends MouseAdapter{ public void mouseClicked(MouseEvent e){ repaint(); } } public void paint(Graphics g){ int xp,yp; final int MAX=20,WIDTH=200,HEIGHT=200; g.draw3DRect(0,0,WIDTH-2,HEIGHT-2,false); for(int i=0;i<MAX;i++){ g.setColor(Color.blue); xp=(int)(Math.random()*WIDTH); yp=(int)(Math.random()*HEIGHT); g.fillOval(xp-5,yp-5,10,10); } }} 用以上的程式為基礎,稍作改動製作出新的applet:用mouse click了以後,那個位置會出現一粒藍點(最多10點) http://img146.imageshack.us/img146/2820/spots.gif hints: 在public void mouseClicked(MouseEvent e) 用 e.getX();e.getY(); 來取得x,y座標 座標用array xp[i]yp[i], 當click的時候,不止是顯示新click的一點,而是會同時出現之前所畫的所有點. 在method mouseClicked(MouseEvent e)& method paint(Graphics g) 會用到相同的座標所以要用global declaration

回答 (1)

2010-12-03 1:20 am
✔ 最佳答案
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

public class Marble extends Applet {
final int MAX=10;
int[] xp, yp;
int count;

public void init(){
xp = new int[MAX];
yp = new int[MAX];
count = 0;

MsListener mouseListener=new MsListener();
setBackground(Color.white);
addMouseListener(mouseListener);
}

class MsListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
if (count < MAX) {
xp[count] = e.getX();
yp[count] = e.getY();
count++;
}
repaint();
}
}

public void paint(Graphics g){
final int WIDTH=200,HEIGHT=200;

g.draw3DRect(0,0,WIDTH-2,HEIGHT-2,false);
for(int i=0;i<count;i++){
g.setColor(Color.blue);
g.fillOval(xp[i]-5,yp[i]-5,10,10);
}
}
}



2010-12-02 17:21:04 補充:
再有功課問題可以直接寫信問我丫^^


收錄日期: 2021-04-13 17:40:53
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20101202000051KK00251

檢視 Wayback Machine 備份