導航:首頁 > 編程語言 > javaapplet繪制圖形

javaapplet繪制圖形

發布時間:2024-02-01 04:57:26

java怎麼繪制一個正方形

可使用Graphics 的fillRect繪制正方形,代碼如下:

importjava.awt.Color;
importjava.awt.Graphics;
importjavax.swing.JFrame;

publicclassRectextendsJFrame{
專Rect(){
屬setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
publicvoidpaint(Graphicsg){
g.setColor(Color.blue);
g.drawRect(80,80,50,50);
g.fillRect(150,150,50,50);
}
publicstaticvoidmain(String[]args){
newRect();
}
}

② java 繪圖程序

我基於你原來畫圖的方法,添加了事件觸發的命令b[j].setActionCommand("b" + j);否則你不能在事件響應處理的方法中使用e.getActionCommand(),而且字元串的比較用equals方法比較好。現在可以運行了,你可以看一下:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class drawing extends Applet implements ActionListener {
Button b[] = new Button[5];
String fontname = "仿宋_GB2312";
int style = Font.PLAIN;
int size = 24;
int index = 0;
Font myfont;

public void init() {
setSize(700,700);
myfont = new Font(fontname, style, size);
b[0] = new Button("扇形");
b[1] = new Button("圓形");
b[2] = new Button("三角形");
b[3] = new Button("長方形");
b[4] = new Button("橢圓形");
for (int j = 0; j < b.length; j++) {
b[j].setBounds(10, 10, 50, 20);
b[j].addActionListener(this);
b[j].setActionCommand("b" + j);
add(b[j]);
}
}

public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("b0")) {
index = 0;
repaint();
}
if (e.getActionCommand().equals("b1")) {
index = 1;
repaint();
}
if (e.getActionCommand().equals("b2")) {
index = 2;
repaint();
}
if (e.getActionCommand().equals("b3")) {
index = 3;
repaint();
}
if (e.getActionCommand().equals("b4")) {
index = 4;
repaint();
}
}

public void paint(Graphics g) {
switch (index) {
case 0:
g.fillArc(0, 60, 80, 60, 30, 120);
break;
case 1:
g.drawOval( 300, 50, 60, 60);
break;
case 2:
Polygon filledPolygon = new Polygon();
filledPolygon.addPoint(380, 50);
filledPolygon.addPoint(380, 110);
filledPolygon.addPoint(450, 90);
g.drawPolygon(filledPolygon);
break;
case 3:
g.drawRect( 200, 50, 80, 60);
break;
case 4:
g.drawOval(100, 50, 80, 60);
break;
default:
g.fillArc(0, 60, 80, 60, 30, 120);
break;
}

}
/*
* public void paint(Graphics g) { g.fillArc( 0, 60, 80, 60, 30, 120);
* //繪制扇形 g.drawOval( 100, 50, 80, 60); g.drawRect( 200, 50, 80, 60);
* g.drawOval( 300, 50, 60, 60); Polygon filledPolygon=new Polygon();
* filledPolygon.addPoint(380,50); filledPolygon.addPoint(380,110);
* filledPolygon.addPoint(450,90); g.drawPolygon(filledPolygon); }
*/
}

③ 、編寫Applet程序,在屏幕上畫一組同心圓(至少20個),相鄰兩圓的直徑相差10 像素。

