JAVA实验报告 简单绘图程序
java课程设计报告++画笔程序
目录一、前言 (2)二、功能简介 (3)三、概要设计 (4)四、详细设计 (5)五、测试数据及运行结果 (7)六、源程序 (9)七、总结 (19)八、参考文献 (20)一、前言Java不依赖平台的特点使它受到广泛的关注,Java已成为网络时代最重要的语言之一。
目前,Java语言不仅是一门被广泛使用的编程语言,而且已成为软件设计开发者应当掌握的一门基础语言。
因为很多新的技术领域都涉及到Java语言,国内外许多大学已将Java语言列入本科教学计划,而IT行业对Java人才的需求也在不断的增长,因此,掌握Java已经成为共识。
Java是一门说简单也不简单,说难也不难的课程。
所以,我们在学习的过程中要根据自己的具体情况,合理安排编程训练时间,相信编程能力会在不知不觉中得到提高。
二、功能简介1)设计一个画图程序,能够实现画笔、画直线、画圆形、画矩形的功能,并且在绘图过程中能够修改该画笔的大小以及颜色。
该画图程序还需具有橡皮擦功能以及清空整个画面的功能。
2)此程序要实现的功能如下:1、这个画图程序,最基本的功能是,作为一个画笔,能利用它实现在屏幕上任意绘画、书写的功能;2、利用这个画图程序,通过选择画直线、画圆形、画矩形等功能选项并且在屏幕上拖动鼠标操作能实现画出相应图形的功能;3、这个画图程序,还需具备橡皮擦的功能,利用这个橡皮擦能够擦除屏幕上的图案,并且此橡皮擦也应该能够改变大小;4、这个画图程序,还应该做到能够改变画笔颜色的功能;5、这个画图程序,还应该具备能够清除整个屏幕已绘制图画的功能。
三、概要设计1、此程序为实现这些功能模块,必须首先定义一个工具面板,将这些画笔、画直线、画圆形、画矩形、画笔颜色、画笔大小、橡皮等功能组件放入这个工具面板中。
2、此程序为实现利用鼠标做画笔的功能,必会产生鼠标事件MouseEvent。
因此,为实现鼠标画图的功能,必须用到鼠标触发事件,故在此程序中,必须实现“委托事件模型”,用到事件源、事件对象以及监听者对象。
绘图JAVA程序报告(含程序)
本次编程工具为 UltraEdit。
3 系统流程
开始
曲线 按钮
直线 按钮
画圆 按钮
矩形 按钮
粗线 按钮
填充 颜色
清除
画笔 粗细
f=1
f=2
f=3
f=4
f=5
填充
Y
N
fill=true
fill=false
size 改变
改变颜色
Y
N
输入颜 色
f=1
f=2
f=3
通过 JCheckBox 创建一个按钮,利用按钮监听器决定是否要描绘填 充图形,如果是则将实现赋值 fill=true,否则 fill=false,然后通过 布尔值判断在描绘图形时是 draw 还是 fill,如果布尔值是 ture 时则实 现了图形的填充。 2.2.4 画笔的粗细及画笔的颜色变更
画笔的粗细主要是通过不断地重画填充圆来实现,通过鼠标的拖拽 不断地在画板上进行重画;而粗细则由创建的 JSlider 来调节圆的半径, 如果圆的半径越大则所绘出的曲线越粗,反则越细;画笔的颜色变更主 要通过创建的 JButton 按钮,利用按钮监听器,当按下了按钮,则实现 c=JColorChooser.showDialog(right,"choose",c)语句,从而把初始的 画笔颜色(黑色)改变。 2.2.5 实现鼠标单击和鼠标拖拽进行绘图
在实现绘画的功能,主要通过创建 ButtonGroup 从而把所有的 JRadioButton 都添加进去,从而达到在描绘图形时多选一的选择功能; 利用按钮监听器,利用 Object source=event.getSource()语句当 source==op1 时进行曲线绘画,在实现曲线绘画的功能时,主要利用了 鼠标的点击和鼠标的拖拽,通过鼠标的点击来扑捉第一个坐标点,然后 利用鼠标的拖拽来不断变换第一个点的坐标(利用 sx=x 和 sy=y 语句), 从而将所有点都连接起来,最终实现了在画板上描绘曲线的功能;当 source==op2 时进行直线绘画,在实现直线绘画的功能时,主要利用了 鼠标的点击,鼠标的释放和鼠标的拖拽,通过鼠标的点击来扑捉直线的 第一个坐标点,然后利用鼠标的拖拽选择直线的另一个点,最终通过鼠 标的释放在画板上描绘出直线来;当 source==op3 时进行圆和椭圆绘画, 在实现圆和椭圆绘画的功能时,主要利用了鼠标的点击,鼠标的释放和 鼠标的拖拽,通过鼠标的点击来扑捉圆和椭圆的一个坐标点,然后利用 鼠标的拖拽选择圆和椭圆的大小,最终通过鼠标的释放在画板上描绘出 圆和椭圆来;当 source==op4 时进行矩形绘画,在实现矩形绘画的功能 时,主要利用了鼠标的点击,鼠标的释放和鼠标的拖拽,通过鼠标的点 击来扑捉矩形的一个坐标点,然后利用鼠标的拖拽选择矩形的大小,最 终通过鼠标的释放在画板上描绘出矩形来。 2.2.3 填充功能(其中包括圆的填充,椭圆圆的填充,矩形圆的填充)
Java实现简单的绘图软件
Java实现简单的绘图软件项目效果图:项目源代码:import java.awt.*;import java.awt.eve nt.*;import java.awt.geom.Ellipse2D; import java.awt.geom. Li ne2D; import java.awt.geom.Recta ngle2D; import java.awt.image.Bufferedlmage; import java.io.File;import java.io .IO Exceptio n;import javax.imagei o.I mageIO; import javax.swi ng.*;importjavax.sw in g.filechooser.FileNameExte nsion Filte r;/* author:蒋冰*/public class ImageDraw {private int typeFlag = 1;private int en dFlag = 1;private int strokeTemp = 1;private Color color = Color.black;private BasicStroke stroke = new BasicStroke();private float pre_x = 0;private float pre_y = 0;private float start_x = 0;private float start_y = 0;private float start_X = 0;private float start_Y = 0;private float end_x = 0;private float end_y = 0;private float width = 0;private float height = 0;private final int AREA_WIDTH = 700;private final int AREA_HEIGHT = 400;private Lin e2D.FIoat line;private Recta ngle2D.FIoat rect;private Ellipse2D.FIoat ellipse;private File imageFile;Bufferedlmage image = new Bufferedlmage(AREA_WIDTHAREA_HEIGHTBufferedImage.T YPE_INT_RGB);Graphics2D g2 = (Graphics2D)image.getGraphics();private JFrame frame = new JFrame(" 简单手绘程序");private DrawPa nel drawArea = new DrawPa nel();JButt on butt on ShowColor = new JButto n("");public void in it(){g2.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT);g2.setColor(Color.black);drawArea.setPreferredSize( newDime nsio n(AREA_WIDTHAREA_HEIGHT));drawArea.addMouseMotio nListe ner(new MouseMotionAdapter(){public void mouseDragged(MouseEvent e){do_mouseDragged(e);}});drawArea.addMouseListe ner(new MouseAdapter(){public void mousePressed(MouseEvent e1){do_mousePressed(e1);}public void mouseReleased(MouseEvent e){ g2.setColor(color); g2.setStroke(stroke);en dFlag = typeFlag; drawArea.repa in t();}public void mouseEntered(MouseEvent e){ frame.setCursor( newCursor(Cursor.CROSSHAIR_CURSOR));}public void mouseExited(MouseEve nte){ frame.setCursor( nu II);}});frame.add(drawArea);JMe nuBar mb = new JMen uBar();JMenu menuFile = new JMenu("文件");JMe nultem men ultemSave = new JMenultem("保存");men ultemSave.addActio nListe ner(new Actio nListe ner(){public void actio nPerformed(Actio nEve nt argO){ do_save_actio nPerformed(arg0);}});JMe nultem men ultemOpe n = new JMenultem("打开");men ultemOpe n.addActio nListe ner(new Actio nListe ner(){publicvoid actio nPerformed(Actio nEve nt argO) {try {do_ope n_acti on Performed(argO);} catch (lOExcepti on e) {II TODO自动生成的catch块e.pri ntStackTrace();}}});JMe nultem men ultemExit = new JMenultem("退出");men ultemExit.addActio nListe ner(new Actio nListe ner(){public void actio nPerformed(Actio nEve nt argO) {System.exit(O);});men uFile.add(me nultemSave);men uFile.add(me nultemOpe n);men uFile.add(me nultemExit);mb.add(me nuFile);JPa nel butt onPanel = new JPa nel();FlowLayout layout = new FlowLayout(FlowLayout.CENTER, 20, 20);butt onPan el.setLayout(layout);butt onPan el.setBackgro un d(Color.gray);JButton butto nDraw = new JButto n(" 绘图");butt on Draw.addActio nListe ner(newActio nListe ner(){public void actio nPerformed(Actio nEve nt argO) {typeFlag = 1;}});buttonPa nel.add(buttonDraw);JButton buttonLine = new JButton("直线”);butt onLin e.addActi on Liste ner(newActio nListe ner(){public void actio nPerformed(Actio nEve nt argO) {typeFlag = 2;}});butt onPan el.add(butt onLin e);JButt on butt on Rect = new JButto n("矩形");butt on Rect.addActio nListe ner(newActio nListe ner(){public void actio nPerformed(Actio nEve nt arg0) {typeFlag = 3;}});buttonPa nel.add(buttonRect);JButton buttonEllipse = new JButton("椭圆");butt on Ellipse.addActio nListe ner(newActio nListe ner(){public void actio nPerformed(Actio nEve nt argO) {typeFlag = 4;}});butt onPan el.add(butt on Ellipse);JButt on butt on Drop = new JButto n("清除");butt on Drop.addActio nListe ner(newActio nListe ner(){public void actio nPerformed(Actio nEve nt arg0) {typeFlag = 5;g2.setColor(Color.white);g2.fillRect(0 , 0 ,AREA_WIDTH , AREA_HEIGHT);drawArea.repa in t();}});butt onPan el.add(butt on Drop);butt on ColorChoose.addActio nListe ner(newActio nListe ner(){ public void actio nPerformed(Actio nEve nt argO) {do_butt on ColorChoose_acti on Performed(arg 0);}});buttonPa nel.add(buttonColorChoose); butto nShowColor = new JButt on ("");buttonPa nel.add(buttonShowColor); JButt on butt onColorChooseJButton("选择颜色"); newJLabel label = new JLabel("边框:"); butt onPan el.add(label);JComboBox comboxJComboBox();for(int i=1; i<=36; i++){combox.addltem(i);}combox.addItemListe ner(newItemListe ner() {publicitemStateCha nged(ltemEve nt e){ strokeTempIn teger.parseI nt(e.getltem().toStri ng());stroke= BasicStroke(strokeTemp);}});butt onPan el.add(combox);frame.add(butt onPan el,BorderLayout.SOUT H); newvoid newframe.add(mb,BorderLayout.NORTH);frame.setBackgro un d(Color.gray);frame.pack();frame.setVisible(true);}public static void main( Stri ng[] args){new lmageDraw().init();}class DrawPa nel exte nds JPa nel{public void pain t(Graphics g){Graphics2D g2 = (Graphics2D) g;g2.clearRect(0, 0, AREA_WIDTH, AREA_HEIGHT);g2.setColor(color);g2.setStroke(stroke);g2.drawlmage(image , 0,0 , n ull);if(typeFlag == 2){line = new Lin e2D.FIoat(start_x, start_y, en d_x, en d_y);g2.draw(li ne);}if(typeFlag == 3){rect = new Recta ngle2D.FIoat(start_X, start_Y, width, height);g2.draw(rect);} if(typeFlag == 4){ellipse = new Ellipse2D.Float(start_X, start_Y, width, height);g2.draw(ellipse);} if(typeFlag ==5){ g2.setColor(Color.white); g2.fillRect(0 ,0 ,AREA_WIDTH AREA_HEIGHT);}}private void do_save_actio nPerformed(Actio nEve nt argO) { // TODO自动生成的方法存根JFileChooser chooser = new JFileChooser();chooser.setSelectedFile( newFile(imageFile.getName()));int option = chooser.showSaveDialog(null);if(opti on == JFileChooser.APPROVE_OPTION){File file = chooser.getSelectedFile();try {ImageIO.write(image, "jpg", file);} catch (IOExcepti on e) {// TODO自动生成的catch块e.pri ntStackTrace();}private void do_ope n_ actio nPerformed(Actio nEvent argO) throws IOExcepti on {// TODO自动生成的方法存根JFileChooser chooser = new JFileChooser();chooser.setFileFilter( newFileNameExte nsion Filter(" 图片文件1! I!' I!',jpg」peg , j if));chooser.setFileSelecti on Mode(JFileChooser.FI LES_ONL Y);int option = chooser.showOpenDialog(null);if(opti on == JFileChooser.APPROVE_OPTION){imageFile = chooser.getSelectedFile();Image sourceImage = ImageIO.read(imageFile);g2.drawlmage(sourcelmage, 0, 0, sourcelmage.getWidth( null),sourcelmage.getHeight (n ull), nu II);drawArea.repa in t();}}private void do_butt on ColorChoose_acti on Performed(Actio n Eve nt argO) {II TODO自动生成的方法存根JColorChooser chooser = new JCoIorChooser();color = chooser.showDialog(null,"请选取颜色", Color.black);butt on ShowColor.setBackgro un d(color);}private void do_mouseDragged(MouseEve nt e) {end_x = e.getX();end_y = e.get Y();width = Math.abs( end_x - start_x ); height = Math.abs( en d_y - start_y );if(end_x <= start_x && end_y <=start_y){ start_X = start_x - width;start_Y = start_y - heigh t;}if(end_x > start_x && end_y <start_y){ start_Y = start_y - heigh t;start_X = start_x;}if(end_x <= start_x && end_y >=start_y){ start_Y = start_y;start_X = start_x - width;}if(end_x >= start_x &&end_y >=start_y){ start_Y = start_y;start_X = start_x;if(typeFlag == 1){if (pre_x > 0 && pre_y > 0){line = new Lin e2D.FIoat(pre_x, pre_y, end_x, en d_y);g2.setColor(color);g2.setStroke(stroke);g2.draw(li ne);}pre_x = e.getX();pre_y = e.get Y();drawArea.repa in t();}else{drawArea.repa in t();}}private void do_mousePressed(MouseEve nt e1) {// TODO自动生成的方法存根width = 0;height = 0;start_x = end_x = pre_x = e1.getX(); start_y = end_y = pre_y = el.get Y();if(e ndFlag == 2){ g2.draw(l in e);}if(e ndFlag == 3){ g2.draw(rect);}if(e ndFlag == 4){ g2.draw(ellipse);}drawArea.repai nt(); }}。
java绘图程序
Java画图程序一、实验目的了解面向对象的系统分析和建模方法,掌握基于对象模型的程序设计方法,掌握java绘图程序设计相关类的用法以及掌握java绘图程序设计相关类的用法二、实验环境网络计算机,JDK1.4,文本编辑工具(可以用Windows自带的记事本,UltraEdit 或EditPlus等)。
三、实验内容设计一个简单的绘图程序,程序可以根据用户的请求绘制圆、矩形、直线等几何图形,并且可以移动这些图形。
要求建立这个画图程序的对象模型,集合图形的常用操作比如绘制、移动等以多态方法提供,并且绘制的图形对象保存在数组或者集合对象中。
四、实验方法和步骤1.设计绘图系统的域模型,抽取图元超类和矩形、圆等子类。
2.设计绘图系统界面类从Frame派生子类,利用Canvas作为画布类并实现绘图。
3.建立域类包和界面类包。
4.设计域类。
5.设计界面类,实现界面上按钮操作功能Java源代码如下:import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.event.*;import javax.imageio.ImageIO;import java.io.*;import java.awt.geom.*;import java.awt.image.*;import java.awt.font.*;public class Painter extends JFrame implements ActionListener {private Container c = getContentPane();private String menuBar[]={"文件(F)","编辑(E)","视图(V)","说明(H)"};private String menuItem[][]={{"新建(N)|78","打开(O)|79","保存(S)|83","另存为(A)","退出(X)|88"},{"撤消(U)|90","重复(R)|89","剪切(T)|87","复制(C)|68","粘贴(P)|85"},{"工具箱(T)|84","色块(C)|76","状态栏(S)","属性栏(M)"},};private JMenuItem jMenuItem[][]=new JMenuItem[4][5];private JMenu jMenu[];private JCheckBoxMenuItem jCheckBoxMenuItem[] = new JCheckBoxMenuItem[4];private String ButtonName[]={"直线","矩开","椭圆","圆角矩形","贝氏曲线","扇型","多边形","铅笔","橡皮擦","文字","选取"};private JToggleButton jToggleButton[];private ButtonGroup buttonGroup;private JPanel jPanel[]=new JPanel[5];//0內層,1繪圖區,2工具箱,3色塊,4屬性欄private JLabel jLabel[]=new JLabel[1];//狀態列private Stringtoolname[]={"img/tool1.gif","img/tool2.gif","img/tool3.gif","img/tool4.gif","im g/tool5.gif","img/tool8.gif","img/tool9.gif","img/tool7.gif","img/tool6.gif","i mg/tool10.gif","img/tool11.gif"};private Icon tool[]=new ImageIcon[11];private inti,j,show_x,show_y,drawMethod=7,draw_panel_width=700,draw_panel_height=500;private Paint color_border,color_inside;private SetPanel setPanel;private DrawPanel drawPanel;private UnderDrawPanel underDrawPanel;private ColorPanel colorPanel;private Stroke stroke;private Shape shape;private String isFilled;//Download:public Painter(){//設定JMenuBar,並產生JMenuItem、並設置快捷鍵JMenuBar bar = new JMenuBar();jMenu=new JMenu[menuBar.length];for(i=0;i<menuBar.length;i++){jMenu[i] = new JMenu(menuBar[i]);jMenu[i].setMnemonic(menuBar[i].split("\\(")[1].charAt(0));bar.add(jMenu[i]);}for(i=0;i<menuItem.length;i++){for(j=0;j<menuItem[i].length;j++){if(i==0 && j==4 || i==1 && j==2) jMenu[i].addSeparator();if(i!=2){jMenuItem[i][j] = new JMenuItem(menuItem[i][j].split("\\|")[0]);if(menuItem[i][j].split("\\|").length!=1)jMenuItem[i][j].setAccelerator(KeyStroke.getKeyStroke(Integer.parseInt(menu Item[i][j].split("\\|")[1]), ActionEvent.CTRL_MASK) );jMenuItem[i][j].addActionListener(this);jMenuItem[i][j].setMnemonic(menuItem[i][j].split("\\(")[1].charAt(0));jMenu[i].add(jMenuItem[i][j]);}else{jCheckBoxMenuItem[j] = new JCheckBoxMenuItem(menuItem[i][j].split("\\|")[0]);if(menuItem[i][j].split("\\|").length!=1)jCheckBoxMenuItem[j].setAccelerator(KeyStroke.getKeyStroke(Integer.parseInt (menuItem[i][j].split("\\|")[1]), ActionEvent.CTRL_MASK) );jCheckBoxMenuItem[j].addActionListener(this);jCheckBoxMenuItem[j].setMnemonic(menuItem[i][j].split("\\(")[1].charAt(0));jCheckBoxMenuItem[j].setSelected( true );jMenu[i].add(jCheckBoxMenuItem[j]);}}}this.setJMenuBar( bar );c.setLayout( new BorderLayout() );for(i=0;i<5;i++)jPanel[i]=new JPanel();jLabel[0]=new JLabel(" 狀態列");buttonGroup = new ButtonGroup();JToolBar jToolBar=new JToolBar("工具箱",JToolBar.VERTICAL);jToggleButton=new JToggleButton[ButtonName.length];for(i=0;i<ButtonName.length;i++){tool[i] = new ImageIcon(toolname[i]);jToggleButton[i] = new JToggleButton(tool[i]);jToggleButton[i].addActionListener( this );jToggleButton[i].setFocusable( false );buttonGroup.add(jToggleButton[i]);}jToolBar.add(jToggleButton[7]);jToolBar.add(jToggleButton[8]);jToolBar.add(jToggleButton[0]);jToolBar.add(jToggleButton[4]);jToolBar.add(jToggleButton[1]);jToolBar.add(jToggleButton[3]);jToolBar.add(jToggleButton[2]);jToolBar.add(jToggleButton[5]);jToolBar.add(jToggleButton[6]);jToolBar.add(jToggleButton[9]);jToolBar.add(jToggleButton[10]);jToggleButton[7].setSelected(true);jToolBar.setLayout( new GridLayout( 6, 2, 2, 2 ) );jPanel[2].add(jToolBar);jToolBar.setFloatable(false);//無法移動colorPanel=new ColorPanel();jPanel[3].setLayout(new FlowLayout(FlowLayout.LEFT));jPanel[3].add(colorPanel);drawPanel=new DrawPanel();underDrawPanel=new UnderDrawPanel();underDrawPanel.setLayout(null);underDrawPanel.add(drawPanel);drawPanel.setBounds(new Rectangle(2, 2, draw_panel_width, draw_panel_height));setPanel=new SetPanel();jPanel[4].add(setPanel);jPanel[0].setLayout( new BorderLayout() );jPanel[0].add(underDrawPanel,BorderLayout.CENTER);jPanel[0].add(jPanel[2],BorderLayout.WEST);jPanel[0].add(jPanel[3],BorderLayout.SOUTH);jPanel[0].add(jPanel[4],BorderLayout.EAST);jLabel[0].setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));underDrawPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERE D));underDrawPanel.setBackground(new Color(128,128,128));jPanel[3].setBorder(BorderFactory.createMatteBorder(1,0,0,0,newColor(172,168,153)));c.add(jPanel[0],BorderLayout.CENTER);c.add(jLabel[0],BorderLayout.SOUTH);setSize(draw_panel_width,draw_panel_height);setTitle("小画家");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);show();}public void save(){FileDialog fileDialog = new FileDialog( new Frame() , "请指定一个文件名", FileDialog.SAVE );fileDialog.show();if(fileDialog.getFile()==null) return;drawPanel.filename = fileDialog.getDirectory()+fileDialog.getFile();}public void actionPerformed( ActionEvent e ){for(i=0;i<ButtonName.length;i++){if(e.getSource()==jToggleButton[i]){drawMethod=i;if(drawMethod==5)setPanel.pie_add_ctrl();elsesetPanel.pie_remove_ctrl();if(drawMethod==7 || drawMethod==8)setPanel.pencil_add_ctrl();elsesetPanel.pencil_remove_ctrl();drawPanel.clear();drawPanel.repaint();jMenuItem[1][2].setEnabled(false);jMenuItem[1][3].setEnabled(false);}}if(e.getSource()==jMenuItem[1][0]){drawPanel.undo();}else if(e.getSource()==jMenuItem[1][1]){drawPanel.redo();}else if(e.getSource()==jMenuItem[1][2]){drawPanel.cut();}else if(e.getSource()==jMenuItem[1][3]){drawPanel.copy();}else if(e.getSource()==jMenuItem[1][4]){drawPanel.paste();}else if(e.getSource()==jMenuItem[0][0]){//開新檔案underDrawPanel.remove(drawPanel);drawPanel=null;drawPanel=new DrawPanel();underDrawPanel.add(drawPanel);drawPanel.setBounds(new Rectangle(2, 2, draw_panel_width, draw_panel_height));underDrawPanel.ctrl_area.setLocation(draw_panel_width+3,draw_panel_height+3 );underDrawPanel.ctrl_area2.setLocation(draw_panel_width+3,draw_panel_height/ 2+3);underDrawPanel.ctrl_area3.setLocation(draw_panel_width/2+3,draw_panel_heigh t+3);repaint();}else if(e.getSource()==jMenuItem[0][1]){//開啟舊檔FileDialog fileDialog = new FileDialog( new Frame() , "選擇一個圖檔", FileDialog.LOAD );fileDialog.show();if(fileDialog.getFile()==null) return;underDrawPanel.removeAll();drawPanel=null;drawPanel=new DrawPanel();underDrawPanel.add(drawPanel);drawPanel.setBounds(new Rectangle(2, 2, draw_panel_width, draw_panel_height));drawPanel.openfile(fileDialog.getDirectory()+fileDialog.getFile());}else if(e.getSource()==jMenuItem[0][2]){//儲存檔案if(drawPanel.filename==null){save();}else{try{int dotpos = stIndexOf('.');ImageIO.write(drawPanel.bufImg,drawPanel.filename.substring(dotpos + 1), new File(drawPanel.filename));}catch(IOException even) {JOptionPane.showMessageDialog(null, even.toString(),"無法儲存圖檔", JOptionPane.ERROR_MESSAGE);}}}else if(e.getSource()==jMenuItem[0][3]){//另存新檔save();try{int dotpos = stIndexOf('.');ImageIO.write(drawPanel.bufImg,drawPanel.filename.substring(dotpos + 1), new File(drawPanel.filename));}catch(IOException even) {JOptionPane.showMessageDialog(null, even.toString(),"無法儲存圖檔", JOptionPane.ERROR_MESSAGE);}}else if(e.getSource()==jMenuItem[0][4]){//離開System.exit(0);}for(i=0;i<2;i++){if(jCheckBoxMenuItem[i].isSelected())jPanel[i+2].setVisible( true );elsejPanel[i+2].setVisible( false );}if(jCheckBoxMenuItem[3].isSelected()){setPanel.setVisible( true );jPanel[4].setVisible( true );}else{setPanel.setVisible( false );jPanel[4].setVisible( false );}if(jCheckBoxMenuItem[2].isSelected())jLabel[0].setVisible( true );elsejLabel[0].setVisible( false );}public class UnderDrawPanel extends JPanel implements MouseListener, MouseMotionListener{public int x,y;float data[]={2};public JPanel ctrl_area=new JPanel(),ctrl_area2=new JPanel(),ctrl_area3=new JPanel();public UnderDrawPanel(){this.setLayout(null);this.add(ctrl_area);this.add(ctrl_area2);this.add(ctrl_area3);ctrl_area.setBounds(new Rectangle(draw_panel_width+3, draw_panel_height+3, 5, 5));ctrl_area.setBackground(new Color(0,0,0));ctrl_area2.setBounds(new Rectangle(draw_panel_width+3, draw_panel_height/2, 5, 5));ctrl_area2.setBackground(new Color(0,0,0));ctrl_area3.setBounds(new Rectangle(draw_panel_width/2, draw_panel_height+3, 5, 5));ctrl_area3.setBackground(new Color(0,0,0));ctrl_area.addMouseListener(this);ctrl_area.addMouseMotionListener(this);ctrl_area2.addMouseListener(this);ctrl_area2.addMouseMotionListener(this);ctrl_area3.addMouseListener(this);ctrl_area3.addMouseMotionListener(this);}public void mouseClicked(MouseEvent e){}public void mousePressed(MouseEvent e){}public void mouseReleased(MouseEvent e){draw_panel_width=x;draw_panel_height=y;ctrl_area.setLocation(draw_panel_width+3,draw_panel_height+3);ctrl_area2.setLocation(draw_panel_width+3,draw_panel_height/2+3);ctrl_area3.setLocation(draw_panel_width/2+3,draw_panel_height+3);drawPanel.setSize(x,y);drawPanel.resize();repaint();}public void mouseEntered(MouseEvent e){}public void mouseExited(MouseEvent e){}public void mouseDragged(MouseEvent e){if(e.getSource()==ctrl_area2){x = e.getX()+draw_panel_width;y = draw_panel_height;}else if(e.getSource()==ctrl_area3){x = draw_panel_width;y = e.getY()+draw_panel_height;}else{x = e.getX()+draw_panel_width;y = e.getY()+draw_panel_height;}repaint();jLabel[0].setText(x+","+y);}public void mouseMoved(MouseEvent e) {}public void paint(Graphics g) {Graphics2D g2d = (Graphics2D) g;super.paint(g2d);g2d.setPaint( new Color(128,128,128) );g2d.setStroke( new BasicStroke( 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 10, data, 0 ) );g2d.draw( new Rectangle2D.Double( -1, -1, x+3, y+3 ) );}}public class SetPanel extends JPanel implements ItemListener, ChangeListener, ActionListener{private JPanel jPanel_set1=new JPanel();private JPanel jPanel_set2=new JPanel();private JPanel temp0=new JPanel(new GridLayout(4,1)), temp1=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp2=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp3=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp4=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp5=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp6=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp7=new JPanel(new FlowLayout(FlowLayout.LEFT)), temp8=new JPanel(new GridLayout(3,1));public JCheckBox jCheckBox = new JCheckBox();private BufferedImage bufImg = new BufferedImage(50 ,50,BufferedImage.TYPE_3BYTE_BGR);private JLabel jlbImg=new JLabel();float data[]={20};JLabel pie[]=new JLabel[3];public int number=5;JSpinner lineWidthSelect = new JSpinner();JRadioButton style[] = new JRadioButton[ 5 ];ButtonGroup styleGroup = new ButtonGroup() ,pieGroup = new ButtonGroup();public SetPanel(){//產生版面//this.setLayout(null);this.add(jPanel_set1);jlbImg.setIcon(new ImageIcon(bufImg));jPanel_set1.setLayout(new FlowLayout());jPanel_set1.setBounds(new Rectangle(0, 0, 100, 160));jPanel_set1.setBorder( new TitledBorder(null, "边框",TitledBorder.LEFT, TitledBorder.TOP) );lineWidthSelect.setValue(new Integer(5));for(i=0;i<=1;i++){style[i] = new JRadioButton();styleGroup.add(style[i]);style[i].addActionListener(this);}style[0].setSelected( true );temp1.add(new JLabel("大小:"));temp1.add(lineWidthSelect);temp2.add(new JLabel("虛线:"));temp2.add(jCheckBox);temp3.add(new JLabel("圆角:"));temp3.add(style[0]);temp4.add(new JLabel("尖角:"));temp4.add(style[1]);temp0.add(temp1);temp0.add(temp2);temp0.add(temp3);temp0.add(temp4);jPanel_set1.add(temp0);lineWidthSelect.addChangeListener( this );jCheckBox.addItemListener( this );jPanel_set2.setBounds(new Rectangle(0, 170, 100, 130));jPanel_set2.setBorder( new TitledBorder(null, "扇型设定",TitledBorder.LEFT, TitledBorder.TOP) );for(i=2;i<=4;i++){style[i] = new JRadioButton();pieGroup.add(style[i]);style[i].addActionListener(this);}style[4].setSelected( true );pie[0] = new JLabel("弦状:");temp5.add(pie[0]);temp5.add(style[2]);pie[1] = new JLabel("开放:");temp6.add(pie[1]);temp6.add(style[3]);pie[2] = new JLabel("派状:");temp7.add(pie[2]);temp7.add(style[4]);temp8.add(temp5);temp8.add(temp6);temp8.add(temp7);temp8.setPreferredSize(new Dimension( 71 , 95 ));jPanel_set2.add(temp8);this.add(jPanel_set2);pie_remove_ctrl();stroke = new BasicStroke(5, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);}public void pencil_add_ctrl(){style[0].setSelected(true);style[1].setEnabled(false);jCheckBox.setSelected(false);jCheckBox.setEnabled(false);BasicStroke stroke2 = (BasicStroke) stroke;stroke = new BasicStroke(stroke2.getLineWidth(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);}public void pencil_remove_ctrl(){style[1].setEnabled(true);jCheckBox.setEnabled(true);}public void pie_add_ctrl(){pie[0].setEnabled(true);pie[1].setEnabled(true);pie[2].setEnabled(true);style[2].setEnabled(true);style[3].setEnabled(true);style[4].setEnabled(true);}public void pie_remove_ctrl(){pie[0].setEnabled(false);pie[1].setEnabled(false);pie[2].setEnabled(false);style[2].setEnabled(false);style[3].setEnabled(false);style[4].setEnabled(false);}public void actionPerformed( ActionEvent e ){BasicStroke stroke2 = (BasicStroke) stroke;if ( e.getSource() == style[0] )stroke = new BasicStroke( stroke2.getLineWidth(), BasicStroke.CAP_ROUND, stroke2.getLineJoin(), stroke2.getMiterLimit(), stroke2.getDashArray(), stroke2.getDashPhase() );else if ( e.getSource() == style[1] )stroke = new BasicStroke( stroke2.getLineWidth(), BasicStroke.CAP_BUTT, stroke2.getLineJoin(), stroke2.getMiterLimit(), stroke2.getDashArray(), stroke2.getDashPhase() );else if ( e.getSource() == style[2] )drawPanel.pie_shape=Arc2D.CHORD;else if ( e.getSource() == style[3] )drawPanel.pie_shape=Arc2D.OPEN;else if ( e.getSource() == style[4] )drawPanel.pie_shape=Arc2D.PIE;}public void stateChanged(ChangeEvent e){number = Integer.parseInt(lineWidthSelect.getValue().toString());if(number <= 0) {lineWidthSelect.setValue(new Integer(1));number = 1;}BasicStroke stroke2 = (BasicStroke) stroke;stroke = new BasicStroke( number, stroke2.getEndCap(), stroke2.getLineJoin(), stroke2.getMiterLimit(), stroke2.getDashArray(), stroke2.getDashPhase() );}public void itemStateChanged( ItemEvent e ){BasicStroke stroke2 = (BasicStroke) stroke;if ( e.getSource() == jCheckBox ){if ( e.getStateChange() == ItemEvent.SELECTED )stroke = new BasicStroke( stroke2.getLineWidth(), stroke2.getEndCap(), stroke2.getLineJoin(), 10, data, 0 );elsestroke = new BasicStroke( stroke2.getLineWidth(), stroke2.getEndCap(), stroke2.getLineJoin());}}public Dimension getPreferredSize(){return new Dimension( 100, 300 );}}public class Gradient extends JPanel{//漸層預覽用public Color G_color_left = new Color(255,255,255);public Color G_color_right = new Color(0,0,0);public Gradient(){repaint();}public void paint(Graphics g) {Graphics2D g2d = (Graphics2D) g;g2d.setPaint( new GradientPaint( 0, 0, G_color_left, 100, 0, G_color_right, true ) );g2d.fill( new Rectangle2D.Double( 0, 0, 100, 25 ) );}public Dimension getPreferredSize(){return new Dimension( 100, 25 );}}public class ColorPanel extends JPanel implements MouseListener,ActionListener{//調色盤classprivate JPanel jPanel_color0[]=new JPanel[5];private JPanel jPanel_color1[]=new JPanel[32];private JPanel jPanel_color2[]=new JPanel[32];private ImageIcon special_color[]= new ImageIcon[4];private BufferedImage bufImg = new BufferedImage(12 ,12,BufferedImage.TYPE_3BYTE_BGR) ,bufImg2 = new BufferedImage(12 ,12,BufferedImage.TYPE_3BYTE_BGR);private JLabel jlbImg=new JLabel() ,jlbImg2=new JLabel();private ImageIcon icon;private JDialog jDialog;private JButton ok, cancel,left,right;private Gradient center = new Gradient();private int rgb[][]={{0,255,128,192,128,255,128,255, 0, 0, 0, 0, 0, 0,128,255,128,255, 0, 0, 0,128, 0,128,128,255,128,255,255,255,255,255}, {0,255,128,192, 0, 0,128,255,128,255,128,255, 0, 0, 0, 0,128,255, 64,255,128,255, 64,128, 0, 0, 64,128,255,255,255,255},{0,255,128,192, 0, 0, 0, 0, 0, 0,128,255,128,255,128,255, 64,128, 64,128,255,255,128,255,255,128, 0, 64,255,255,255,255}};public ColorPanel(){//產生版面//addMouseListener( this );jlbImg.setIcon(new ImageIcon(bufImg));jlbImg2.setIcon(new ImageIcon(bufImg2));special_color[0] = new ImageIcon( "img/icon1.gif" );special_color[1] = new ImageIcon( "img/icon2.gif" );special_color[2] = new ImageIcon( "img/icon3.gif" );special_color[3] = new ImageIcon( "img/icon4.gif" );this.setLayout(null);color_border=new Color(0,0,0);color_inside=null;for(i=0;i<jPanel_color0.length;i++){jPanel_color0[i]=new JPanel();if(i<=2){jPanel_color0[i].setBorder(BorderFactory.createEtchedBorder(BevelBorder.RAI SED));jPanel_color0[i].setLayout(null);}else{jPanel_color0[i].setBackground(newColor(rgb[0][i-3],rgb[1][i-3],rgb[2][i-3]));jPanel_color0[i].setLayout(new GridLayout(1,1));jPanel_color0[i-2].add(jPanel_color0[i]);}}for(i=0;i<jPanel_color2.length;i++){jPanel_color2[i]=new JPanel();jPanel_color2[i].setLayout(new GridLayout(1,1));jPanel_color2[i].setBounds(new Rectangle(2, 2, 12, 12));jPanel_color2[i].setBackground(newColor(rgb[0][i],rgb[1][i],rgb[2][i]));if(i>=28)jPanel_color2[i].add(new JLabel(special_color[i-28]));}for(i=0;i<jPanel_color1.length;i++){jPanel_color1[i]=new JPanel();jPanel_color1[i].setLayout(null);jPanel_color1[i].add(jPanel_color2[i]);this.add(jPanel_color1[i]);if(i%2==0){jPanel_color1[i].setBounds(new Rectangle(32+i/2*16, 0, 16, 16));}else{jPanel_color1[i].setBounds(new Rectangle(32+i/2*16, 16, 16, 16));}jPanel_color1[i].setBorder(BorderFactory.createEtchedBorder(BevelBorder.RAI SED));}jPanel_color0[3].add(jlbImg);jPanel_color0[4].add(jlbImg2);Graphics2D g2d = bufImg2.createGraphics();g2d.setPaint( Color.white );g2d.fill( new Rectangle2D.Double( 0, 0, 12, 12 ) );g2d.setPaint( Color.red );g2d.draw( new Line2D.Double( 0, 0, 12, 12 ) );g2d.draw( new Line2D.Double( 11, 0, 0, 11 ) );repaint();this.add(jPanel_color0[1]);this.add(jPanel_color0[2]);this.add(jPanel_color0[0]);jPanel_color0[0].setBounds(new Rectangle(0, 0, 32, 32));jPanel_color0[1].setBounds(new Rectangle(4, 4, 16, 16));jPanel_color0[2].setBounds(new Rectangle(12,12,16, 16));jPanel_color0[3].setBounds(new Rectangle(2, 2, 12, 12));jPanel_color0[4].setBounds(new Rectangle(2, 2, 12, 12));jDialog = new JDialog(Painter.this, "請選擇兩種顏色做漸層", true);jDialog.getContentPane().setLayout(new FlowLayout());jDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE );jDialog.setSize(250, 110);JPanel temp = new JPanel(new GridLayout(2,1));JPanel up = new JPanel(new FlowLayout());JPanel down = new JPanel(new FlowLayout());ok = new JButton("確定");cancel = new JButton("取消");left = new JButton(" ");right = new JButton(" ");center.setBorder(BorderFactory.createEtchedBorder(BevelBorder.RAISED));up.add(left);up.add(center);up.add(right);down.add(ok);down.add(cancel);temp.add(up);temp.add(down);jDialog.getContentPane().add(temp);ok.addActionListener(this);cancel.addActionListener(this);left.addActionListener(this);right.addActionListener(this);}public void actionPerformed( ActionEvent e ){if(e.getSource() == left){center.G_color_left = JColorChooser.showDialog( Painter.this, "請選擇邊線顏色", center.G_color_left );center.repaint();}else if(e.getSource() == right){center.G_color_right = JColorChooser.showDialog( Painter.this, "請選擇邊線顏色", center.G_color_right );center.repaint();}else{jDialog.dispose();}}public Dimension getPreferredSize(){return new Dimension( 300, 32 );}public void mouseClicked( MouseEvent e ){}public void mousePressed( MouseEvent e ){Graphics2D g2d;if(e.getX()>=5 && e.getX()<=20 && e.getY()>=5 && e.getY()<=20){g2d = bufImg.createGraphics();color_border = JColorChooser.showDialog( Painter.this, "請選擇邊線顏色", (Color)color_border );g2d.setPaint(color_border);g2d.fill( new Rectangle2D.Double( 0, 0, 12, 12 ) );repaint();}else if(e.getX()>=13 && e.getX()<=28 && e.getY()>=13 && e.getY()<=28){ g2d = bufImg2.createGraphics();color_inside = JColorChooser.showDialog( Painter.this, "請選擇填充顏色", (Color)color_inside );g2d.setPaint(color_inside);g2d.fill( new Rectangle2D.Double( 0, 0, 12, 12 ) );repaint();}if(!(e.getX()>=32 && e.getX()<=288)) return;int choose=(e.getX()-32)/16*2+e.getY()/16;if(e.getButton()==1)//判斷填充邊框或填滿內部g2d = bufImg.createGraphics();elseg2d = bufImg2.createGraphics();if(choose==28){//填充無顏色g2d.setPaint( Color.white );g2d.fill( new Rectangle2D.Double( 0, 0, 12, 12 ) );g2d.setPaint( Color.red );g2d.draw( new Line2D.Double( 0, 0, 12, 12 ) );g2d.draw( new Line2D.Double( 11, 0, 0, 11 ) );repaint();if(e.getButton()==1)color_border=null;elsecolor_inside=null;}else if(choose==29){//填充漸層jDialog.show();g2d.setPaint( new GradientPaint( 0, 0, center.G_color_left, 12, 12, center.G_color_right, true ) );g2d.fill( new Rectangle2D.Double( 0, 0, 12, 12 ) );repaint();if(e.getButton()==1)color_border=new GradientPaint( 0, 0, center.G_color_left, 12, 12, center.G_color_right, true );elsecolor_inside=new GradientPaint( 0, 0, center.G_color_left, 12, 12, center.G_color_right, true );}else if(choose==30){//填充圖案FileDialog fileDialog = new FileDialog( new Frame() , "選擇一個圖檔", FileDialog.LOAD );//利用FileDialog抓取檔名fileDialog.show();//秀出視窗if(fileDialog.getFile()==null) return;//按取消的處理g2d.drawImage(special_color[2].getImage(), 0, 0,this);//把調色盤左方換成『圖片』icon = new ImageIcon(fileDialog.getDirectory()+fileDialog.getFile());//利用FileDialog傳進來的檔名讀取圖片BufferedImage bufferedImage = new BufferedImage(icon.getIconWidth(),icon.getIconHeight(),BufferedImage.TYPE_3BYTE _BGR);//創一張新的BufferedImage,為了要讀取讀進來的圖片長寬,以免有空白bufferedImage.createGraphics().drawImage(icon.getImage(),0,0,this);//把icon畫到BufferedImage上repaint();//重繪螢幕if(e.getButton()==1)//判斷邊線顏色或內部填滿色color_border=new TexturePaint(bufferedImage, new Rectangle( icon.getIconWidth(), icon.getIconHeight() ) );//把這張BufferedImage 設成TexturePaint來填滿elsecolor_inside=new TexturePaint(bufferedImage, new Rectangle( icon.getIconWidth(), icon.getIconHeight() ) );}else if(choose==31){//填充文字String text=JOptionPane.showInputDialog("請輸入文字","文字");//輸入文字if(text==null) return;//按取消時的處理Color FontColor=new Color(0,0,0);//給這個字顏色FontColor = JColorChooser.showDialog( Painter.this, "請選擇一個顏色當文字顏色", FontColor );//讓使用者選擇顏色g2d.drawImage(special_color[3].getImage(), 0, 0,this);//把調色盤左方換成『字』BufferedImage bufferedImage = new BufferedImage(draw_panel_width,draw_panel_height,BufferedImage.TYPE_3BYTE_BGR); //創一張新的BufferedImageGraphics2D g2d_bufferedImage = bufferedImage.createGraphics();//把Graphics拿出來畫FontRenderContext frc = g2d_bufferedImage.getFontRenderContext();//讀Graphics中的FontFont f = new Font("新細明體",Font.BOLD,10);//新FontTextLayout tl = new TextLayout(text, f, frc);//創新的TextLayout,並利用f(Font)跟畫至於frc(FontRenderContext)int sw = (int) (tl.getBounds().getWidth()+tl.getCharacterCount());//計算TextLayout的長int sh = (int) (tl.getBounds().getHeight()+3);//計算TextLayout 的高bufferedImage = new BufferedImage(sw,sh,BufferedImage.TYPE_3BYTE_BGR);//再創一張新的BufferedImage,這裡利用相同指標指向不同記憶體g2d_bufferedImage = bufferedImage.createGraphics();//拿出Graphics來畫,前一張BufferedImage只是為了計算文字長度與高度,這樣才能完整填滿g2d_bufferedImage.setPaint(Color.WHITE);//設定顏色為白色g2d_bufferedImage.fill(new Rectangle(0,0,sw,sh));//畫一個填滿白色矩型g2d_bufferedImage.setPaint(FontColor);//設定顏色為之前選擇文字顏色g2d_bufferedImage.drawString(text,0,10);//畫一個String於BufferedImage上repaint();//更新畫面if(e.getButton()==1)//判斷邊線顏色或內部填滿色color_border=new TexturePaint(bufferedImage, new Rectangle(sw,sh) );//把這張BufferedImage設成TexturePaint來填滿elsecolor_inside=new TexturePaint(bufferedImage, new Rectangle(sw,sh) );}else{//填充一般色g2d.setPaint(newColor(rgb[0][choose],rgb[1][choose],rgb[2][choose]));g2d.fill( new Rectangle2D.Double( 0, 0, 12, 12 ) );repaint();if(e.getButton()==1)color_border=newColor(rgb[0][choose],rgb[1][choose],rgb[2][choose]);elsecolor_inside=newColor(rgb[0][choose],rgb[1][choose],rgb[2][choose]);}}public void mouseReleased( MouseEvent e ){}public void mouseEntered( MouseEvent e ){}public void mouseExited( MouseEvent e ){}}public class DrawPanel extends JPanel implements MouseListener, MouseMotionListener, ItemListener, ActionListener, ChangeListener{//中央畫布public BufferedImage bufImg;//記錄最新畫面,並在此上作畫private BufferedImage bufImg_data[];//記錄所有畫出圖面,索引值越大越新,最大為最新private BufferedImage bufImg_cut;private ImageIcon img;private JLabel jlbImg;private int x1=-1,y1=-1,x2,y2,count,redo_lim,press,temp_x1,temp_y1,temp_x2,temp_y2,temp_x3, temp_y3,step,step_chk,step_arc,step_chk_arc,chk,first,click,cut;private Arc2D.Double arc2D = new Arc2D.Double();//扇型private Line2D.Double line2D = new Line2D.Double();//直線private Ellipse2D.Double ellipse2D = new Ellipse2D.Double();//橢圓private Rectangle2D.Double rectangle2D = new Rectangle2D.Double();//矩型private CubicCurve2D.Double cubicCurve2D = new CubicCurve2D.Double();//貝氏曲線private RoundRectangle2D.Double roundRectangle2D = new RoundRectangle2D.Double();//圓角矩型private Polygon polygon;//多邊型private float data[]={5};private Rectangle2D.Double rectangle2D_select = new Rectangle2D.Double();//矩型private Ellipse2D.Double ellipse2D_pan = new Ellipse2D.Double();private BasicStroke basicStroke_pen = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);private BasicStroke basicStroke_select = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER,10, data, 0);private double center_point_x;private double center_point_y;private double start;private double end;public String filename;private JTextField textField_font = new JTextField("Fixedsys",16), textField_word = new JTextField("JAVA",16);private int size=100;private JSpinner fontsize = new JSpinner();private JDialog jDialog;。
Java画图软件设计报告
佛山科学技术学院《可视化编程技术》课程设计报告画图软件设计学生姓名:***学号:**********年级专业:11级教育技术学2班指导老师:***学院:教育科学学院广东★佛山提交日期:2013年6月目录1. 前言 (2)2.概要设计 (3)2.1 开发环境 (3)2.2 画图软件功能 (3)2.3 界面设计 (3)2.4 类的框架结构图 (4)3. 详细设计 (4)3.1 使用的JAVA类的说明 (4)3.2 类的主要方法 (5)3.2.1 颜色选择器 (5)3.2.2 控制画笔样式 (5)3.2.3 选取颜色按钮的监听件类 (6)3.2.4 设计总体认识 (6)3.2.5 程序流程图 (7)4. 运行结果 (7)5. 测试分析 (8)5.1 程序运行情况 (8)6. 源程序 (8)参考文献 (14)设计总结 (14)摘要:该程序是一个图形界面的简单的java画图软件,具有良好的界面,使用人员能快捷简单地进行操作。
该画图软件操作较为简单,只需要一直按着左键就能根据你鼠标移动的方面,画出你想要的图案。
你也可以选择你自己想到的颜色和画笔的粗细。
而且可以显示你当前的画笔的状态。
界面为灰白对称。
是一个非常简单的作图工具,让人能轻松上手。
关键字:java,画图类,方法,事件1 前言随着科学技术的不断发展,计算机已经成为我们工作学习和生活中不可缺少的工具。
文本编辑器是个人计算机最司空见惯的应用程序了,在学习了Java语言之后,我决定使用Java语言编写一个简单的画图工具,可以实现简单的画图作图功能,满足日常基本的工作学习和娱乐需要。
Java是由Sun公司开发的新一代纯面向对象的网络编程语言。
其目标是建立一种在任意种机器、任一种操作系统的网络环境中运行的软件,实行所谓的“程序写一次,到处运行”的目标。
正因为如此,Java已成为当今Internet上最流行、最受欢迎的一种程序开发语言。
Java开发小组把Java按特性分为基本版、移动版、企业版,每个版本有一个软件开发包。
java实验报告
java实验报告Java实验报告实验名称:Java图形界面编程实验对象:Java初学者实验目的:通过实际操作掌握Java图形界面编程的基本知识和技巧实验过程:1. 实验准备:安装Java JDK开发环境,并准备好IDE工具(如Eclipse或IntelliJ IDEA)2. 创建工程:打开IDE工具,新建一个Java工程,并指定工程名和保存路径3. 创建界面:在工程上新建一个Java类,命名为"MainUI"4. 设计界面:在"MainUI"类中使用Swing或JavaFX等GUI库,设计界面布局和组件5. 添加事件监听:在"MainUI"类中添加事件监听器,使组件与逻辑代码进行关联6. 编写逻辑代码:在"MainUI"类中编写逻辑代码,实现界面交互和功能实现7. 编译运行:将工程编译成可执行文件,并运行程序,查看界面效果和功能是否符合预期8. 调试修复:根据实际运行情况,对代码进行调试和修复,确保程序的稳定性和正确性9. 测试验证:使用不同输入数据对程序进行测试,验证程序的鲁棒性和准确性10. 总结反思:对实验过程进行总结和反思,提出改进和优化的建议实验结果:通过实验,我成功创建了一个简单的Java图形界面程序,并实现了基本的交互和功能。
在界面设计方面,我使用了Swing库进行布局和组件的添加,通过事件监听器实现了按钮点击和文本框输入的监听。
在逻辑代码方面,我实现了简单的计算器功能,能够进行加减乘除等基本运算。
通过测试验证,程序运行稳定,结果准确。
实验心得:通过这次实验,我对Java图形界面编程有了更深入的了解和掌握。
我学会了使用Swing或JavaFX等库进行界面设计,以及如何添加事件监听器和编写逻辑代码。
通过实际操作,我发现编写图形界面程序相对于命令行程序更加复杂,需要考虑到用户的交互和界面布局,还需要注意代码的可读性和可维护性。
JAVA绘图实验报告
南京工程学院 实 验 报 告 课程名称 java基础 实验项目名称 图形用户界面设计 实验学生班级 实验学生姓名 学 号 同组学生姓名 无 实验时间 2012年11月 实验地点 实验成绩评定 指导教师签字 年 月 日一、实验目的和要求1.目的:掌握java awt及swing组件的使用方法,包括窗口、框架、对话框、布局方式、面板、文本编辑器、按钮、组合框等,合理利用委托事件处理模型,掌握不同组件,不同事件的事件处理方法,设计出能够响应事件的java图形用户界面。
2.要求:设计图形用户界面,事件处理,异常处理并弹出对话框,提示重新输入信息。
二、实验题目 验证哥德巴赫猜想,添加图形用户界面三、实验方法与步骤(需求分析、算法设计思路、流程图等)1.添加图形用户界面 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class gdbh extends frame implements actionlistener //窗口框架响应单击事件,利用awt组件设计框架 {private button button; //按钮 private textfield text1; //文本行 private textarea text2; //文本区 public gdbh() {super(验证哥德巴赫猜想); //设置框架窗口标题 this.setbounds(450, 200, 350, 400); //设置框架的位置和尺寸 this.setresizable(false); // 设置框架大小不可改变 this.setbackground(color.lightgray); //设置窗口背景颜色 this.setlayout(new flowlayout()); // 默认窗口流布局 中对齐 this.add(new label(输入一个整数)); text1=new textfield(,20); this.add(text1); button=new button(验证哥德巴赫猜想); this.add(button); button.addactionlistener(this); //为按钮注册单击事件监听器,委托当前对象处理事件 this.setlayout(new flowlayout()); //默认中对齐 text2=new textarea(20,25); text2.seteditable(false); this.add(text2); this.setvisible(true); //设置组件可见 this.addwindowlistener(new winclose()); // 为框架注册窗口事件监听器,委托winclose对象处理事件 }2.实现单击事件和窗口事件监听器接口 public void actionperformed(actionevent e) //单击事件处理方法,实现actionlistener接口 {string str =text1.gettext(); //获得文本行的字符串try {long num = long.parselong(str); // 将字符串转化成长整形text2.settext(yz(num)); }catch(numberformatexception n) {joptionpane.showmessagedialog(this, \+str+\字符串不能转换成整数,请重新输入!!); return; }}class winclose implements windowlistener //实现窗口事件监听器接口 {public void windowclosing(windowevent e) // 窗口关闭事件处理方法 {system.exit(0); //程序运行结束 } public void windowopened(windowevent e) {} public void windowclosed(windowevent e) {} public void windowiconified(windowevent e) {} public void windowdeiconified(windowevent e) {} public void windowactivated(windowevent e) {} public void windowdeactivated(windowevent e) {} }3.异常处理 若文本行中的字符串不能转化成长整形,将弹出对话框“字符串不能转换成整数,请重新输入!!;另外如果所输入的整数为小于等于2或大于2小于等于5 也会弹出一个对话框“输入错误!必须是大于2的偶数或大于5的奇数!!”(该窗口代码设置在yz()函数中)。
《Java程序设计》实验报告 --实验3
else if(e.getSource()==buttontwo){//按键2操作
tf.setText(tf.getText()+"2");
flag1=Double.parseDouble(tf.getText());
}
else if(e.getSource()==buttonthree){//按键3操作
buttondevision=new JButton("/");
buttonsin=new JButton("sin");
buttontozero=new JButton(">0");
paneleast.setLayout(new GridLayout(3,1));//设置西边的布局为3行1列
//将操作按钮"+""-""*""/""sin"">0"添加到西边的面板中
JButton buttonplus,buttonminus,buttonmultiple,buttondevision,
buttonsin,buttontozero;//新建按钮"+""-""*""/""sin"和归零按钮
JButton buttonone,buttontwo,buttonthree,buttonfour,buttonfive,buttonsix,
panelcenter.add(buttonthree);
panelcenter.add(buttonfour);
panelcenter.add(buttonfive);
java绘图程序
package绘图程序;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.*;class DrawFigure extends JFrame implementsMouseListener,MouseMotionListener,AdjustmentListener,ItemListener{private static final long serialVersionUID = 1L;//serialVersionUID 用来表明类的不同版本间的兼容性具体数值可以自己修改JPanel p1 = new JPanel();JPanel p2 = new JPanel();JPanel top = new JPanel();JPanel bottom = new JPanel();ButtonGroup g = new ButtonGroup();JRadioButton op1 = new JRadioButton ("画",true);JRadioButton op2 = new JRadioButton ("直线" ,false);JRadioButton op3 = new JRadioButton ("圆",false);JRadioButton op4 = new JRadioButton ("矩形",false);JRadioButton op5 = new JRadioButton ("橡皮擦",false);JCheckBox c1 = new JCheckBox("填充");Color c = Color.black;JTextArea tt=new JTextArea(2,3);int f=1;int sx,sy,x,y;boolean fill=false;boolean flag=false;JScrollBar r1=new JScrollBar(JScrollBar.HORIZONTAL,0,4,0,255);JScrollBar g1=new JScrollBar(JScrollBar.HORIZONTAL,0,4,0,255);JScrollBar b1=new JScrollBar(JScrollBar.HORIZONTAL,0,4,0,255);public DrawFigure(){getContentPane().setLayout(new BorderLayout());top.setOpaque(true);top.setBackground(Color.white);tt.setBackground(Color.black);p1.setLayout(new FlowLayout());p1.setBackground(Color.lightGray);p2.setLayout(new GridLayout(3,1));p2.setPreferredSize(new Dimension(150,150));p2.add(r1); p2.add(g1); p2.add(b1);tt.setEditable(false);g.add(op1); g.add(op2); g.add(op3); g.add(op4); g.add(op5);p1.add(op1); p1.add(op2); p1.add(op3); p1.add(op4); p1.add(op5); p1.add(c1); p1.add(tt);bottom.add(p1); bottom.add(p2);c1.addItemListener(this);r1.addAdjustmentListener(this);g1.addAdjustmentListener(this);b1.addAdjustmentListener(this);op1.addItemListener(this);op2.addItemListener(this);op3.addItemListener(this);op4.addItemListener(this);top.addMouseListener(this);top.addMouseMotionListener(this);getContentPane().add(top,"Center");getContentPane().add(bottom,"South");this.setTitle("绘图程序09商务2班【第3组制作】");setSize(500,300);setVisible(true);}public void mousePressed(MouseEvent e){flag=false;sx=e.getX(); sy=e.getY();}public void mouseReleased(MouseEvent e){int x0, y0;Graphics g=top.getGraphics();switch(f){case 2:g.setXORMode(Color.white);g.drawLine(sx,sy,x,y);x=e.getX(); y=e.getY();g.setColor(c);g.setPaintMode();g.drawLine(sx, sy, x, y);break;case 3:case 4:g.setXORMode(Color.white);x0=x>sx?sx:x; y0=y>sy?sy:y;if(! fill){if(f==3)g.drawOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.drawRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}else{if(f==3)g.fillOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.fillRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}g.setPaintMode();x=e.getX(); y=e.getY();x0=x>sx?sx:x; y0=y>sy?sy:y;g.setColor(c);if(! fill){if(f==3)g.drawOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.drawRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}else{if(f==3)g.fillOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.fillRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}break;}}public void mouseEntered(MouseEvent e){}public void mouseExited (MouseEvent e){}public void mouseClicked(MouseEvent e){}public void mouseMoved (MouseEvent e){}public void mouseDragged(MouseEvent e){int x0,y0;Graphics g=top.getGraphics();switch(f){case 1:x=e.getX(); y=e.getY();g.setColor(c);g.setPaintMode();g.drawLine(sx, sy, x, y);sx=x; sy=y;break;case 2:if(!flag){x=e.getX(); y=e.getY();g.setXORMode(Color.white);g.drawLine(sx,sy,x,y);flag=true;}else{g.setXORMode(Color.white);g.drawLine(sx,sy,x,y);x=e.getX(); y=e.getY();g.setXORMode(Color.white);g.drawLine(sx,sy,x,y);}break;case 3:case 4:if(!flag){x=e.getX(); y=e.getY();x0=x>sx?sx:x; y0=y>sy?sy:y;g.setXORMode(Color.white);if(! fill){if(f==3)g.drawOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.drawRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}else{if(f==3)g.fillOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.fillRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}flag=true;}else{g.setXORMode(Color.white);x0=x>sx?sx:x; y0=y>sy?sy:y;if(! fill){if(f==3)g.drawOval(x0, y0, Math.abs(x-sx),Math.abs(y-sy));elseg.drawRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}else{if(f==3)g.fillOval(x0, y0, Math.abs(x-sx),Math.abs(y-sy));elseg.fillRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}x=e.getX(); y=e.getY();x0=x>sx?sx:x; y0=y>sy?sy:y;if(! fill){if(f==3)g.drawOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.drawRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}else{if(f==3)g.fillOval(x0, y0, Math.abs(x-sx), Math.abs(y-sy));elseg.fillRect(x0, y0, Math.abs(x-sx), Math.abs(y-sy));}}break;}}public void actionPerformed(ActionEvent e){f=Integer.parseInt(e.getActionCommand());}public void adjustmentValueChanged(AdjustmentEvent e) {c=new Color(r1.getValue(),g1.getValue(),b1.getValue());tt.setBackground(c);}public void itemStateChanged(ItemEvent e){if(e.getItemSelectable()instanceof JCheckBox){JCheckBox temp=(JCheckBox)e.getItemSelectable();fill=temp.isSelected();}else{JRadioButton temp =(JRadioButton)e.getItemSelectable();if(temp==op1)f=1;else if(temp==op2)f=2;else if(temp==op3)f=3;else if(temp==op4)f=4;}}public static void main (String args[]){JFrame.setDefaultLookAndFeelDecorated(true);Font font=new Font("JFrame",Font.PLAIN,14);Enumeration keys =UIManager.getLookAndFeelDefaults().keys();while(keys.hasMoreElements()){Object key=keys.nextElement();if(UIManager.get(key)instanceof Font)UIManager.put(key, font);}DrawFigure mainFrame=new DrawFigure();}}。
简单的绘图程序实验报告
面向对象程序设计实训(基于MFC程序设计)题目: 简单的绘图程序院系专业:姓名:学号:同组其他学生(学号):简单绘图程序说明1、功能分析目前这个软件的主要功能有如下:1、画直线:通过OnLine()函数实现。
2、画矩形:通过OnRectangle()函数实现。
3、画圆角矩形:通过OnRoundrect()函数实现。
4、画椭圆:通过OnEllipse()函数实现。
5、铅笔工具:可以画任意线条。
通过直接在OnMouseMove(UINT nFlags, CPointpoint)函数里面添加代码实现。
6、右键弹出菜单:可以在客户中点击鼠标右键,快速选择常用菜单。
通过OnContextMenu函数实现。
7、状态栏显示鼠标移动的坐标:在程序的右下角显示,通过调用setWidnowText和GetParent()实现。
8、画图颜色选择:可以画任何颜色的线条,通过OnColor()函数实现。
9、线条类型及线宽的设置:可以将画出的线条设置成实线、虚线、点线、点划线,双点划线,还可以设置线条的粗细,,通过实例这一功能立刻显示所选择线条的粗细及线型。
通过新建CLineSettingDlg类,其中OnSelchangeLineStyle()函数实现线型的改变,OnChangeEditLineWidth()函数实现线宽的改变。
再在CDrawView类中调用OnLineSetting()函数实现画笔的对话框,CLineSettingDlg类中的OnPaint()函数是实现示例功能的。
10、窗口的重绘时不擦除原来的内容:新建CShape类用来保存线条的颜色,线宽,填充色等属性,在窗口大小发生变化时有OnDraw(CDC* pDC)函数进行重绘工作,重绘中调用了各个绘图函数的Draw(CDC *pDC)函数。
11、所绘图形的保存于读取,通过Serialize(CArchive &ar)函数进行序列化操作,将所绘图形的信息通过文件的形式保存起来。
用java实现的一个简单的画板程序
用java实现的一个简单的画板程序一个实现简单画板功能的java程序,可以画直线,长方形,椭圆,曲线。
主类import java.awt.Color;import javax.swing.*;public class painter {public static void main(String [] args){JPanel jpl = new Board();JFrame painter =new JFrame();painter.add(jpl);painter.setBackground(Color.WHITE);painter.setTitle("Painter");painter.setSize(400,200);painter.setLocationRelativeTo(null);painter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);painter.setVisible(true);}}加了选择事件的画板import java.awt.*;import javax.swing.*;import java.awt.event.*;@SuppressWarnings("serial")public class Choose extends Board{JRadioButton jrb1=new JRadioButton("Line");JRadioButton jrb2=new JRadioButton("Rectangle");JRadioButton jrb3=new JRadioButton("Oval");JRadioButton jrb4=new JRadioButton("Curve");JButton jbt = new JButton("Clear");public Choose(){JPanel jp1=new JPanel();jp1.setLayout(new GridLayout(5,1,5,5));jp1.add(jrb1);jp1.add(jrb2);jp1.add(jrb3);jp1.add(jrb4);jp1.add(jbt);add(jp1);ButtonGroup group = new ButtonGroup();group.add(jrb1);group.add(jrb2);group.add(jrb3);group.add(jrb4);ActionListener chooseListener = new chooseListener(); MouseListener clearListener = new clearListener();jrb1.addActionListener(chooseListener);jrb2.addActionListener(chooseListener);jrb3.addActionListener(chooseListener);jrb4.addActionListener(chooseListener);jbt.addMouseListener(clearListener);}class chooseListener implements ActionListener{ public void actionPerformed(ActionEvent e) {if(e.getSource()==jrb1){drawLine();System.out.println("line");}else if(e.getSource()==jrb2){drawRectangle();System.out.println("rec");}else if(e.getSource()==jrb3){drawOval();System.out.println("oval");}else if(e.getSource()==jrb4){drawCurve();System.out.println("curve");}}}class clearListener extends MouseAdapter{public void mouseClicked(MouseEvent e){ drawClear();}}}画板import java.awt.*;import java.awt.event.*;import java.awt.image.BufferedImage;import java.awt.image.ImageProducer;import javax.swing.*;@SuppressWarnings("serial")public class Board extends JPanel{ JRadioButton jrb1=new JRadioButton("Line"); JRadioButton jrb2=new JRadioButton("Rectangle"); JRadioButton jrb3=new JRadioButton("Oval");JRadioButton jrb4=new JRadioButton("Curve");JButton jbt = new JButton("Clear");BufferedImage bi=new BufferedImage(500,500,BufferedImage.TYPE_INT_RGB);;int x=-1;int y=-1;int [] location=new int[4];int mode=0;boolean ifNotCurveClicked=false;boolean ifCurveClicked=false;public Board(){setLayout(new BorderLayout());JPanel jp1=new JPanel();jp1.setLayout(new GridLayout(5,1,5,5));jp1.add(jrb1);jp1.add(jrb2);jp1.add(jrb3);jp1.add(jrb4);jp1.add(jbt);add(jp1,BorderLayout.WEST);ButtonGroup group = new ButtonGroup();group.add(jrb1);group.add(jrb2);group.add(jrb3);group.add(jrb4);ActionListener chooseListener = new chooseListener();MouseListener clearListener = new clearListener();jrb1.addActionListener(chooseListener);jrb2.addActionListener(chooseListener);jrb3.addActionListener(chooseListener);jrb4.addActionListener(chooseListener); jbt.addMouseListener(clearListener);}public void drawLine(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ location[0]=e.getX();location[1]=e.getY();}public void mouseReleased(MouseEvent e){ if(!ifCurveClicked){location[2]=e.getX();location[3]=e.getY();mode=1;repaint();}}});}public void drawRectangle(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ location[0]=e.getX();location[1]=e.getY();}public void mouseReleased(MouseEvent e){ if(!ifCurveClicked){location[2]=e.getX();location[3]=e.getY();mode=2;repaint();}}});}public void drawOval(){ addMouseListener(new MouseAdapter(){ public void mousePressed(MouseEvent e){ location[0]=e.getX();location[1]=e.getY();}public void mouseReleased(MouseEvent e){if(!ifCurveClicked){location[2]=e.getX();location[3]=e.getY();mode=3;repaint();}}});}public void drawCurve(){ addMouseMotionListener(new MouseAdapter(){ public void mouseDragged(MouseEvent e){if(!ifNotCurveClicked){x=e.getX();y=e.getY();mode=4;repaint();}}});}public void drawClear(){mode=5;repaint();}protected void paintComponent(Graphics g){switch(mode){case(1):g.drawLine(location[0],location[1],location[2],location[3]);break;case(2):if(location[0]<=location[2]&&location[1]<location[3])<p="">g.drawRect(location[0],location[1],location[2]-location[0],location[3]-location[1]);else if(location[0]<=location[2]&&location[1]>=location[3])g.drawRect(location[0],location[3],location[2]-location[0],location[1]-location[3]);else if(location[0]>location[2]&&location[1]<=location[3])g.drawRect(location[2],location[1],location[0]-location[2],location[3]-location[1]);elseg.drawRect(location[2],location[3],location[0]-location[2],location[1]-location[3]);break;case(3):if(location[0]<=location[2]&&location[1]<location[3])<p="">g.drawOval(location[0],location[1],location[2]-location[0],location[3]-location[1]);else if(location[0]<=location[2]&&location[1]>=location[3])g.drawOval(location[0],location[3],location[2]-location[0],location[1]-location[3]);else if(location[0]>location[2]&&location[1]<=location[3])g.drawOval(location[2],location[1],location[0]-location[2],location[3]-location[1]);elseg.drawOval(location[2],location[3],location[0]-location[2],location[1]-location[3]);break;case(4):g.fillOval(x,y,2,2);break;case(5):setBackground(Color.WHITE);super.paintComponent(g);break;}}class chooseListener implements ActionListener{public void actionPerformed(ActionEvent e) {if(e.getSource()==jrb1){ifNotCurveClicked=true;ifCurveClicked=false;drawLine();}else if(e.getSource()==jrb2){ifNotCurveClicked=true;ifCurveClicked=false;drawRectangle();}else if(e.getSource()==jrb3){ ifNotCurveClicked=true; ifCurveClicked=false;drawOval();}else if(e.getSource()==jrb4){ ifNotCurveClicked=false; ifCurveClicked=true;drawCurve();}}}class clearListener extends MouseAdapter{ public void mouseClicked(MouseEvent e){ drawClear();}}}</location[3])<></location[3])<>。
java设计模式实验报告
设计模式实验报告学院:学院专业:班姓名:学号:指导教师:一.实例实例:简单工厂模式使用简单工厂模式设计一个可以创建不同几何形状(圆形、方形和三角形等)的绘图工具,每个几何图形都要有绘制draw()和擦除erase()两个方法,要求在绘制不支持的几何图形时,提示一个Unsupportedshapeexception.要求真正做出来,不要使用system.out.println。
1.UML图:2.源代码graph.javapackage simplefactory2;import java.awt.Graphics;public interface graph { void draw(Graphics g); void erase(Graphics g); } circle.javapackage simplefactory2;import java.awt.Graphics;public class circle implements graph{@Overridepublic void draw(Graphics g) { g.drawOval(20, 60, 60, 60); }@Overridepublic void erase(Graphics g) { g.clearRect(18, 55, 63, 68); }}rectangle.javapackage simplefactory2;import java.awt.Graphics;public class rectangle implements graph{@Overridepublic void draw(Graphics g) {g.drawRect(160, 60, 60, 60);}@Overridepublic void erase(Graphics g) {g.clearRect(159, 58, 66, 66);}}triangle.javapackage simplefactory2;import java.awt.Graphics;public class triangle implements graph{@Overridepublic void draw(Graphics g) {int[]xPoints={80,120,150}; int[]yPoints={70,120,70}; int nPoints=3;g.drawPolygon(xPoints, yPoints, nPoints); }@Overridepublic void erase(Graphics g) { g.clearRect(81, 70, 70, 60); }} geometryfctory.javapackage simplefactory2;public class geometryfctory {static graph renshow(String type) throws Exception{if("circle".equals(type)){ return new circle();}else if("triangle".equals(type)){ return new triangle();}else if("rectangle".equals(type)){ return new rectangle();}else{throw new Exception("Unsupportedshapeexception");}}} NewJFrame.javapackage simplefactory2;import java.util.logging.Level;import java.util.logging.Logger;public class NewJFrame extends javax.swing.JFrame {public NewJFrame() {initComponents();}@SuppressWarnings("unchecked")// <editor-fold defaultstate="collapsed" desc="Generated Code">private void initComponents() {jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton();jButton3 = new javax.swing.JButton() ; jButton4 = new javax.swing.JButton();jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton();jButton7 = new javax.swing.JButton();jTextField1 = new javax.swing.JTextField();jTextField2 = new javax.swing.JTextField();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);jButton1.setText("circle");jButton1.addMouseListener(new java.awt.event.MouseAdapter() {public void mouseClicked(java.awt.event.MouseEvent evt) {jButton1MouseClicked(evt); } });jButton1.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton1ActionPerformed(evt); } });jButton2.setText("triangle");jButton2.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton2ActionPerformed(evt); } });jButton3.setText("rectangle");jButton3.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton3ActionPerformed(evt); }});jButton4.setText("其他");jButton4.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton4ActionPerformed(evt); }});jButton5.setText("circle");jButton5.addMouseListener(new java.awt.event.MouseAdapter() {public void mouseClicked(java.awt.event.MouseEvent evt) { jButton5MouseClicked(evt); }});jButton5.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton5ActionPerformed(evt); }});jButton6.setText("triangle");jButton6.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton6ActionPerformed(evt); }});jButton7.setText("rectangle");jButton7.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {jButton7ActionPerformed(evt); }});jTextField1.setText("画图"); jTextField2.setText("檫除");javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(jButton1).addPreferredGap(ponentPlacement.RELATED).addComponent(jButton2).addPreferredGap(ponentPlacement.RELATED).addComponent(jButton3).addGap(18, 18, 18).addComponent(jButton4)).addGroup(layout.createSequentialGroup().addComponent(jButton5).addPreferredGap(ponentPlacement.RELATED).addComponent(jButton6).addPreferredGap(ponentPlacement.RELATED).addComponent(jButton7))).addGap(18, 18, 18).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false).addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 40, Short.MAX_VALUE).addComponent(jTextField1)) .addGap(0, 20, Short.MAX_VALUE)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap(173, Short.MAX_VALUE).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton1) .addComponent(jButton2).addComponent(jButton3) .addComponent(jButton4).addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addPreferredGap(ponentPlacement.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton5) .addComponent(jButton6).addComponent(jButton7).addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)).addGap(75, 75, 75))); pack();} private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {graph x = null;try {x = geometryfctory.renshow("circle");}catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); }x.draw(this.getGraphics()); }private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { graph z = null; try {y = geometryfctory.renshow("triangle");}catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); }y.draw(this.getGraphics());}private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {try {z = geometryfctory.renshow("rectangle");} catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); }z.draw(this.getGraphics());}private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { graph z = null;try {z = geometryfctory.renshow("aa");} catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); }z.draw(this.getGraphics()); }private void jButton5MouseClicked(java.awt.event.MouseEvent evt) { graph x = null;try {x = geometryfctory.renshow("circle");} catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); }x.erase(this.getGraphics());}private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) { graph y = null;try {y = geometryfctory.renshow("triangle");} catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex); }y.erase(this.getGraphics());}private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {graph z = null;try {z = geometryfctory.renshow("rectangle");}catch (Exception ex) {Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);}z.erase(this.getGraphics());}public static void main(String args[]) {java.awt.EventQueue.invokeLater(new Runnable() {public void run() {new NewJFrame().setVisible(true); }});}private javax.swing.JButton jButton1; private javax.swing.JButton jButton2;private javax.swing.JButton jButton3; private javax.swing.JButton jButton4;private javax.swing.JButton jButton5; private javax.swing.JButton jButton6;private javax.swing.JButton jButton7; private javax.swing.JTextField jTextField1;private javax.swing.JTextField jTextField2; }3.运行截图a.点击“运行”,如图1:b.分别点击画图行的“circle”“triangle”“rectangle”按钮,如图2图1 图2C.点击“擦除”行的“triangle”按钮,如图3 d.点击“其他“按钮,如图4图3 图4二.总结通过对本课程设计模式的学习,理解了部分模式的结构、优缺点及适用场景,也体会到了老师说的:设计模式不仅仅是编程工具,更是一门“艺术”。
JAVA画图板程序实验报告(附完整代码)分析
画板程序一、软件系统分析和设计方案1、功能需求分析设计类似于Windows画板的程序,程序可以通过功能菜单(或工具条)进行功能选择操作,在画板中可以用鼠标操作绘制不同颜色的点,直线,多边形和椭圆,可以保存和打开自定义的图形文件。
2、结构设计过程经过对需求的分析,我们设计的画图板界面主要包括菜单栏、工具栏、画板三个部分。
菜单栏包含文件、编辑、帮助等常见功能菜单,实现打开保存文件等功能;工具栏主要包括画笔、矩形、椭圆、直线、刷子、橡皮、文字、颜色等工具,可完成一些基本操作;画板能够编辑处理图片及文字。
而代码实现上采用面向对象的思想,将上述组件封装与一个画板类中布局并实现功能;通过一个窗框类实现画板对象;最后在主类中建立窗框对象。
思路如下图:二、软件实现和代码编写具体代码及详细注释如下:import java.awt.*;import java.awt.event.*;import java.awt.geom.*;import javax.swing.*;import javax.swing.UIManager.*;import java.io.*;import java.util.Vector;//主类建立窗框public class DrawPad {public static void main(String[] args) {try {// 优化UI效果for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) {UIManager.setLookAndFeel(info.getClassName());break;}}} catch (Exception e) {System.out.println(e);}new DrawFrame();}}// 添加窗口和画板组件class DrawFrame extends JFrame {public DrawFrame() {DrawPanel panel = new DrawPanel();add(panel);setTitle("简单JAVA画板");setBounds(100, 100, 800, 600);setVisible(true);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}}// 定义绘画点的基本属性class position implements Serializable {int x;int y;int type;String s;Color color;}// 定义画板组件class DrawPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener {JMenuBar mb;// 菜单栏JMenu menu1, menu2, menu3;JMenuItem i1, i2, i3, i4;JPanel jp1; // 工具栏public JButton anj0, anj1, anj2, anj3, anj4, anj5, anj6, anj7, anj8, anj9,anj10;JLabel l1, lcolor;Vector<position> thedraw = new Vector<position>(); // 保存画图轨迹的数组int style = 0; // 保存画图类型,默认为画笔int x1 = 0;// 保存点的坐标int x2 = 0;int y1 = 0;int y2 = 0;String input = "";// 默认输入文字内容Color linecolor = Color.BLACK; // 默认线的颜色public DrawPanel() {setBackground(Color.WHITE);setLayout(new BorderLayout());setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));// 上部菜单栏mb = new JMenuBar();mb.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));add(mb, BorderLayout.NORTH);// 加入菜单栏的组件menu1 = new JMenu(" 文件");menu2 = new JMenu(" 编辑");menu3 = new JMenu(" 帮助");i1 = new JMenuItem("打开", new ImageIcon("img/open.png"));i2 = new JMenuItem("保存", new ImageIcon("img/save.png"));i3 = new JMenuItem("清空", new ImageIcon("img/clear.png"));i4 = new JMenuItem("关于简单JAVA画板", new ImageIcon( "img/about.png"));menu1.add(i1);menu1.addSeparator();menu1.add(i2);menu2.add(i3);menu3.add(i4);mb.add(menu1);mb.add(menu2);mb.add(menu3);add(mb, BorderLayout.NORTH);// 侧边工具栏jp1 = new JPanel();jp1.setBackground(Color.LIGHT_GRAY);jp1.setLayout(new BoxLayout(jp1, BoxLayout.Y_AXIS));jp1.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));add(jp1, BorderLayout.WEST);// 加入工具栏的组件anj0 = new JButton("画笔", new ImageIcon("img/pen.png"));anj1 = new JButton("刷子", new ImageIcon("img/brush.png"));anj2 = new JButton("橡皮", new ImageIcon("img/erease.png"));anj3 = new JButton("文字", new ImageIcon("img/word.png"));anj4 = new JButton("直线", new ImageIcon("img/sline.png"));anj5 = new JButton("矩形", new ImageIcon("img/rec.png"));anj6 = new JButton("圆矩", new ImageIcon("img/frec.png"));anj7 = new JButton("椭圆", new ImageIcon("img/eli.png"));anj10 = new JButton("");lcolor = new JLabel("■");// 会变色的方块l1 = new JLabel(" 颜色");anj10.add(lcolor);anj10.add(l1);jp1.add(anj0);jp1.add(anj1);jp1.add(anj2);jp1.add(anj3);jp1.add(anj4);jp1.add(anj5);jp1.add(anj6);jp1.add(anj7);jp1.add(anj10);// 事件处理i1.addActionListener(this);i2.addActionListener(this);i3.addActionListener(this);i4.addActionListener(this);anj0.addActionListener(this);anj1.addActionListener(this);anj2.addActionListener(this);anj3.addActionListener(this);anj4.addActionListener(this);anj5.addActionListener(this);anj6.addActionListener(this);anj7.addActionListener(this);anj10.addActionListener(this);addMouseListener(this);addMouseMotionListener(this);}// 记录鼠标选择的功能public void actionPerformed(ActionEvent e) {if (e.getSource() == anj0)style = 0;else if (e.getSource() == anj1)style = 1;else if (e.getSource() == anj2)style = 2;else if (e.getSource() == anj3) {style = 3;input = JOptionPane.showInputDialog("输入文字后在画板上点击放置");} else if (e.getSource() == anj4)style = 4;else if (e.getSource() == anj5)style = 5;else if (e.getSource() == anj6)style = 6;else if (e.getSource() == anj7)style = 7;else if (e.getSource() == anj10) {linecolor = JColorChooser.showDialog(null, "请选择颜色", Color.BLACK);lcolor.setForeground(linecolor);} else if (e.getActionCommand().equals("关于简单JAVA画板")) {JOptionPane.showMessageDialog(null,"这是一个简单的JAVA画板。
Java语言_实习绘图
……
fileMI2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("Open")) { ReadFile(); }} }); ……}
为菜单添加事件
— 将事件和菜单写到一个类中。
public void ReadFile() {try { FileReader file1 = new FileReader("HubBount.txt"); BufferedReader buff = new BufferedReader(file1); boolean eof = false; try{ while(!eof){ String strTemp = buff.readLine(); if (strTemp == null) eof = true; else{ strInput = strTemp; getGraphics().drawString(strInput, 10, 100);}} catch(EOFException e) ……} }} }
为菜单添加事件
— 将事件类MenuListener与组件进行关联
import java.awt.*; import java.awt.event.*; public class TestMenuBar { …… TestMenuBar() { …… filePrint.add(printM1); //将菜单项加入print菜单中 filePrint.add(printM2); fileM.add(filePrint); //将print菜单作为菜单项加入file菜单中 MenuListener m1 = new MenuListener(); printM1.addActionListener(m1); printM2.addActionListener(m1); ……} }
JAVA简单画板程序设计实验报告
J A V A简单画板程序设计实验报告As a person, we must have independent thoughts and personality.JAVA期末画板实验报告课程题目:运用JAVA语言编写一个画板程序,这个画板要有画图,特殊图形绘制,颜色改变,画笔大小改变等功能。
设计思想:1.进行界面设计2.进行算法实现3.运行调试4.总结问题设计过程:A.界面设计B.新建一个Jframe容器,然后定义一个panel( Panel convas2),convas2是工具栏。
用borderlayout布置容器的边框布局,将工具栏放在NORTH部分。
完成界面设计。
add(canvas2,;Panel canvas2 = new Panel();添加工具按键Panel canvas2 = new Panel();Button btn1 = new Button("直线");Button btn2 = new Button("椭圆");Button btn3 = new Button("矩形");Button btn4 = new Button("清除");Button btn5 = new Button("画笔");Button btn6 = new Button("橡皮");Choice choice = new Choice();Choice choice1 = new Choice();(choice);(choice1);(btn1);(btn2);(btn3);(btn4);(btn5);(btn6);在工具表中,有两个下拉菜单,分别收录画笔的大小和颜色。
1.画笔的大小:("1");("3");("5");("7");("9");2.画笔颜色("黑色");("蓝色");("红色");("黄色");("绿色");3展示画板C.算法实现运用画板,首先要对工具栏按键和鼠标进行监听,然后对监听进行响应。
Java画板实验报告
二、Java画板的设计一、实验名称及其要求A、实验名称:Java画板的设计B、实验要求:1•实验目的:图形界面设计。
熟悉java.awt包中的组件,掌握图形界面设计方法,理解委托事件处理模型。
2•实验要求:(1)设计图形界面添加菜单:窗口上添加各种组件及菜单,并处理组件及菜单的事件监听程序。
(2 )实现画板的基本功能。
二、程序设计本程序完成的是一个类似于Win dows画图板的绘图程序。
由于不是开发和设计专业的绘图和图像制作软件,所以,完成的程序的简单功能包括以下几项:1. 新建一个空白图形文件:用于绘制新的图形。
2. 打开或保存一个图形文件,便于对图形文件的管理。
3. 绘制一些基本的画图组件:直线、矩形、实心矩形、椭圆、实心椭圆、圆、实心圆、圆角矩形、实心圆角矩形等。
4. 可以用鼠标在绘图面板上单击拖动进行随笔画。
5. 橡皮擦:可以将已绘制好的图形擦掉。
6. 添加文字:可以在绘图区域内添加文字。
7. 选择文字的字体:通过一个下拉式的选择条,可以选中所需要的字体。
本程序中包括:宋体、隶书、华文彩云、仿宋_GB2312华文行楷、方正舒体、Times NewRoman Serif、Monospaced SonsSerif、Garamond当然,在下面的的程序分析中可以看到,由于我们灵活设置了字体数组,是的可以随意添加系统支持的任何字体。
大大方便和简化了程序设计。
8. 选择文字的字体风格:通过两个复选框按钮,可以选择需要的字体风格,包括:粗体、斜体,使用者有三种选择方式,包括:①同时选中两者、②只选择其中一种、③ 两者都不选中。
9. 设置画笔的颜色:可以选择当前绘制图形的画笔颜色,让图形更加丰富多彩、生动活泼。
10. 设置画笔的粗细:该选项在作用于基本图形组件和文字时,它的效果是不一样的。
①当作用于绘制图形组件时,它的作用是改变画笔绘制线条的粗细;②当作用于文字时,它的作用是改变文字的大小。
由此可以看到,虽然我们的画图板程序不及那些专业的绘图程序,但是,“麻雀虽小, 五脏俱全”,它已经具备了一个绘图软件所应该有的基本功能和操作。
java画图程序-JAVA毕业设计论文
repaint();}Paint方法描述了组件的绘制方法,通过覆盖该方法,可绘制各种需要的图形。
在本程序中,通过一个swith-case结构来设置绘制图形的类型。
Shape参数来自于工具栏,通过drawShape方法传入,shape 为0、1、2时画线、画圆、画矩形,它们分别通过Graphics类的drawLine、drawOval、drawRect方法完成。
这部分的主要代码如下:switch (shape){case 0:g.drawLine(point[0].x,point[0].y,point[1].x,point[1].y);break;case 1:int width=point[1].x-point[0].x;int height=point[1].y-point[0].y;g.drawOval(point[0].x,point[0].y,width,height);break;case 2:width=point[1].x-point[0].x;height=point[1].y-point[0].y;g.drawRect(point[0].x,point[0].y,width,height);break;}2.演示程序在用户界面上方设置了一个工具栏,包含3个按钮,这3个按钮组成按钮组,某时刻只能一个按钮被有选中。
在按钮的事件处理中,调用ActionEvent类的getSource方法得到事件源,将它与3个按钮进行比较,可得到事件来自于哪个按钮,并将这个参数通过PainterPanel类的drawShape方法传递到PainterPanel 实例中,这样在发生鼠标拖拽时,就能根据shape的值来确定应该绘制哪种图形。
主要代码如下:for (int i=0;i<button.length;i++){if (e.getSource()==button[i]){painter.drawShape(i);}}本程序的运行效果如下图:。
Java实现简易画图程序
《Java语言》课程期末作业题目第1题:简易绘图程序学院计算机学院专业软件工程班别学号姓名2015年12月6日一、课程题目绘图应用程序。
利用学过的GUI 方法实现一个较为完整的绘图应用程序。
用户可以选择要画的图形(如线,椭圆,圆,矩形,弧,圆角矩形,多边形,折线等等),选择画笔颜色和画笔粗度,用鼠标单击和拖拽等动作绘图,并能将绘图结果保存为jpg和bmp格式.二、题目分析与设计1. 开发环境:Eclipse 4。
5.0 JDK 1.8.0_452. 题目需求分析:题目要求实现一个较为完整的绘图程序,最基本的要求是用户可以自由选择图形,颜色,线条粗细等属性,并用鼠标绘制图形,并将其保存为图片文件。
首先,程序界面参考一般绘图软件,进行组件的布局.另外对于程序的功能实现,则将图形封装成类,通过多态实现多种不同图形的绘制,并用输入输出流保存或打开文件。
除此之外根据实际操作的需要,添加一些必要或者实用的功能,如撤销操作,快捷键撤销或保存,关闭文件前弹窗提示保存等功能。
(1)。
菜单功能:通过菜单栏进行:一、文件的读取与写入;二、使用扩展功能;三、程序的简单偏好设置;四、程序信息提示。
(2). 绘图功能:在绘图过程通过工具栏进行形状、颜色等图形选择,在文本输入及扩展功能状态下会新增子工具栏,在子工具栏中对于字体或其它形状进行设置.然后在画板区域通过鼠标的点击与拖拽绘制图形。
绘图过程应有保存与撤销功能.绘图范围为画板的显示的区域.(3)。
其它功能:如快捷键Ctrl+z为撤销,Ctrl+s为保存。
鼠标停在工具栏按钮上时提示功能。
文件修改后窗口标题带上星号作为标记。
第一次编辑的文件或修改过的文件关闭前自动提示保存。
等等。
(4). 功能架构图:3。
界面设计:本程序使用Swing图形编程。
菜单:类似于常见程序,添加子菜单:File,Paint,Setting,Help。
在File 菜单下有new,open,save,exit等菜单项。
实验报告(画图)
计算机学院2008级2班张俊发20082101032一、实验目标用Java2D画图,实现画直线、矩形、圆角矩形、椭圆、曲线、多边形等功能,能从服务器加载图片,以及上传图片到服务器。
二、实验环境普通PC机,windows XP 操作系统。
使用了Netbeans和BlueJ两种工具。
三、关键源程序1、客户端/** To change this template, choose Tools | Templates* and open the template in the editor.*/package mydraw;/**** @author zhangjunfa*/import java.awt.Point;import java.awt.Graphics2D;import java.awt.geom.*;import java.awt.Color;import java.awt.Image;public abstract class MyShape {protected Color shapeColor=Color.BLACK;public static final int PENC=0;public static final int LINE=1;public static final int RECT=2;public static final int RORC=3;public static final int ELLI=4;public static final int POL Y=5;public static final int CURV=6;public static final int ERAS=7;public static final int IMAG=8;public abstract void draw(Graphics2D g);public void SetColor(Color clr){shapeColor=clr;}}class MyLine extends MyShape {private Line2D line=null;public MyLine(double x1,double y1,double x2,double y2){ line=new Line2D.Double(x1, y1, x2, y2);}public void draw(Graphics2D g) {// TODO Auto-generated method stubg.setColor(shapeColor);g.draw(line);}}class MyPencil extends MyShape {public int x[];public int y[];public int n;public MyPencil(int x[],int y[]) {this.x=x;this.y=y;this.n=x.length;}public void draw(Graphics2D g) {g.setColor(shapeColor);g.drawPolyline(x, y, n);}}class MyRectangle extends MyShape {private Rectangle2D rectangle=null;public MyRectangle(double x, double y, double w, double h) { rectangle=new Rectangle2D.Double(x, y, w, h);}public void draw(Graphics2D g) {g.setColor(shapeColor);g.draw(rectangle);}}class MyRoundRectangle extends MyShape {private RoundRectangle2D roundrect=null;public MyRoundRectangle(double x, double y, double w, double h) { roundrect=new RoundRectangle2D.Double(x, y, w, h,w/2,h/2);}public void draw(Graphics2D g) {g.setColor(shapeColor);g.draw(roundrect);}}class MyEllipse extends MyShape{private Ellipse2D ellipse=null;public MyEllipse(double x,double y,double w,double h) {ellipse=new Ellipse2D.Double(x, y, w, h);}public void draw(Graphics2D g) {g.setColor(shapeColor);g.draw(ellipse);}}class MyPoly extends MyShape {java.awt.Polygon plg=null;public MyPoly(int x[],int y[]) {plg=new java.awt.Polygon(x,y,x.length);}public void draw(Graphics2D g) {g.setColor(shapeColor);g.draw(plg);}}class MyEraser extends MyShape {public int x[];public int y[];public int n;public MyEraser(int x[],int y[]) {this.x=x;this.y=y;this.n=x.length;}public void draw(Graphics2D g) {g.setColor(Color.WHITE);g.drawPolyline(x, y, n);}}class MyCurve extends MyShape {public Point cBucket[]=new Point[4];public int action;CubicCurve2D cubicC=null;QuadCurve2D quadC=null;Line2D line=null;MyCurve(Point[] points,int as){for(int i=0;i<cBucket.length;i++){cBucket[i]=points[i];}action=as;}public void draw(Graphics2D g) {g.setColor(shapeColor);switch(action){case 4://三次曲线cubicC=new CubicCurve2D.Float();cubicC.setCurve(cBucket[0],cBucket[2],cBucket[3],cBucket[1]);g.draw(cubicC);break;case 3://2次曲�?quadC=new QuadCurve2D.Float();quadC.setCurve(cBucket[0],cBucket[2],cBucket[1]);g.draw(quadC);break;case 2://直线line=new Line2D.Float();line.setLine(cBucket[0],cBucket[1]);g.draw(line);break;default:break;}}}class MyImage extends MyShape {Image image=null;int width,height;public MyImage(int w,int h,Image img){width=w;height=h;image=img;}public void draw(Graphics2D g) {g.drawImage(image, 0, 20,(int)width,(int)height,null);}}/** To change this template, choose Tools | Templates* and open the template in the editor.*//** DrawPanel.java** Created on 2011-1-1, 10:56:53*/package mydraw;import java.awt.Rectangle;import java.awt.Robot;import java.io.*;import .Socket;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Point;import java.util.LinkedList;/**** @author zhangjunfa*/public class DrawPanel extends javax.swing.JPanel {private LinkedList<Point> points=new LinkedList<Point>();private LinkedList<MyShape> shapes=new LinkedList<MyShape>();private MyShape myshape;private java.awt.Color shpClr=java.awt.Color.BLACK;private int ShapeType=0;private int action=0;private int curNext=1;private Point[] curPoint=new Point[4];//曲线坐标�?private BufferedImage buffImage = null;/** Creates new form DrawPanel */public DrawPanel() {initComponents();this.setSize(590, 450);}/** This method is called from within the constructor to* initialize the form.* WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor.*/@SuppressWarnings("unchecked")// <editor-fold defaultstate="collapsed" desc="Generated Code">private void initComponents() {jToolBar1 = new javax.swing.JToolBar();Pencil = new javax.swing.JButton();Line = new javax.swing.JButton();Rect = new javax.swing.JButton();RoundRect = new javax.swing.JButton();Ellipse = new javax.swing.JButton();Poly = new javax.swing.JButton();Curve = new javax.swing.JButton();Erasre = new javax.swing.JButton();DownLoad = new javax.swing.JButton();UpLoad = new javax.swing.JButton();setBackground(new java.awt.Color(255, 255, 255));addMouseListener(new java.awt.event.MouseAdapter() {public void mousePressed(java.awt.event.MouseEvent evt) {formMousePressed(evt);}public void mouseReleased(java.awt.event.MouseEvent evt) {formMouseReleased(evt);}});addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseDragged(java.awt.event.MouseEvent evt) {formMouseDragged(evt);}});setLayout(null);jToolBar1.setRollover(true);Pencil.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/pencil.gif"))); // NOI18NPencil.setFocusable(false);Pencil.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);Pencil.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Pencil.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {PencilActionPerformed(evt);}});jToolBar1.add(Pencil);Line.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/line.gif"))); // NOI18N Line.setFocusable(false);Line.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);Line.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Line.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {LineActionPerformed(evt);}});jToolBar1.add(Line);Rect.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/rect.gif"))); // NOI18N Rect.setFocusable(false);Rect.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);Rect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Rect.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {RectActionPerformed(evt);}});jToolBar1.add(Rect);RoundRect.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/roundrect.gif"))); // NOI18NRoundRect.setFocusable(false);RoundRect.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); RoundRect.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);RoundRect.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {RoundRectActionPerformed(evt);}});jToolBar1.add(RoundRect);Ellipse.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/oval.gif"))); // NOI18N Ellipse.setFocusable(false);Ellipse.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); Ellipse.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Ellipse.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {EllipseActionPerformed(evt);}});jToolBar1.add(Ellipse);Poly.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/poly.gif"))); // NOI18N Poly.setFocusable(false);Poly.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);Poly.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Poly.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {PolyActionPerformed(evt);}});jToolBar1.add(Poly);Curve.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/curve.gif"))); // NOI18NCurve.setFocusable(false);Curve.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);Curve.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Curve.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {CurveActionPerformed(evt);}});jToolBar1.add(Curve);Erasre.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/mydraw/eraser.gif"))); // NOI18NErasre.setFocusable(false);Erasre.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);Erasre.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);Erasre.addActionListener(new java.awt.event.ActionListener() {public void actionPerformed(java.awt.event.ActionEvent evt) {ErasreActionPerformed(evt);}});jToolBar1.add(Erasre);DownLoad.setBackground(new java.awt.Color(216, 233, 236));DownLoad.setText("下载");DownLoad.setFocusable(false);DownLoad.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); DownLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);DownLoad.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {DownLoadActionPerformed(evt);}});jToolBar1.add(DownLoad);UpLoad.setBackground(new java.awt.Color(216, 233, 236));UpLoad.setText("上传");UpLoad.setFocusable(false);UpLoad.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); UpLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);UpLoad.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) {UpLoadActionPerformed(evt);}});jToolBar1.add(UpLoad);add(jToolBar1);jToolBar1.setSize(450, 40);}// </editor-fold>private void PencilActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.PENC;}private void LineActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.LINE;}private void RectActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.RECT;}private void RoundRectActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.RORC;}private void EllipseActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.ELLI;}private void PolyActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.POLY;}private void CurveActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.CURV;}private void ErasreActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:ShapeType=MyShape.ERAS;}private void formMousePressed(java.awt.event.MouseEvent evt) { // TODO add your handling code here:if(ShapeType == MyShape.CURV ){switch(curNext){case 1:curPoint[0]=evt.getPoint();action=1;curNext=2;break;case 3:if(shapes.size()!=0)shapes.removeLast();curPoint[2]=evt.getPoint();action=3;curNext=3;break;case 4:if(shapes.size()!=0)shapes.removeLast();curPoint[3]=evt.getPoint();action=4;curNext=4;break;default:break;}shapes.addLast(myshape);}repaint();}private void formMouseDragged(java.awt.event.MouseEvent evt) { // TODO add your handling code here:points.add(evt.getPoint());if(ShapeType == MyShape.CURV){switch(curNext){case 2:if(shapes.size()!=0)shapes.removeLast();curPoint[1]=evt.getPoint();action=2;curNext=2;break;case 3:if(shapes.size()!=0)shapes.removeLast();curPoint[2]=evt.getPoint();action=3;curNext=3;break;case 4:if(shapes.size()!=0)shapes.removeLast();curPoint[3]=evt.getPoint();action=4;curNext=4;break;default:break;}shapes.addLast(myshape);}repaint();}private void formMouseReleased(java.awt.event.MouseEvent evt) { // TODO add your handling code here:if(points.size()!=0)points.clear();//清除�?��拖拉引起的坐标点if(ShapeType == MyShape.CURV ){switch(curNext){case 2:if(shapes.size()!=0)shapes.removeLast();curPoint[1]=evt.getPoint();action=2;curNext=3;break;case 3:if(shapes.size()!=0)shapes.removeLast();curPoint[2]=evt.getPoint();action=3;curNext=4;break;case 4:if(shapes.size()!=0)shapes.removeLast();curPoint[3]=evt.getPoint();action=4;curNext=1;break;default:break;}}else{action=0;}shapes.addLast(myshape);}private void DownLoadActionPerformed(java.awt.event.ActionEvent evt) { ShapeType=MyShape.IMAG;try{Socket server=new Socket("localhost",5000);OutputStream netOut=server.getOutputStream();PrintStream out = new PrintStream(netOut);out.println("open");out.flush();File file=new File("newFile.jpg");file.createNewFile();RandomAccessFile raf=new RandomAccessFile(file,"rw");InputStream netIn=server.getInputStream();byte[] buf=new byte[2048];int num=netIn.read(buf);while(num!=(-1)){raf.write(buf,0,num);raf.skipBytes(num);num=netIn.read(buf);}netOut.close();netIn.close();raf.close();server.close();buffImage = ImageIO.read(file);int srcHeight = buffImage.getHeight();int srcWidth = buffImage.getWidth();if (srcHeight > this.getHeight() - 2|| srcWidth > this.getWidth() - 2) {int newHeight = this.getHeight();int newWidth = this.getWidth();myshape= new MyImage(newWidth, newHeight,buffImage);} else {myshape = new MyImage( srcWidth, srcHeight,buffImage);}shapes.add(myshape);file.delete();}catch(Exception e){System.out.print(e); }repaint();}private void UpLoadActionPerformed(java.awt.event.ActionEvent evt) { try{Socket client=new Socket("localhost",5000);OutputStream netOut=client.getOutputStream();PrintStream out = new PrintStream(netOut);out.println("save");out.flush();Robot r = null;Point p = this.getLocationOnScreen();int width = this.getWidth();int height = this.getHeight();try {r = new Robot();} catch (Exception e) {System.out.print(e); }// 截屏产生缓冲图象buffImage = r.createScreenCapture(new Rectangle(p.x, p.y, width,height));try{File file=new File("newFile.jpg");file.createNewFile();ImageIO.write(buffImage, "jpg", file);FileInputStream fout=new FileInputStream(file);//创建文件读取缓冲�?byte[] buf=new byte[2048];int num=fout.read(buf);while(num!=(-1)){//是否读完文件netOut.write(buf,0,num);//把文件数据写出网络缓冲区netOut.flush();num=fout.read(buf);//继续从文件中读取数据}fout.close();netOut.close();client.close();}catch(Exception e) {System.out.print(e); }}catch(Exception e){System.out.print(e); }}// Variables declaration - do not modifyprivate javax.swing.JButton Curve;private javax.swing.JButton DownLoad;private javax.swing.JButton Ellipse;private javax.swing.JButton Erasre;private javax.swing.JButton Line;private javax.swing.JButton Pencil;private javax.swing.JButton Poly;private javax.swing.JButton Rect;private javax.swing.JButton RoundRect;private javax.swing.JButton UpLoad;public javax.swing.JToolBar jToolBar1;// End of variables declaration@Overridepublic void paintComponent(Graphics g) {super.paintComponent(g);Graphics2D g2d=(Graphics2D)g;if(ShapeType!=MyShape.CURV){for(MyShape ms:shapes) {ms.draw(g2d);}}else if(shapes.size()>1){for(MyShape ms:shapes) {ms.draw(g2d);}}if(points.size()!=0){double startX=points.getFirst().getX();double startY=points.getFirst().getY();double endX=points.getLast().getX();double endY=points.getLast().getY();double width=Math.abs(endX-startX);double height=Math.abs(endY-startY);int length,x[],y[];switch(ShapeType){case MyShape.PENC:length = points.size();x = new int[length];y = new int[length];for (int i = 0; i < length; i++) {x[i] = points.get(i).x;y[i] = points.get(i).y;}myshape = new MyPencil(x, y);break;case MyShape.LINE:myshape=new MyLine(startX,startY,endX,endY);break;case MyShape.RECT:myshape=new MyRectangle(startX,startY,width,height);break;case MyShape.RORC:myshape=newMyRoundRectangle(startX,startY,width,height);break;case MyShape.ELLI:myshape=new MyEllipse(startX,startY,width,height);break;case MyShape.POLY:length = points.size();x = new int[length];y = new int[length];for (int i = 0; i < length; i++) {x[i] = points.get(i).x;y[i] = points.get(i).y;}myshape = new MyPoly(x, y);break;case MyShape.CURV:myshape=new MyCurve(curPoint,action);break;case MyShape.ERAS:length = points.size();x = new int[length];y = new int[length];for (int i = 0; i < length; i++) {x[i] = points.get(i).x;y[i] = points.get(i).y;}myshape = new MyEraser(x, y);break;default:break;}myshape.draw(g2d);}}}客户端:/*** 在这里给出对类ssad 的描述。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
实验三绘制图形一、实验目的学会JButton的使用,能进行JButton的基本操作,能使用JButton构造一个图形界面框架通过实验熟悉swing图形用户界面程序设计熟悉java中的事件处理模型,每个事件动作代表的意义进一步提高编程能力,学会独立思考,学会上网查找资料决问题。
二、实验内容设计一个程序,该程序能够绘制基本的图形(包括圆形、矩形、直线等);要求有一个简单易操作的用户界面(包括菜单、按钮等组件)。
编写的程序要求能够实现保存和读取的功能。
三、实验代码Main.javaimport ;import ;import ;importimportimportimport winpaint.WinToolBar;import winpaint.windowsPaint;public class Main {/*** @param args*/public static void main(String[] args) {// TODO Auto-generated method stubJPanel paintWin = new windowsPaint("画图");paintWin.setBounds(0, 30, 1000, 1000);paintWin.setLayout(null);paintWin.setVisible(true);JToolBar tool = new WinToolBar((windowsPaint)paintWin);tool.setBounds(0, 0, 1000, 30);tool.setVisible(true);JFrame frame = new JFrame();frame.setLayout(null);frame.setVisible(true);frame.setBounds(0, 0, 1000, 1000);frame.add(tool);frame.add(paintWin);}}test.javaimport base.GrapicsElem;import base.Rect;public class testfractor {/*** @param args* @throws ClassNotFoundException*/public static void main(String[] args) throws ClassNotFoundException { // TODO Auto-generated method stubGrapicsElem Ge = new Rect();Class<?> demo1=null;Class<?> demo2=null;Class<?> demo3=null;try{//一般尽量采用这种形式demo1=Class.forName("base.Rect");Class<?> con= demo1.getSuperclass();demo2 = Class.forName("base.GrapicsElem");Class<?> suns[] = demo2.getInterfaces();for (int i = 0; i < suns.length; i++) {}// GrapicsElem gg = (GrapicsElem)con[0].newInstance();con[0]);con[1]);con[2]);}catch(Exception e){e.printStackTrace();}demo2=new Rect().getClass();demo3=Rect.class;}}GrapicsElem.javapackage base;importimportimportpublic abstract class GrapicsElem {Point start;Point end;private Color color;public Color getColor() {return color;}public void setColor(Color color) {this.color = color;}public void setStart(Point start) {this.start = start;}public void setEnd(Point end) {this.end = end;}public abstract void doMousePress(Point p);public abstract void doMouseDrag(Point p);public abstract void doMouseRelease(Point p);public abstract void draw(Graphics g ) ;}Line.javapackage base;importimportimportpublic class Line extends GrapicsElem {ArrayList<Point> track;public Line(){track = new ArrayList<Point>();}@Overridepublic void draw(Graphics g) {for (int i = 0; i < track.size()-1; i++) {Point cur = track.get(i);Point next = track.get(i+1);g.drawLine(cur.x, cur.y, next.x, next.y);}}private void AddPoint(Point p){track.add(p);}@Overridepublic void doMousePress(Point p) {// TODO Auto-generated method stubAddPoint(p);}@Overridepublic void doMouseDrag(Point p) {// TODO Auto-generated method stubAddPoint(p);}@Overridepublic void doMouseRelease(Point p) {// TODO Auto-generated method stubAddPoint(p);}}Rect.javapackage base;importimportpublic class Rect extends GrapicsElem {int x,y,width,height;@Overridepublic void draw(Graphics g) {// TODO Auto-generated method stubg.drawRect(getX(), getY(), getWidth(), getHeight());}@Overridepublic void doMousePress(Point p) {super.setStart(p);super.setEnd(p);}@Overridepublic void doMouseDrag(Point p) {super.setEnd(p);}@Overridepublic void doMouseRelease(Point p) {super.setEnd(p);}public int getX() {return Math.min(start.x, end.x);}public int getY() {return Math.min(start.y, end.y);}public int getWidth() {return Math.abs(start.x-end.x);}public int getHeight() {return Math.abs(start.y-end.y);}}Circle.javapackage base;importpublic class Circle extends Rect {@Overridepublic void draw(Graphics g) {// TODO Auto-generated method stubg.drawOval(getX(), getY(), getWidth(), getHeight());}}windowsPaint.javapackage winpaint;import base.Circle;import base.GrapicsElem;import base.Line;import base.Rect;public class windowsPaint extends JPanelimplements MouseListener, MouseMotionListener {String command = "矩形";List<GrapicsElem> Lg = new ArrayList() ;GrapicsElem cur;JLabel label;public windowsPaint(String title){init();}private void init() {addMouseListener(this);addMouseMotionListener(this);}/*** 可以使用反射去掉判断语句、* Class<?> g = Class.forName("base.Rect");* g.newInstance();* @return*/private GrapicsElem newInstance(){command = mand;if(command.equals("矩形")){return new Rect();}else if(command.equals("圆形")){return new Circle();}else if(command.equals("线")){return new Line();}return null;}@Overridepublic void paint(Graphics g) {// TODO Auto-generated method stubsuper.paint(g);Graphics2D g2d = (Graphics2D) g;//g2d.setColor(cur.getColor());g2d.setStroke(new BasicStroke(10.0f));for (int i = 0; i < Lg.size(); i++) {GrapicsElem ge = Lg.get(i);ge.draw(g);}}// @Override// public void repaint() {// // TODO Auto-generated method stub// // TODO Auto-generated method stub// //// super.repaint();//// Thread thread = new Thread(new Runnable() {//// @Override//// public void run() {//// // TODO Auto-generated method stub//// try {//// SaveToFile();//// } catch (IOException e) {//// // TODO Auto-generated catch block//// e.printStackTrace();//// }//// }//// });//// thread.start();//////// ImageIcon bg = new ImageIcon("tmp.jpg");//// if(bg!=null){//// if(label!=null)//// this.remove(label);//// label = new JLabel(bg);//// label.setBounds(0,0,bg.getIconWidth(),bg.getIconHeight());//// this.add(label);//// super.repaint();//// }////// }private void SaveToFile() throws IOException {// TODO Auto-generated method stubBufferedImage bimg = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_3BYTE_BGR);Graphics2D g2d = bimg.createGraphics();this.paint(g2d);ImageIO.write(bimg, "jpg", new File("tmp.jpg"));}@Overridepublic void mousePressed(MouseEvent e) {Point p = new Point(e.getX(),e.getY());cur = newInstance();cur.doMousePress(p);Lg.add(cur);}@Overridepublic void mouseDragged(MouseEvent e) {Point p = new Point(e.getX(),e.getY());cur.doMouseDrag(p);repaint();}@Overridepublic void mouseReleased(MouseEvent e) {Point p = new Point(e.getX(),e.getY());cur.doMouseRelease(p);repaint();}@Overridepublic void mouseMoved(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}}WinToolBar.javapackage winpaint;public class WinToolBar extends JToolBar implements ActionListener{ public static String Command = "矩形";JButton btn1,btn2,btn3;//windowsPaint winp;public WinToolBar(windowsPaint winP ){btn1 = new JButton("矩形");btn2 = new JButton("圆形");btn3 = new JButton("线");this.add(btn1);this.add(btn2);this.add(btn3);btn1.addActionListener((ActionListener)this);btn2.addActionListener((ActionListener)this);btn3.addActionListener((ActionListener)this);// this.winp =winP;JComboBox com = new JComboBox();com.addItem("红色");com.addItem("蓝色");com.addItem("黑色");com.addItemListener(new ItemListener() {@Overridepublic void itemStateChanged(ItemEvent e) {// TODO Auto-generated method stub}});this.add(com);}@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubJButton btn = (JButton) e.getSource();btn.setBackground(Color.green);Command = btn.getActionCommand();}}三、实验结果。