① 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("画图程序"); }
}