public class MyClock extends Applet implements Runnable
{
static final int BACKGROUND=0; //背景圖片的序號,供數組使用
static final int LOGO=1; //LOGO圖片的序號,供數組使用
static final String JAVEX="bear"; //表盤上顯示的文字
static final double MINSEC=0.104719755; //分針和秒針在表盤上的刻度(60個)間的弧度
static final double HOUR=0.523598776; //時針在表盤上的刻度(24個)間的弧度

Thread clockThread = null; //使用多線程機制,用另一個線程不斷顯示圖片

//提供的默認參數,如果HTML文件裡面沒有給參數就使用
int width = 100;
int height = 100;
Color bgColor = new Color(0,0,0);
Color faceColor = new Color(0,0,0);
Color sweepColor = new Color(255,0,0);
Color minuteColor = new Color (192,192,192);
Color hourColor = new Color (255,255,255);
Color textColor = new Color (255,255,255);
Color caseColor = new Color (0,0,0);
Color trimColor = new Color (192,192,192);
String logoString=null;

Image images[] = new Image[2]; //背景和LOGO的圖片

boolean isPainted=false; //如果第一次載入時繪制背景及表盤,其他時候重繪則只繪制指針

//時鍾圓心的位置
int x1,y1;

//最上面那個三角形的刻度圖形的坐標
int xPoints[]=new int[3], yPoints[]=new int[3];

//保存當前時間,轉換成(double)(hours + minutes/60)
Hms cur_time;

//秒針、分針、時針
SweepHand sweep;
HmHand minuteHand,
hourHand;

//用於繪制的時、分、秒
double lastHour;
int lastMinute,lastSecond;

//顯示日期和表盤上的字母的字體
Font font;

//圖片顯示使用了緩沖機制,offScrImage和offScrGC存放緩沖區內圖片的信息
Image offScrImage;
Graphics offScrGC;

//用於測試背景圖片和LOGO圖片
MediaTracker tracker;

int minDimension; // 如果背景區域不是正方形的話,保證時鍾在中間顯示
int originX; // 時鍾圖形所在正方形區域的左上角X坐標
int originY; // 時鍾圖形所在正方形區域的左上角Y坐標

double tzDifference=0; //時區間的差,向西為負數,向東為正數

boolean localOnly=false; //是否只使用本地時間,如果為FALSE則可以根據傳入的時區顯示該時區時間

//保存參數的類型說明
public String[][] getParameterInfo()
{
String[][] info = {
{"width", "int", "APPLET的長度,以象素為單位"},
{"height", "int", "APPLET的寬度,以象素為單位"},
{"bgColor", "string", "背景顏色,e.g FF0000"},
{"faceColor", "string", "表盤顏色"},
{"sweepColor", "string", "秒針顏色"},
{"minuteColor", "string", "分針顏色"},
{"hourColor", "string", "時針顏色"},
{"textColor", "string", "文本顏色"},
{"caseColor", "string", "框內顏色"},
{"trimColor", "string", "空白區顏色"},
{"bgImageURL", "string", "背景圖片地址"},
{"logoString", "string", "LOGO字元"},
{"logoImageURL","string", "LOGO圖片地址"},
{"timezone", "real", "時區間的差"},
{"localonly", "int", "是否考慮到時區差別"}
};
return info;
}

//顯示信息
public String getAppletInfo()
{
return "版權所有,COPY必究,保護正版,人人有責";
}

void showURLerror(Exception e)
{
String errorMsg = "URL錯誤:"+e;
showStatus(errorMsg);
System.err.println(errorMsg);
}

//相當於把時鍾變成100×100的大小,percent即相對坐標
private int size(int percent)
{
return (int)((double)percent/100.0 * (double)minDimension);
}

public void init()
{
URL imagesURL[] = new URL[2];
String szImagesURL[] = new String[2];
tracker = new MediaTracker(this);

//得到HTML頁面提供的參數,並把它轉換相應的格式
String paramString = getParameter( "WIDTH" );
if( paramString != null )
width = Integer.valueOf(paramString).intValue();

paramString = getParameter( "HEIGHT" );
if( paramString != null )
height = Integer.valueOf(paramString).intValue();

paramString = getParameter( "TIMEZONE" );
if( paramString != null )
tzDifference = Double.valueOf(paramString).doubleValue();

paramString = getParameter( "LOCALONLY" );
if( paramString != null && Integer.valueOf(paramString).intValue() != 0){
localOnly=true;
tzDifference=0.;
}

paramString = getParameter( "BGCOLOR");
if( paramString != null )
bgColor=parseColorString(paramString);

paramString = getParameter( "FACECOLOR");
if( paramString != null )
faceColor=parseColorString(paramString);

paramString = getParameter( "SWEEPCOLOR");
if( paramString != null )
sweepColor=parseColorString(paramString);

paramString = getParameter( "MINUTECOLOR");
if( paramString != null )
minuteColor=parseColorString(paramString);

paramString = getParameter( "HOURCOLOR");
if( paramString != null )
hourColor=parseColorString(paramString);

paramString = getParameter( "TEXTCOLOR");
if( paramString != null )
textColor=parseColorString(paramString);

paramString = getParameter( "CASECOLOR");
if( paramString != null )
caseColor=parseColorString(paramString);

paramString = getParameter( "TRIMCOLOR");
if( paramString != null )
trimColor=parseColorString(paramString);

logoString = getParameter( "LOGOSTRING");
if( logoString == null )
logoString=JAVEX;
else if(logoString.length() > 8)
logoString= logoString.substring(0,8); //限制8個字母,否則顯示不下!

//szImagesURL數組根據HTML傳入參數存放圖片的文件名
szImagesURL[BACKGROUND] = getParameter("BGIMAGEURL");
szImagesURL[LOGO] = getParameter("LOGOIMAGEURL");

//測試圖片
for(int i=0; i<2; i++){
if(szImagesURL[i] != null){
//根據CodeBase參數與Image文件名得到image的路徑,測試是否存在,如果不存在就不用圖片
try{
imagesURL[i]=new URL(getCodeBase(),szImagesURL[i]);
} catch (MalformedURLException e)
{
showURLerror(e);
imagesURL[i]=null;
images[i]=null;
}
if(imagesURL[i] != null){
showStatus("載入圖片: " + imagesURL[i].toString());
images[i]=getImage(imagesURL[i]);
if(images[i] != null)
tracker.addImage(images[i],i);
showStatus("");
}
try{
tracker.waitForAll(i);
}catch (InterruptedException e){}
}
else images[i]=null;
}

//得到相應時區的時間
cur_time=(localOnly)? new Hms() : new Hms(tzDifference);
lastHour=-1.0;
lastMinute=-1;
lastSecond=-1;

x1=width/2;
y1=height/2;

//換算出圓形時鍾在背景里的左上角坐標
minDimension= Math.min(width, height);
originX=(width-minDimension)/2;
originY=(height-minDimension)/2;

//計算出上面三角形的三個點的坐標
xPoints[1]=x1-size(3); xPoints[2]=x1+size(3); xPoints[0]=x1;
yPoints[1]=y1-size(38);yPoints[2]=y1-size(38); yPoints[0]=y1-size(27);

//計算出秒針、分針、時針圖形的各個點坐標
sweep=new SweepHand(x1,y1,size(40),3);
minuteHand=new HmHand(x1,y1,size(40),size(6),6);
hourHand=new HmHand(x1,y1,size(25),size(8),6);

//構造字體
font=new Font("TXT",Font.BOLD,size(10));

//構造緩沖區內圖形
offScrImage = createImage(width,height);
offScrGC = offScrImage.getGraphics();

System.out.println(getAppletInfo());
}

public void start() //開始啟動顯示線程
{
if(clockThread == null){
clockThread = new Thread(this);
}
clockThread.start();
}

public void stop() //停止顯示
{
clockThread = null;
}

private void drawHands(Graphics g)
{

double angle;
int i,j;
int x,y;

angle=MINSEC * lastSecond; //根據lastSecond算出秒針相對於12點刻度的角度
sweep.draw(faceColor, angle, g);//畫出秒針

//如果時與分改變則重繪時針分針
if(cur_time.getMinutes() != lastMinute){
minuteHand.draw(faceColor,MINSEC*lastMinute,g);
if(cur_time.get_hours() != lastHour)
hourHand.draw(faceColor,HOUR*lastHour,g);
}

g.setColor(textColor);
g.fillRect(originX+size(12),y1-size(2),size(10),size(4)); //繪制左側橫條
g.fillRect(x1-size(2),originY + minDimension-size(22),size(4),size(10)); //繪制下面的橫條
g.fillPolygon( xPoints, yPoints, 3); //繪制頂部的三角形
for(i=1;i<12;i+=3) //在表盤的2、3、5、6、8、9、11時針刻度區繪制圓
for(j=i;j<i+2;j++){
x=(int)(x1+Math.sin(HOUR*j)*size(35));
y=(int)(y1-Math.cos(HOUR*j)*size(35));
g.fillOval(x-size(3),y-size(3),size(6),size(6));
}

//設置字體
g.setFont(font);
FontMetrics fm=g.getFontMetrics();

//畫頂部的LOGO字元串
g.drawString(logoString,x1-fm.stringWidth(logoString)/2,y1-size(12));

//得到日期
String day=Integer.toString(cur_time.getDate(),10);

//將日期繪制在表盤右側
g.drawString( day,
originX + minDimension-size(14)-fm.stringWidth(day),
y1+size(5));

//外面畫上框子
g.drawRect( originX + minDimension-size(14)-fm.stringWidth(day)-size(2),
y1-size(5)-size(2),
fm.stringWidth(day)+size(4),
size(10)+size(4));

if(images[LOGO] != null){ //如果LOGO圖片存在,在底部畫出來
x = originX + (minDimension-images[LOGO].getWidth(this))/2;
y = y1 + (minDimension/2 - size(22) - images[LOGO].getHeight(this))/2;
if(x > 0 && y > 0)
offScrGC.drawImage(images[LOGO], x, y, this);
}

lastHour=cur_time.get_hours();
hourHand.draw(hourColor,HOUR*lastHour,g); //畫時針

lastMinute=cur_time.getMinutes();
minuteHand.draw(minuteColor,MINSEC*lastMinute,g); //畫分針

g.setColor(minuteColor); //繪制分針尾部的圓形
g.fillOval(x1-size(4),y1-size(4),size(8),size(8));
g.setColor(sweepColor); //繪制秒針尾部的圓形
g.fillOval(x1-size(3),y1-size(3),size(6),size(6));

lastSecond=cur_time.getSeconds(); //得到新的秒數,重畫
angle=MINSEC*lastSecond;
sweep.draw(sweepColor, angle,g);

g.setColor(trimColor);
g.fillOval(x1-size(1),y1-size(1),size(2),size(2)); //秒針尾部圓心部分應該是螺絲,挖空處理^_^
}

private Color parseColorString(String colorString) //參數傳入為字元串形(規定為16進制6位字元串)
{
if(colorString.length()==6){
int R = Integer.valueOf(colorString.substring(0,2),16).intValue(); //前兩位為R值
int G = Integer.valueOf(colorString.substring(2,4),16).intValue(); //中間為G值
int B = Integer.valueOf(colorString.substring(4,6),16).intValue(); //最後為B值
return new Color(R,G,B); //得到COLOR
}
else return Color.lightGray; //字元串不符合規范,默認為灰色
}

public void run()
{
repaint(); //每次啟動時首先重繪一次
//每隔500ms獲得現在時間並重繪一次
while(null != clockThread){
cur_time= (localOnly)? new Hms() :new Hms(tzDifference);
repaint();

try{
Thread.sleep(500);
} catch (InterruptedException e) {}
}
}

public void paint(Graphics g) //首先繪制緩沖區內圖片,再顯示出來
{
int i,x0,y0,x2,y2;

//如果沒有提供背景圖片,則用bgColor繪制背景
if(images[BACKGROUND] == null){
offScrGC.setColor(bgColor);
offScrGC.fillRect(0,0,width,height);
}
else //否則直接使用背景圖片
offScrGC.drawImage(images[BACKGROUND], 0, 0, this);

//繪制外框到表盤間的部分
offScrGC.setColor(caseColor);

//將園形的范圍適量縮減(不充滿整個區域),防止有些地方被截取
offScrGC.fillOval( originX+1,
originY+1,
minDimension-2,
minDimension-2);

//繪製表盤
offScrGC.setColor(faceColor);
offScrGC.fillOval( originX + size(5),
originY + size(5),
minDimension - size(10),
minDimension - size(10));

//繪制外框線
offScrGC.setColor(trimColor);
offScrGC.drawOval( originX+1,
originY+1,
minDimension-2,
minDimension-2);

//繪制內框線
offScrGC.drawOval( originX + size(5),
originY + size(5),
minDimension - size(10),
minDimension - size(10));

offScrGC.setColor(textColor);

//畫刻度,一共有60個刻度,x0、y0為刻度起始的位置,x1、y1圓心位置,x2、y2為刻度終止位置(x0<x2,y0<y2)
for(i=0;i<60;i++){
if(i==0 || (i>=5 && i%5 == 0)){ // x0=(int)(x1+size(40)*Math.sin(MINSEC*i));
y0=(int)(y1+size(40)*Math.cos(MINSEC*i));
}
else{ //其他部分繪制短線
x0=(int)(x1+size(42)*Math.sin(MINSEC*i));
y0=(int)(y1+size(42)*Math.cos(MINSEC*i));
}
x2=(int)(x1+size(44)*Math.sin(MINSEC*i));
y2=(int)(y1+size(44)*Math.cos(MINSEC*i));
offScrGC.drawLine(x0,y0,x2,y2);
}

drawHands(offScrGC); //繪制指針
g.drawImage(offScrImage,0,0,this); //把生成的緩沖區圖形繪制到頁面上

isPainted=true; //使下次UPDATE時不繪製表盤
}

public synchronized void update(Graphics g)
{
if(!isPainted)
paint(g);
else{
drawHands(offScrGC);
g.drawImage(offScrImage,0,0,this);
}
}
}

<HTML>
<TITLE></TITLE>
<BODY>
<h2></h2>
<p>
<applet code="MyClock.class" width="300" height="300">
<param name="BGCOLOR" value="FFFFFF">
<param name="FACECOLOR" value="FFFFFF">
<param name="SWEEPCOLOR" value="FF0000">
<param name="MINUTECOLOR" value="008080">
<param name="HOURCOLOR" value="000080">
<param name="TEXTCOLOR" value="000000">
<param name="CASECOLOR" value="000080">
<param name="TRIMCOLOR" value="C0C0C0">
<param name="LOGOIMAGEURL" value="java.gif">
<param name="TIMEZONE" value="8">
</p>
</BODY>
</HTML>

④ java 實現 簡單畫圖功能(簡單點的)

樓主給你一個我編的,直接保存成pb.java編譯運行,就是你要的畫圖功能
____________________________________________________________________

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.awt.geom.*;
import java.io.*;

class Point implements Serializable
{
int x,y;
Color col;
int tool;
int boarder;

Point(int x, int y, Color col, int tool, int boarder)
{
this.x = x;
this.y = y;
this.col = col;
this.tool = tool;
this.boarder = boarder;
}
}

class paintboard extends Frame implements ActionListener,MouseMotionListener,MouseListener,ItemListener
{
int x = -1, y = -1;
int con = 1;//畫筆大小
int Econ = 5;//橡皮大小

int toolFlag = 0;//toolFlag:工具標記
//toolFlag工具對應表:
//(0--畫筆);(1--橡皮);(2--清除);
//(3--直線);(4--圓);(5--矩形);

Color c = new Color(0,0,0); //畫筆顏色
BasicStroke size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);//畫筆粗細
Point cutflag = new Point(-1, -1, c, 6, con);//截斷標志

Vector paintInfo = null;//點信息向量組
int n = 1;

FileInputStream picIn = null;
FileOutputStream picOut = null;

ObjectInputStream VIn = null;
ObjectOutputStream VOut = null;

// *工具面板--畫筆,直線,圓,矩形,多邊形,橡皮,清除*/
Panel toolPanel;
Button eraser, drLine,drCircle,drRect;
Button clear ,pen;
Choice ColChoice,SizeChoice,EraserChoice;
Button colchooser;
Label 顏色,大小B,大小E;
//保存功能
Button openPic,savePic;
FileDialog openPicture,savePicture;

paintboard(String s)
{
super(s);
addMouseMotionListener(this);
addMouseListener(this);

paintInfo = new Vector();

/*各工具按鈕及選擇項*/
//顏色選擇
ColChoice = new Choice();
ColChoice.add("black");
ColChoice.add("red");
ColChoice.add("blue");
ColChoice.add("green");
ColChoice.addItemListener(this);
//畫筆大小選擇
SizeChoice = new Choice();
SizeChoice.add("1");
SizeChoice.add("3");
SizeChoice.add("5");
SizeChoice.add("7");
SizeChoice.add("9");
SizeChoice.addItemListener(this);
//橡皮大小選擇
EraserChoice = new Choice();
EraserChoice.add("5");
EraserChoice.add("9");
EraserChoice.add("13");
EraserChoice.add("17");
EraserChoice.addItemListener(this);
////////////////////////////////////////////////////
toolPanel = new Panel();

clear = new Button("清除");
eraser = new Button("橡皮");
pen = new Button("畫筆");
drLine = new Button("畫直線");
drCircle = new Button("畫圓形");
drRect = new Button("畫矩形");

openPic = new Button("打開圖畫");
savePic = new Button("保存圖畫");

colchooser = new Button("顯示調色板");

//各組件事件監聽
clear.addActionListener(this);
eraser.addActionListener(this);
pen.addActionListener(this);
drLine.addActionListener(this);
drCircle.addActionListener(this);
drRect.addActionListener(this);
openPic.addActionListener(this);
savePic.addActionListener(this);
colchooser.addActionListener(this);

顏色 = new Label("畫筆顏色",Label.CENTER);
大小B = new Label("畫筆大小",Label.CENTER);
大小E = new Label("橡皮大小",Label.CENTER);
//面板添加組件
toolPanel.add(openPic);
toolPanel.add(savePic);

toolPanel.add(pen);
toolPanel.add(drLine);
toolPanel.add(drCircle);
toolPanel.add(drRect);

toolPanel.add(顏色); toolPanel.add(ColChoice);
toolPanel.add(大小B); toolPanel.add(SizeChoice);
toolPanel.add(colchooser);

toolPanel.add(eraser);
toolPanel.add(大小E); toolPanel.add(EraserChoice);

toolPanel.add(clear);
//工具面板到APPLET面板
add(toolPanel,BorderLayout.NORTH);

setBounds(60,60,900,600); setVisible(true);
validate();
//dialog for save and load

openPicture = new FileDialog(this,"打開圖畫",FileDialog.LOAD);
openPicture.setVisible(false);
savePicture = new FileDialog(this,"保存圖畫",FileDialog.SAVE);
savePicture.setVisible(false);

openPicture.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ openPicture.setVisible(false); }
});

savePicture.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ savePicture.setVisible(false); }
});

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0);}
});

}

public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;

Point p1,p2;

n = paintInfo.size();

if(toolFlag==2)
g.clearRect(0,0,getSize().width,getSize().height);//清除

for(int i=0; i<n ;i++){
p1 = (Point)paintInfo.elementAt(i);
p2 = (Point)paintInfo.elementAt(i+1);
size = new BasicStroke(p1.boarder,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

g2d.setColor(p1.col);
g2d.setStroke(size);

if(p1.tool==p2.tool)
{
switch(p1.tool)
{
case 0://畫筆

Line2D line1 = new Line2D.Double(p1.x, p1.y, p2.x, p2.y);
g2d.draw(line1);
break;

case 1://橡皮
g.clearRect(p1.x, p1.y, p1.boarder, p1.boarder);
break;

case 3://畫直線
Line2D line2 = new Line2D.Double(p1.x, p1.y, p2.x, p2.y);
g2d.draw(line2);
break;

case 4://畫圓
Ellipse2D ellipse = new Ellipse2D.Double(p1.x, p1.y, Math.abs(p2.x-p1.x) , Math.abs(p2.y-p1.y));
g2d.draw(ellipse);
break;

case 5://畫矩形
Rectangle2D rect = new Rectangle2D.Double(p1.x, p1.y, Math.abs(p2.x-p1.x) , Math.abs(p2.y-p1.y));
g2d.draw(rect);
break;

case 6://截斷,跳過
i=i+1;
break;

default :
}//end switch
}//end if
}//end for
}

public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==ColChoice)//預選顏色
{
String name = ColChoice.getSelectedItem();

if(name=="black")
{c = new Color(0,0,0); }
else if(name=="red")
{c = new Color(255,0,0);}
else if(name=="green")
{c = new Color(0,255,0);}
else if(name=="blue")
{c = new Color(0,0,255);}
}
else if(e.getSource()==SizeChoice)//畫筆大小
{
String selected = SizeChoice.getSelectedItem();

if(selected=="1")
{
con = 1;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="3")
{
con = 3;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="5")
{con = 5;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="7")
{con = 7;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="9")
{con = 9;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
}
else if(e.getSource()==EraserChoice)//橡皮大小
{
String Esize = EraserChoice.getSelectedItem();

if(Esize=="5")
{ Econ = 5*2; }
else if(Esize=="9")
{ Econ = 9*2; }
else if(Esize=="13")
{ Econ = 13*2; }
else if(Esize=="17")
{ Econ = 17*3; }

}

}

public void mouseDragged(MouseEvent e)
{
Point p1 ;
switch(toolFlag){
case 0://畫筆
x = (int)e.getX();
y = (int)e.getY();
p1 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p1);
repaint();
break;

case 1://橡皮
x = (int)e.getX();
y = (int)e.getY();
p1 = new Point(x, y, null, toolFlag, Econ);
paintInfo.addElement(p1);
repaint();
break;

default :
}
}

public void mouseMoved(MouseEvent e) {}

public void update(Graphics g)
{
paint(g);
}

public void mousePressed(MouseEvent e)
{
Point p2;
switch(toolFlag){
case 3://直線
x = (int)e.getX();
y = (int)e.getY();
p2 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p2);
break;

case 4: //圓
x = (int)e.getX();
y = (int)e.getY();
p2 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p2);
break;

case 5: //矩形
x = (int)e.getX();
y = (int)e.getY();
p2 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p2);
break;

default :
}
}

public void mouseReleased(MouseEvent e)
{
Point p3;
switch(toolFlag){
case 0://畫筆
paintInfo.addElement(cutflag);
break;

case 1: //eraser
paintInfo.addElement(cutflag);
break;

case 3://直線
x = (int)e.getX();
y = (int)e.getY();
p3 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p3);
paintInfo.addElement(cutflag);
repaint();
break;

case 4: //圓
x = (int)e.getX();
y = (int)e.getY();
p3 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p3);
paintInfo.addElement(cutflag);
repaint();
break;

case 5: //矩形
x = (int)e.getX();
y = (int)e.getY();
p3 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p3);
paintInfo.addElement(cutflag);
repaint();
break;

default:
}
}

public void mouseEntered(MouseEvent e){}

public void mouseExited(MouseEvent e){}

public void mouseClicked(MouseEvent e){}

public void actionPerformed(ActionEvent e)
{

if(e.getSource()==pen)//畫筆
{toolFlag = 0;}

if(e.getSource()==eraser)//橡皮
{toolFlag = 1;}

if(e.getSource()==clear)//清除
{
toolFlag = 2;
paintInfo.removeAllElements();
repaint();
}

if(e.getSource()==drLine)//畫線
{toolFlag = 3;}

if(e.getSource()==drCircle)//畫圓
{toolFlag = 4;}

if(e.getSource()==drRect)//畫矩形
{toolFlag = 5;}

if(e.getSource()==colchooser)//調色板
{
Color newColor = JColorChooser.showDialog(this,"調色板",c);
c = newColor;
}

if(e.getSource()==openPic)//打開圖畫
{

openPicture.setVisible(true);

if(openPicture.getFile()!=null)
{
int tempflag;
tempflag = toolFlag;
toolFlag = 2 ;
repaint();

try{
paintInfo.removeAllElements();
File filein = new File(openPicture.getDirectory(),openPicture.getFile());
picIn = new FileInputStream(filein);
VIn = new ObjectInputStream(picIn);
paintInfo = (Vector)VIn.readObject();
VIn.close();
repaint();
toolFlag = tempflag;

}

catch(ClassNotFoundException IOe2)
{
repaint();
toolFlag = tempflag;
System.out.println("can not read object");
}
catch(IOException IOe)
{
repaint();
toolFlag = tempflag;
System.out.println("can not read file");
}
}

}

if(e.getSource()==savePic)//保存圖畫
{
savePicture.setVisible(true);
try{
File fileout = new File(savePicture.getDirectory(),savePicture.getFile());
picOut = new FileOutputStream(fileout);
VOut = new ObjectOutputStream(picOut);
VOut.writeObject(paintInfo);
VOut.close();
}
catch(IOException IOe)
{
System.out.println("can not write object");
}

}
}
}//end paintboard

public class pb
{
public static void main(String args[])
{ new paintboard("畫圖程序"); }
}

⑤ JAVA實現簡單的畫圖板

樓主寫一個html,很容易把下面代碼嵌入到applet,可以google一下實現,
還有自己不知道算不算復制。。。-_-!
--------------------------------------------------------------------
樓主給你一個我的,直接保存成pb.java編譯運行,就是你要的畫圖功能 ,可以參考一下
____________________________________________________________________

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.awt.geom.*;
import java.io.*;

class Point implements Serializable
{
int x,y;
Color col;
int tool;
int boarder;

Point(int x, int y, Color col, int tool, int boarder)
{
this.x = x;
this.y = y;
this.col = col;
this.tool = tool;
this.boarder = boarder;
}
}

class paintboard extends Frame implements ActionListener,MouseMotionListener,MouseListener,ItemListener
{
int x = -1, y = -1;
int con = 1;//畫筆大小
int Econ = 5;//橡皮大小

int toolFlag = 0;//toolFlag:工具標記
//toolFlag工具對應表:
//(0--畫筆);(1--橡皮);(2--清除);
//(3--直線);(4--圓);(5--矩形);

Color c = new Color(0,0,0); //畫筆顏色
BasicStroke size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);//畫筆粗細
Point cutflag = new Point(-1, -1, c, 6, con);//截斷標志

Vector paintInfo = null;//點信息向量組
int n = 1;

FileInputStream picIn = null;
FileOutputStream picOut = null;

ObjectInputStream VIn = null;
ObjectOutputStream VOut = null;

// *工具面板--畫筆,直線,圓,矩形,多邊形,橡皮,清除*/
Panel toolPanel;
Button eraser, drLine,drCircle,drRect;
Button clear ,pen;
Choice ColChoice,SizeChoice,EraserChoice;
Button colchooser;
Label 顏色,大小B,大小E;
//保存功能
Button openPic,savePic;
FileDialog openPicture,savePicture;

paintboard(String s)
{
super(s);
addMouseMotionListener(this);
addMouseListener(this);

paintInfo = new Vector();

/*各工具按鈕及選擇項*/
//顏色選擇
ColChoice = new Choice();
ColChoice.add("black");
ColChoice.add("red");
ColChoice.add("blue");
ColChoice.add("green");
ColChoice.addItemListener(this);
//畫筆大小選擇
SizeChoice = new Choice();
SizeChoice.add("1");
SizeChoice.add("3");
SizeChoice.add("5");
SizeChoice.add("7");
SizeChoice.add("9");
SizeChoice.addItemListener(this);
//橡皮大小選擇
EraserChoice = new Choice();
EraserChoice.add("5");
EraserChoice.add("9");
EraserChoice.add("13");
EraserChoice.add("17");
EraserChoice.addItemListener(this);
////////////////////////////////////////////////////
toolPanel = new Panel();

clear = new Button("清除");
eraser = new Button("橡皮");
pen = new Button("畫筆");
drLine = new Button("畫直線");
drCircle = new Button("畫圓形");
drRect = new Button("畫矩形");

openPic = new Button("打開圖畫");
savePic = new Button("保存圖畫");

colchooser = new Button("顯示調色板");

//各組件事件監聽
clear.addActionListener(this);
eraser.addActionListener(this);
pen.addActionListener(this);
drLine.addActionListener(this);
drCircle.addActionListener(this);
drRect.addActionListener(this);
openPic.addActionListener(this);
savePic.addActionListener(this);
colchooser.addActionListener(this);

顏色 = new Label("畫筆顏色",Label.CENTER);
大小B = new Label("畫筆大小",Label.CENTER);
大小E = new Label("橡皮大小",Label.CENTER);
//面板添加組件
toolPanel.add(openPic);
toolPanel.add(savePic);

toolPanel.add(pen);
toolPanel.add(drLine);
toolPanel.add(drCircle);
toolPanel.add(drRect);

toolPanel.add(顏色); toolPanel.add(ColChoice);
toolPanel.add(大小B); toolPanel.add(SizeChoice);
toolPanel.add(colchooser);

toolPanel.add(eraser);
toolPanel.add(大小E); toolPanel.add(EraserChoice);

toolPanel.add(clear);
//工具面板到APPLET面板
add(toolPanel,BorderLayout.NORTH);

setBounds(60,60,900,600); setVisible(true);
validate();
//dialog for save and load

openPicture = new FileDialog(this,"打開圖畫",FileDialog.LOAD);
openPicture.setVisible(false);
savePicture = new FileDialog(this,"保存圖畫",FileDialog.SAVE);
savePicture.setVisible(false);

openPicture.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ openPicture.setVisible(false); }
});

savePicture.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ savePicture.setVisible(false); }
});

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0);}
});

}

public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;

Point p1,p2;

n = paintInfo.size();

if(toolFlag==2)
g.clearRect(0,0,getSize().width,getSize().height);//清除

for(int i=0; i<n ;i++){
p1 = (Point)paintInfo.elementAt(i);
p2 = (Point)paintInfo.elementAt(i+1);
size = new BasicStroke(p1.boarder,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

g2d.setColor(p1.col);
g2d.setStroke(size);

if(p1.tool==p2.tool)
{
switch(p1.tool)
{
case 0://畫筆

Line2D line1 = new Line2D.Double(p1.x, p1.y, p2.x, p2.y);
g2d.draw(line1);
break;

case 1://橡皮
g.clearRect(p1.x, p1.y, p1.boarder, p1.boarder);
break;

case 3://畫直線
Line2D line2 = new Line2D.Double(p1.x, p1.y, p2.x, p2.y);
g2d.draw(line2);
break;

case 4://畫圓
Ellipse2D ellipse = new Ellipse2D.Double(p1.x, p1.y, Math.abs(p2.x-p1.x) , Math.abs(p2.y-p1.y));
g2d.draw(ellipse);
break;

case 5://畫矩形
Rectangle2D rect = new Rectangle2D.Double(p1.x, p1.y, Math.abs(p2.x-p1.x) , Math.abs(p2.y-p1.y));
g2d.draw(rect);
break;

case 6://截斷,跳過
i=i+1;
break;

default :
}//end switch
}//end if
}//end for
}

public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==ColChoice)//預選顏色
{
String name = ColChoice.getSelectedItem();

if(name=="black")
{c = new Color(0,0,0); }
else if(name=="red")
{c = new Color(255,0,0);}
else if(name=="green")
{c = new Color(0,255,0);}
else if(name=="blue")
{c = new Color(0,0,255);}
}
else if(e.getSource()==SizeChoice)//畫筆大小
{
String selected = SizeChoice.getSelectedItem();

if(selected=="1")
{
con = 1;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="3")
{
con = 3;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="5")
{con = 5;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="7")
{con = 7;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
else if(selected=="9")
{con = 9;
size = new BasicStroke(con,BasicStroke.CAP_BUTT,BasicStroke.JOIN_BEVEL);

}
}
else if(e.getSource()==EraserChoice)//橡皮大小
{
String Esize = EraserChoice.getSelectedItem();

if(Esize=="5")
{ Econ = 5*2; }
else if(Esize=="9")
{ Econ = 9*2; }
else if(Esize=="13")
{ Econ = 13*2; }
else if(Esize=="17")
{ Econ = 17*3; }

}

}

public void mouseDragged(MouseEvent e)
{
Point p1 ;
switch(toolFlag){
case 0://畫筆
x = (int)e.getX();
y = (int)e.getY();
p1 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p1);
repaint();
break;

case 1://橡皮
x = (int)e.getX();
y = (int)e.getY();
p1 = new Point(x, y, null, toolFlag, Econ);
paintInfo.addElement(p1);
repaint();
break;

default :
}
}

public void mouseMoved(MouseEvent e) {}

public void update(Graphics g)
{
paint(g);
}

public void mousePressed(MouseEvent e)
{
Point p2;
switch(toolFlag){
case 3://直線
x = (int)e.getX();
y = (int)e.getY();
p2 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p2);
break;

case 4: //圓
x = (int)e.getX();
y = (int)e.getY();
p2 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p2);
break;

case 5: //矩形
x = (int)e.getX();
y = (int)e.getY();
p2 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p2);
break;

default :
}
}

public void mouseReleased(MouseEvent e)
{
Point p3;
switch(toolFlag){
case 0://畫筆
paintInfo.addElement(cutflag);
break;

case 1: //eraser
paintInfo.addElement(cutflag);
break;

case 3://直線
x = (int)e.getX();
y = (int)e.getY();
p3 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p3);
paintInfo.addElement(cutflag);
repaint();
break;

case 4: //圓
x = (int)e.getX();
y = (int)e.getY();
p3 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p3);
paintInfo.addElement(cutflag);
repaint();
break;

case 5: //矩形
x = (int)e.getX();
y = (int)e.getY();
p3 = new Point(x, y, c, toolFlag, con);
paintInfo.addElement(p3);
paintInfo.addElement(cutflag);
repaint();
break;

default:
}
}

public void mouseEntered(MouseEvent e){}

public void mouseExited(MouseEvent e){}

public void mouseClicked(MouseEvent e){}

public void actionPerformed(ActionEvent e)
{

if(e.getSource()==pen)//畫筆
{toolFlag = 0;}

if(e.getSource()==eraser)//橡皮
{toolFlag = 1;}

if(e.getSource()==clear)//清除
{
toolFlag = 2;
paintInfo.removeAllElements();
repaint();
}

if(e.getSource()==drLine)//畫線
{toolFlag = 3;}

if(e.getSource()==drCircle)//畫圓
{toolFlag = 4;}

if(e.getSource()==drRect)//畫矩形
{toolFlag = 5;}

if(e.getSource()==colchooser)//調色板
{
Color newColor = JColorChooser.showDialog(this,"調色板",c);
c = newColor;
}

if(e.getSource()==openPic)//打開圖畫
{

openPicture.setVisible(true);

if(openPicture.getFile()!=null)
{
int tempflag;
tempflag = toolFlag;
toolFlag = 2 ;
repaint();

try{
paintInfo.removeAllElements();
File filein = new File(openPicture.getDirectory(),openPicture.getFile());
picIn = new FileInputStream(filein);
VIn = new ObjectInputStream(picIn);
paintInfo = (Vector)VIn.readObject();
VIn.close();
repaint();
toolFlag = tempflag;

}

catch(ClassNotFoundException IOe2)
{
repaint();
toolFlag = tempflag;
System.out.println("can not read object");
}
catch(IOException IOe)
{
repaint();
toolFlag = tempflag;
System.out.println("can not read file");
}
}

}

if(e.getSource()==savePic)//保存圖畫
{
savePicture.setVisible(true);
try{
File fileout = new File(savePicture.getDirectory(),savePicture.getFile());
picOut = new FileOutputStream(fileout);
VOut = new ObjectOutputStream(picOut);
VOut.writeObject(paintInfo);
VOut.close();
}
catch(IOException IOe)
{
System.out.println("can not write object");
}

}
}
}//end paintboard

public class pb
{
public static void main(String args[])
{ new paintboard("畫圖程序"); }
}

閱讀全文

與javaapplet繪制圖形相關的資料

熱點內容
文件夾正裝 瀏覽:279
剛復制的文件找不到怎麼辦 瀏覽:724
試運行適用於哪些體系文件 瀏覽:987
ghost文件復制很慢 瀏覽:967
傑德原車導航升級 瀏覽:240
編程dest是什麼意思 瀏覽:935
linux埠鏡像 瀏覽:820
iphone5屏幕清塵 瀏覽:157
機頂盒密碼怎麼改 瀏覽:672
w7系統下載32位教程 瀏覽:618
pcb文件包括哪些內容 瀏覽:598
g00文件 瀏覽:607
用bat程序刪除程序 瀏覽:516
dnf鬼泣90版本打安圖恩 瀏覽:668
245倒角編程怎麼計算 瀏覽:599
可以買生活用品的app有哪些 瀏覽:175
cad在c盤產生的文件夾 瀏覽:541
聯想手機解鎖工具 瀏覽:696
瑞銀3887win10 瀏覽:833
學網路編程哪個好 瀏覽:805

友情鏈接