一个用JAVA写的画图程序

 功能类似WINDOWS的画图程序,代码比较规范。对于刚刚接触图形界面开发的人很有帮助。(对我帮助也很大)

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import java.io.*;
  5. //定义画图的基本图形单元
  6. public class MiniDrawPad extends JFrame //主类,扩展了JFrame类,用来生成主界面
  7. {
  8.     private ObjectInputStream input;
  9.     private ObjectOutputStream output; //定义输入输出流,用来调用和保存图像文件
  10.     private JButton choices[];         //按钮数组,存放以下名称的功能按钮
  11.     private String names[] = {
  12.         "New",
  13.         "Open",
  14.         "Save"//这三个是基本操作按钮,包括"新建"、"打开"、"保存"
  15.         /*接下来是我们的画图板上面有的基本的几个绘图单元按钮*/
  16.         "Pencil"//铅笔画,也就是用鼠标拖动着随意绘图
  17.         "Line"//绘制直线
  18.         "Rect"//绘制空心矩形
  19.         "fRect"//绘制以指定颜色填充的实心矩形
  20.         "Oval"//绘制空心椭圆
  21.         "fOval"//绘制以指定颜色填充的实心椭圆
  22.         "Circle"//绘制圆形
  23.         "fCircle"//绘制以指定颜色填充的实心圆形
  24.         "RoundRect"//绘制空心圆角矩形
  25.         "frRect"//绘制以指定颜色填充的实心圆角矩形
  26.         "Rubber"//橡皮擦,可用来擦去已经绘制好的图案
  27.         "Color"//选择颜色按钮,可用来选择需要的颜色
  28.         "Stroke"//选择线条粗细的按钮,输入需要的数值可以实现绘图线条粗细的变化
  29.         "Word"      //输入文字按钮,可以在绘图板上实现文字输入
  30.     };
  31.     private String styleNames[] = {
  32.         " 宋体 "" 隶书 "" 华文彩云 "" 仿宋_GB2312 "" 华文行楷 ",
  33.         " 方正舒体 "" Times New Roman "" Serif "" Monospaced ",
  34.         " SonsSerif "" Garamond "
  35.     };            //可供选择的字体项
  36.     //当然这里的灵活的结构可以让读者自己随意添加系统支持的字体
  37.     private Icon items[];
  38.     private String tipText[] = {
  39.         //这里是鼠标移动到相应按钮上面上停留时给出的提示说明条
  40.         //读者可以参照上面的按钮定义对照着理解
  41.         "Draw a new picture",
  42.         "Open a saved picture",
  43.         "Save current drawing",
  44.         "Draw at will",
  45.         "Draw a straight line",
  46.         "Draw a rectangle",
  47.         "Fill a ractangle",
  48.         "Draw an oval",
  49.         "Fill an oval",
  50.         "Draw a circle",
  51.         "Fill a circle",
  52.         "Draw a round rectangle",
  53.         "Fill a round rectangle",
  54.         "Erase at will",
  55.         "Choose current drawing color",
  56.         "Set current drawing stroke",
  57.         "Write down what u want"
  58.     };
  59.     JToolBar buttonPanel;              //定义按钮面板
  60.     private JLabel statusBar;            //显示鼠标状态的提示条
  61.     private DrawPanel drawingArea;       //画图区域
  62.     private int width = 800,  height = 550;    //定义画图区域初始大小
  63.     drawings[] itemList = new drawings[5000]; //用来存放基本图形的数组
  64.     private int currentChoice = 3;            //设置默认画图状态为随笔画
  65.     int index = 0;                         //当前已经绘制的图形数目
  66.     private Color color = Color.black;     //当前画笔颜色
  67.     int R, G, B;                           //用来存放当前色彩值
  68.     int f1, f2;                  //用来存放当前字体风格
  69.     String style1;              //用来存放当前字体
  70.     private float stroke = 1.0f;  //设置画笔粗细,默认值为1.0f
  71.     JCheckBox bold, italic;      //定义字体风格选择框
  72.     //bold为粗体,italic为斜体,二者可以同时使用
  73.     JComboBox styles;
  74.     public MiniDrawPad() //构造函数
  75.     {
  76.         super("Drawing Pad");
  77.         JMenuBar bar = new JMenuBar();      //定义菜单条
  78.         JMenu fileMenu = new JMenu("File");
  79.         fileMenu.setMnemonic('F');
  80. //新建文件菜单条
  81.         JMenuItem newItem = new JMenuItem("New");
  82.         newItem.setMnemonic('N');
  83.         newItem.addActionListener(
  84.                 new ActionListener() {
  85.                     public void actionPerformed(ActionEvent e) {
  86.                         newFile();      //如果被触发,则调用新建文件函数段
  87.                     }
  88.                 });
  89.         fileMenu.add(newItem);
  90. //保存文件菜单项
  91.         JMenuItem saveItem = new JMenuItem("Save");
  92.         saveItem.setMnemonic('S');
  93.         saveItem.addActionListener(
  94.                 new ActionListener() {
  95.                     public void actionPerformed(ActionEvent e) {
  96.                         saveFile();     //如果被触发,则调用保存文件函数段
  97.                     }
  98.                 });
  99.         fileMenu.add(saveItem);
  100. //打开文件菜单项
  101.         JMenuItem loadItem = new JMenuItem("Load");
  102.         loadItem.setMnemonic('L');
  103.         loadItem.addActionListener(
  104.                 new ActionListener() {
  105.                     public void actionPerformed(ActionEvent e) {
  106.                         loadFile();     //如果被触发,则调用打开文件函数段
  107.                     }
  108.                 });
  109.         fileMenu.add(loadItem);
  110.         fileMenu.addSeparator();
  111. //退出菜单项
  112.         JMenuItem exitItem = new JMenuItem("Exit");
  113.         exitItem.setMnemonic('X');
  114.         exitItem.addActionListener(
  115.                 new ActionListener() {
  116.                     public void actionPerformed(ActionEvent e) {
  117.                         System.exit(0); //如果被触发,则退出画图板程序
  118.                     }
  119.                 });
  120.         fileMenu.add(exitItem);
  121.         bar.add(fileMenu);
  122. //设置颜色菜单条
  123.         JMenu colorMenu = new JMenu("Color");
  124.         colorMenu.setMnemonic('C');
  125. //选择颜色菜单项
  126.         JMenuItem colorItem = new JMenuItem("Choose Color");
  127.         colorItem.setMnemonic('O');
  128.         colorItem.addActionListener(
  129.                 new ActionListener() {
  130.                     public void actionPerformed(ActionEvent e) {
  131.                         chooseColor();  //如果被触发,则调用选择颜色函数段
  132.                     }
  133.                 });
  134.         colorMenu.add(colorItem);
  135.         bar.add(colorMenu);
  136. //设置线条粗细菜单条
  137.         JMenu strokeMenu = new JMenu("Stroke");
  138.         strokeMenu.setMnemonic('S');
  139. //设置线条粗细菜单项
  140.         JMenuItem strokeItem = new JMenuItem("Set Stroke");
  141.         strokeItem.setMnemonic('K');
  142.         strokeItem.addActionListener(
  143.                 new ActionListener() {
  144.                     public void actionPerformed(ActionEvent e) {
  145.                         setStroke();
  146.                     }
  147.                 });
  148.         strokeMenu.add(strokeItem);
  149.         bar.add(strokeMenu);
  150. //设置提示菜单条
  151.         JMenu helpMenu = new JMenu("Help");
  152.         helpMenu.setMnemonic('H');
  153. //设置提示菜单项
  154.         JMenuItem aboutItem = new JMenuItem("About this Drawing Pad!");
  155.         aboutItem.setMnemonic('A');
  156.         aboutItem.addActionListener(
  157.                 new ActionListener() {
  158.                     public void actionPerformed(ActionEvent e) {
  159.                         JOptionPane.showMessageDialog(null,
  160.                                 "This is a mini drawing pad!/nCopyright (c) 2002 Tsinghua University ",
  161.                                 " 画图板程序说明 ",
  162.                                 JOptionPane.INFORMATION_MESSAGE);
  163.                     }
  164.                 });
  165.         helpMenu.add(aboutItem);
  166.         bar.add(helpMenu);
  167.         items = new ImageIcon[names.length];
  168. //创建各种基本图形的按钮
  169.         drawingArea = new DrawPanel();
  170.         choices = new JButton[names.length];
  171.         buttonPanel = new JToolBar(JToolBar.VERTICAL);
  172.         buttonPanel = new JToolBar(JToolBar.HORIZONTAL);
  173.         ButtonHandler handler = new ButtonHandler();
  174.         ButtonHandler1 handler1 = new ButtonHandler1();
  175. //导入我们需要的图形图标,这些图标都存放在与源文件相同的目录下面
  176.         for (int i = 0; i < choices.length; i++) {//items[i]=new ImageIcon( MiniDrawPad.class.getResource(names[i] +".gif"));
  177.             //如果在jbuilder下运行本程序,则应该用这条语句导入图片
  178.             items[i] = new ImageIcon(names[i] + ".gif");
  179.             //默认的在jdk或者jcreator下运行,用此语句导入图片
  180.             choices[i] = new JButton("", items[i]);
  181.             choices[i].setToolTipText(tipText[i]);
  182.             buttonPanel.add(choices[i]);
  183.         }
  184. //将动作侦听器加入按钮里面
  185.         for (int i = 3; i < choices.length - 3; i++) {
  186.             choices[i].addActionListener(handler);
  187.         }
  188.         choices[0].addActionListener(
  189.                 new ActionListener() {
  190.                     public void actionPerformed(ActionEvent e) {
  191.                         newFile();
  192.                     }
  193.                 });
  194.         choices[1].addActionListener(
  195.                 new ActionListener() {
  196.                     public void actionPerformed(ActionEvent e) {
  197.                         loadFile();
  198.                     }
  199.                 });
  200.         choices[2].addActionListener(
  201.                 new ActionListener() {
  202.                     public void actionPerformed(ActionEvent e) {
  203.                         saveFile();
  204.                     }
  205.                 });
  206.         choices[choices.length - 3].addActionListener(handler1);
  207.         choices[choices.length - 2].addActionListener(handler1);
  208.         choices[choices.length - 1].addActionListener(handler1);
  209. //字体风格选择
  210.         styles = new JComboBox(styleNames);
  211.         styles.setMaximumRowCount(8);
  212.         styles.addItemListener(
  213.                 new ItemListener() {
  214.                     public void itemStateChanged(ItemEvent e) {
  215.                         style1 = styleNames[styles.getSelectedIndex()];
  216.                     }
  217.                 });
  218. //字体选择
  219.         bold = new JCheckBox("BOLD");
  220.         italic = new JCheckBox("ITALIC");
  221.         checkBoxHandler cHandler = new checkBoxHandler();
  222.         bold.addItemListener(cHandler);
  223.         italic.addItemListener(cHandler);
  224.         JPanel wordPanel = new JPanel();
  225.         buttonPanel.add(bold);
  226.         buttonPanel.add(italic);
  227.         buttonPanel.add(styles);
  228.         styles.setMinimumSize(new Dimension(5020));
  229.         styles.setMaximumSize(new Dimension(10020));
  230.         Container c = getContentPane();
  231.         super.setJMenuBar(bar);
  232.         c.add(buttonPanel, BorderLayout.NORTH);
  233.         c.add(drawingArea, BorderLayout.CENTER);
  234.         statusBar = new JLabel();
  235.         c.add(statusBar, BorderLayout.SOUTH);
  236.         statusBar.setText("     Welcome To The Little Drawing Pad!!!  :)");
  237.         createNewItem();
  238.         setSize(width, height);
  239.         show();
  240.     }
  241. //按钮侦听器ButtonHanler类,内部类,用来侦听基本按钮的操作
  242.     public class ButtonHandler implements ActionListener {
  243.         public void actionPerformed(ActionEvent e) {
  244.             for (int j = 3; j < choices.length - 3; j++) {
  245.                 if (e.getSource() == choices[j]) {
  246.                     currentChoice = j;
  247.                     createNewItem();
  248.                     repaint();
  249.                 }
  250.             }
  251.         }
  252.     }
  253. //按钮侦听器ButtonHanler1类,用来侦听颜色选择、画笔粗细设置、文字输入按钮的操作
  254.     public class ButtonHandler1 implements ActionListener {
  255.         public void actionPerformed(ActionEvent e) {
  256.             if (e.getSource() == choices[choices.length - 3]) {
  257.                 chooseColor();
  258.             }
  259.             if (e.getSource() == choices[choices.length - 2]) {
  260.                 setStroke();
  261.             }
  262.             if (e.getSource() == choices[choices.length - 1]) {
  263.                 JOptionPane.showMessageDialog(null,
  264.                         "Please hit the drawing pad to choose the word input position",
  265.                         "Hint", JOptionPane.INFORMATION_MESSAGE);
  266.                 currentChoice = 14;
  267.                 createNewItem();
  268.                 repaint();
  269.             }
  270.         }
  271.     }
  272. //鼠标事件mouseA类,继承了MouseAdapter,用来完成鼠标相应事件操作
  273.     class mouseA extends MouseAdapter {
  274.         public void mousePressed(MouseEvent e) {
  275.             statusBar.setText("     Mouse Pressed @:[" + e.getX() +
  276.                     ", " + e.getY() + "]");//设置状态提示
  277.             itemList[index].x1 = itemList[index].x2 = e.getX();
  278.             itemList[index].y1 = itemList[index].y2 = e.getY();
  279.             //如果当前选择的图形是随笔画或者橡皮擦,则进行下面的操作
  280.             if (currentChoice == 3 || currentChoice == 13) {
  281.                 itemList[index].x1 = itemList[index].x2 = e.getX();
  282.                 itemList[index].y1 = itemList[index].y2 = e.getY();
  283.                 index++;
  284.                 createNewItem();
  285.             }
  286.             //如果当前选择的图形式文字输入,则进行下面操作
  287.             if (currentChoice == 14) {
  288.                 itemList[index].x1 = e.getX();
  289.                 itemList[index].y1 = e.getY();
  290.                 String input;
  291.                 input = JOptionPane.showInputDialog(
  292.                         "Please input the text you want!");
  293.                 itemList[index].s1 = input;
  294.                 itemList[index].x2 = f1;
  295.                 itemList[index].y2 = f2;
  296.                 itemList[index].s2 = style1;
  297.                 index++;
  298.                 currentChoice = 14;
  299.                 createNewItem();
  300.                 drawingArea.repaint();
  301.             }
  302.         }
  303.         public void mouseReleased(MouseEvent e) {
  304.             statusBar.setText("     Mouse Released @:[" + e.getX() +
  305.                     ", " + e.getY() + "]");
  306.             if (currentChoice == 3 || currentChoice == 13) {
  307.                 itemList[index].x1 = e.getX();
  308.                 itemList[index].y1 = e.getY();
  309.             }
  310.             itemList[index].x2 = e.getX();
  311.             itemList[index].y2 = e.getY();
  312.             repaint();
  313.             index++;
  314.             createNewItem();
  315.         }
  316.         public void mouseEntered(MouseEvent e) {
  317.             statusBar.setText("     Mouse Entered @:[" + e.getX() +
  318.                     ", " + e.getY() + "]");
  319.         }
  320.         public void mouseExited(MouseEvent e) {
  321.             statusBar.setText("     Mouse Exited @:[" + e.getX() +
  322.                     ", " + e.getY() + "]");
  323.         }
  324.     }
  325. //鼠标事件mouseB类继承了MouseMotionAdapter,用来完成鼠标拖动和鼠标移动时的相应操作
  326.     class mouseB extends MouseMotionAdapter {
  327.         public void mouseDragged(MouseEvent e) {
  328.             statusBar.setText("     Mouse Dragged @:[" + e.getX() +
  329.                     ", " + e.getY() + "]");
  330.             if (currentChoice == 3 || currentChoice == 13) {
  331.                 itemList[index - 1].x1 = itemList[index].x2 = itemList[index].x1 = e.getX();
  332.                 itemList[index - 1].y1 = itemList[index].y2 = itemList[index].y1 = e.getY();
  333.                 index++;
  334.                 createNewItem();
  335.             } else {
  336.                 itemList[index].x2 = e.getX();
  337.                 itemList[index].y2 = e.getY();
  338.             }
  339.             repaint();
  340.         }
  341.         public void mouseMoved(MouseEvent e) {
  342.             statusBar.setText("     Mouse Moved @:[" + e.getX() +
  343.                     ", " + e.getY() + "]");
  344.         }
  345.     }
  346. //选择字体风格时候用到的事件侦听器类,加入到字体风格的选择框中
  347.     private class checkBoxHandler implements ItemListener {
  348.         public void itemStateChanged(ItemEvent e) {
  349.             if (e.getSource() == bold) {
  350.                 if (e.getStateChange() == ItemEvent.SELECTED) {
  351.                     f1 = Font.BOLD;
  352.                 } else {
  353.                     f1 = Font.PLAIN;
  354.                 }
  355.             }
  356.             if (e.getSource() == italic) {
  357.                 if (e.getStateChange() == ItemEvent.SELECTED) {
  358.                     f2 = Font.ITALIC;
  359.                 } else {
  360.                     f2 = Font.PLAIN;
  361.                 }
  362.             }
  363.         }
  364.     }
  365. //画图面板类,用来画图
  366.     class DrawPanel extends JPanel {
  367.         public DrawPanel() {
  368.             setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
  369.             setBackground(Color.white);
  370.             addMouseListener(new mouseA());
  371.             addMouseMotionListener(new mouseB());
  372.         }
  373.         @Override
  374.         public void paintComponent(Graphics g) {
  375.             super.paintComponent(g);
  376.             Graphics2D g2d = (Graphics2D) g;    //定义画笔
  377.             int j = 0;
  378.             while (j <= index) {
  379.                 draw(g2d, itemList[j]);
  380.                 j++;
  381.             }
  382.         }
  383.         void draw(Graphics2D g2d, drawings i) {
  384.             i.draw(g2d);//将画笔传入到各个子类中,用来完成各自的绘图
  385.         }
  386.     }
  387. //新建一个画图基本单元对象的程序段
  388.     void createNewItem() {
  389.         if (currentChoice == 14)//进行相应的游标设置
  390.         {
  391.             drawingArea.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
  392.         } else {
  393.             drawingArea.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
  394.         }
  395.         switch (currentChoice) {
  396.             case 3:
  397.                 itemList[index] = new Pencil();
  398.                 break;
  399.             case 4:
  400.                 itemList[index] = new Line();
  401.                 break;
  402.             case 5:
  403.                 itemList[index] = new Rect();
  404.                 break;
  405.             case 6:
  406.                 itemList[index] = new fillRect();
  407.                 break;
  408.             case 7:
  409.                 itemList[index] = new Oval();
  410.                 break;
  411.             case 8:
  412.                 itemList[index] = new fillOval();
  413.                 break;
  414.             case 9:
  415.                 itemList[index] = new Circle();
  416.                 break;
  417.             case 10:
  418.                 itemList[index] = new fillCircle();
  419.                 break;
  420.             case 11:
  421.                 itemList[index] = new RoundRect();
  422.                 break;
  423.             case 12:
  424.                 itemList[index] = new fillRoundRect();
  425.                 break;
  426.             case 13:
  427.                 itemList[index] = new Rubber();
  428.                 break;
  429.             case 14:
  430.                 itemList[index] = new Word();
  431.                 break;
  432.         }
  433.         itemList[index].type = currentChoice;
  434.         itemList[index].R = R;
  435.         itemList[index].G = G;
  436.         itemList[index].B = B;
  437.         itemList[index].stroke = stroke;
  438.     }
  439. //选择当前颜色程序段
  440.     public void chooseColor() {
  441.         color = JColorChooser.showDialog(MiniDrawPad.this,
  442.                 "Choose a color", color);
  443.         R = color.getRed();
  444.         G = color.getGreen();
  445.         B = color.getBlue();
  446.         itemList[index].R = R;
  447.         itemList[index].G = G;
  448.         itemList[index].B = B;
  449.     }
  450. //选择当前线条粗细程序段
  451.     public void setStroke() {
  452.         String input;
  453.         input = JOptionPane.showInputDialog(
  454.                 "Please input a float stroke value! ( >0 )");
  455.         stroke = Float.parseFloat(input);
  456.         itemList[index].stroke = stroke;
  457.     }
  458. //保存图形文件程序段
  459.     public void saveFile() {
  460.         JFileChooser fileChooser = new JFileChooser();
  461.         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  462.         int result = fileChooser.showSaveDialog(this);
  463.         if (result == JFileChooser.CANCEL_OPTION) {
  464.             return;
  465.         }
  466.         File fileName = fileChooser.getSelectedFile();
  467.         fileName.canWrite();
  468.         if (fileName == null || fileName.getName().equals("")) {
  469.             JOptionPane.showMessageDialog(fileChooser, "Invalid File Name",
  470.                     "Invalid File Name", JOptionPane.ERROR_MESSAGE);
  471.         } else {
  472.             try {
  473.                 fileName.delete();
  474.                 FileOutputStream fos = new FileOutputStream(fileName);
  475.                 output = new ObjectOutputStream(fos);
  476.                 drawings record;
  477.                 output.writeInt(index);
  478.                 for (int i = 0; i < index; i++) {
  479.                     drawings p = itemList[i];
  480.                     output.writeObject(p);
  481.                     output.flush();    //将所有图形信息强制转换成父类线性化存储到文件中
  482.                 }
  483.                 output.close();
  484.                 fos.close();
  485.             } catch (IOException ioe) {
  486.                 ioe.printStackTrace();
  487.             }
  488.         }
  489.     }
  490. //打开一个图形文件程序段
  491.     public void loadFile() {
  492.         JFileChooser fileChooser = new JFileChooser();
  493.         fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  494.         int result = fileChooser.showOpenDialog(this);
  495.         if (result == JFileChooser.CANCEL_OPTION) {
  496.             return;
  497.         }
  498.         File fileName = fileChooser.getSelectedFile();
  499.         fileName.canRead();
  500.         if (fileName == null || fileName.getName().equals("")) {
  501.             JOptionPane.showMessageDialog(fileChooser, "Invalid File Name",
  502.                     "Invalid File Name", JOptionPane.ERROR_MESSAGE);
  503.         } else {
  504.             try {
  505.                 FileInputStream fis = new FileInputStream(fileName);
  506.                 input = new ObjectInputStream(fis);
  507.                 drawings inputRecord;
  508.                 int countNumber = 0;
  509.                 countNumber = input.readInt();
  510.                 for (index = 0; index < countNumber; index++) {
  511.                     inputRecord = (drawings) input.readObject();
  512.                     itemList[index] = inputRecord;
  513.                 }
  514.                 createNewItem();
  515.                 input.close();
  516.                 repaint();
  517.             } catch (EOFException endofFileException) {
  518.                 JOptionPane.showMessageDialog(this"no more record in file",
  519.                         "class not found", JOptionPane.ERROR_MESSAGE);
  520.             } catch (ClassNotFoundException classNotFoundException) {
  521.                 JOptionPane.showMessageDialog(this"Unable to Create Object",
  522.                         "end of file", JOptionPane.ERROR_MESSAGE);
  523.             } catch (IOException ioException) {
  524.                 JOptionPane.showMessageDialog(this"error during read from file",
  525.                         "read Error", JOptionPane.ERROR_MESSAGE);
  526.             }
  527.         }
  528.     }
  529. //新建一个文件程序段
  530.     public void newFile() {
  531.         index = 0;
  532.         currentChoice = 3;
  533.         color = Color.black;
  534.         stroke = 1.0f;
  535.         createNewItem();
  536.         repaint();//将有关值设置为初始状态,并且重画
  537.     }
  538. //主函数段
  539.     public static void main(String args[]) {
  540.         try {
  541.             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  542.         } catch (Exception e) {
  543.         }//将界面设置为当前windows风格
  544.         MiniDrawPad newPad = new MiniDrawPad();
  545.         newPad.addWindowListener(
  546.                 new WindowAdapter() {
  547.                     public void windowClosing(WindowEvent e) {
  548.                         System.exit(0);
  549.                     }
  550.                 });
  551.     }
  552. }
  553. class drawings implements Serializable//父类,基本图形单元,用到串行化接口,保存时所用
  554. {
  555.     int x1, y1, x2, y2; //定义坐标属性
  556.     int R, G, B;        //定义色彩属性
  557.     float stroke;       //定义线条粗细属性
  558.     int type;       //定义字体属性
  559.     String s1;
  560.     String s2;      //定义字体风格属性
  561.     void draw(Graphics2D g2d) {
  562.     }
  563.     ;//定义绘图函数
  564. }
  565. /*******************************************************************************
  566. 下面是各种基本图形单元的子类,都继承自父类drawings,请仔细理解继承的概念
  567.  ********************************************************************************/
  568. class Line extends drawings //直线类
  569. {
  570.     void draw(Graphics2D g2d) {
  571.         g2d.setPaint(new Color(R, G, B));
  572.         g2d.setStroke(new BasicStroke(stroke,
  573.                 BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
  574.         g2d.drawLine(x1, y1, x2, y2);
  575.     }
  576. }
  577. class Rect extends drawings//矩形类
  578. {
  579.     void draw(Graphics2D g2d) {
  580.         g2d.setPaint(new Color(R, G, B));
  581.         g2d.setStroke(new BasicStroke(stroke));
  582.         g2d.drawRect(Math.min(x1, x2), Math.min(y1, y2),
  583.                 Math.abs(x1 - x2), Math.abs(y1 - y2));
  584.     }
  585. }
  586. class fillRect extends drawings//实心矩形类
  587. {
  588.     void draw(Graphics2D g2d) {
  589.         g2d.setPaint(new Color(R, G, B));
  590.         g2d.setStroke(new BasicStroke(stroke));
  591.         g2d.fillRect(Math.min(x1, x2), Math.min(y1, y2),
  592.                 Math.abs(x1 - x2), Math.abs(y1 - y2));
  593.     }
  594. }
  595. class Oval extends drawings//椭圆类
  596. {
  597.     void draw(Graphics2D g2d) {
  598.         g2d.setPaint(new Color(R, G, B));
  599.         g2d.setStroke(new BasicStroke(stroke));
  600.         g2d.drawOval(Math.min(x1, x2), Math.min(y1, y2),
  601.                 Math.abs(x1 - x2), Math.abs(y1 - y2));
  602.     }
  603. }
  604. class fillOval extends drawings//实心椭圆
  605. {
  606.     void draw(Graphics2D g2d) {
  607.         g2d.setPaint(new Color(R, G, B));
  608.         g2d.setStroke(new BasicStroke(stroke));
  609.         g2d.fillOval(Math.min(x1, x2), Math.min(y1, y2),
  610.                 Math.abs(x1 - x2), Math.abs(y1 - y2));
  611.     }
  612. }
  613. class Circle extends drawings//圆类
  614. {
  615.     void draw(Graphics2D g2d) {
  616.         g2d.setPaint(new Color(R, G, B));
  617.         g2d.setStroke(new BasicStroke(stroke));
  618.         g2d.drawOval(Math.min(x1, x2), Math.min(y1, y2),
  619.                 Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)),
  620.                 Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)));
  621.     }
  622. }
  623. class fillCircle extends drawings//实心圆
  624. {
  625.     void draw(Graphics2D g2d) {
  626.         g2d.setPaint(new Color(R, G, B));
  627.         g2d.setStroke(new BasicStroke(stroke));
  628.         g2d.fillOval(Math.min(x1, x2), Math.min(y1, y2),
  629.                 Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)),
  630.                 Math.max(Math.abs(x1 - x2), Math.abs(y1 - y2)));
  631.     }
  632. }
  633. class RoundRect extends drawings//圆角矩形类
  634. {
  635.     void draw(Graphics2D g2d) {
  636.         g2d.setPaint(new Color(R, G, B));
  637.         g2d.setStroke(new BasicStroke(stroke));
  638.         g2d.drawRoundRect(Math.min(x1, x2), Math.min(y1, y2),
  639.                 Math.abs(x1 - x2), Math.abs(y1 - y2),
  640.                 5035);
  641.     }
  642. }
  643. class fillRoundRect extends drawings//实心圆角矩形类
  644. {
  645.     void draw(Graphics2D g2d) {
  646.         g2d.setPaint(new Color(R, G, B));
  647.         g2d.setStroke(new BasicStroke(stroke));
  648.         g2d.fillRoundRect(Math.min(x1, x2), Math.min(y1, y2),
  649.                 Math.abs(x1 - x2), Math.abs(y1 - y2),
  650.                 5035);
  651.     }
  652. }
  653. class Pencil extends drawings//随笔画类
  654. {
  655.     void draw(Graphics2D g2d) {
  656.         g2d.setPaint(new Color(R, G, B));
  657.         g2d.setStroke(new BasicStroke(stroke,
  658.                 BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
  659.         g2d.drawLine(x1, y1, x2, y2);
  660.     }
  661. }
  662. class Rubber extends drawings//橡皮擦类
  663. {
  664.     void draw(Graphics2D g2d) {
  665.         g2d.setPaint(new Color(255255255));
  666.         g2d.setStroke(new BasicStroke(stroke + 4,
  667.                 BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
  668.         g2d.drawLine(x1, y1, x2, y2);
  669.     }
  670. }
  671. class Word extends drawings//输入文字类
  672. {
  673.     void draw(Graphics2D g2d) {
  674.         g2d.setPaint(new Color(R, G, B));
  675.         g2d.setFont(new Font(s2, x2 + y2, ((int) stroke) * 18));
  676.         if (s1 != null) {
  677.             g2d.drawString(s1, x1, y1);
  678.         }
  679.     }
  680. }

### 回答1: 好的,我可以提供一些代码示例来帮助你一个 Java 贪吃蛇小程序。 首先,你需要创建一个面向对象的类,用来描述蛇的各个部分。比如: ``` class SnakePart { int x, y; public SnakePart(int x, int y) { this.x = x; this.y = y; } } ``` 然后,你需要创建一个 Snake 类,用来维护蛇的位置和状态: ``` import java.util.LinkedList; class Snake { LinkedList<SnakePart> snakeParts = new LinkedList<>(); int direction; public Snake(int x, int y) { snakeParts.add(new SnakePart(x, y)); direction = 0; } public void move() { SnakePart head = snakeParts.getFirst(); int x = head.x; int y = head.y; switch (direction) { case 0: y--; break; case 1: x++; break; case 2: y++; break; case 3: x--; break; } snakeParts.addFirst(new SnakePart(x, y)); snakeParts.removeLast(); } } ``` 最后,你可以创建一个 GUI 程序,用来呈现贪吃蛇游戏: ``` import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.Timer; public class SnakeGame extends JPanel implements ActionListener { private Snake snake; private Timer timer; private Point fruit; public SnakeGame() { setBackground(Color.WHITE); setFocusable(true); snake = new Snake(40, 40); timer = new Timer(50, this); timer.start(); addFruit(); } @Override public void actionPerformed(ActionEvent e) { snake.move(); if (snake ### 回答2: 贪吃蛇是一款经典的游戏,在Java中开发一个贪吃蛇小程序可以通过以下的步骤实现: 1. 创建游戏窗口:使用Java SwingJavaFX框架创建一个游戏窗口,设置窗口的标题、大小和关闭方式。 2. 绘制游戏画面:使用Java图形库绘制游戏界面,包括背景、蛇身和食物等元素。可以使用二维数组或集合来表示游戏地图,每个格子可以是空白、蛇身或食物。 3. 实现蛇的移动:定义一个蛇类,包括蛇的初始长度、位置和移动方向等属性,通过监听键盘事件来改变蛇的移动方向。在每一次游戏循环中更新蛇的位置,包括蛇身的增加和移除。 4. 确定食物位置:在每一次游戏循环中判断蛇是否吃到食物,如果蛇头位置与食物位置重合,则蛇的长度增加,并重新生成食物的位置。 5. 判断游戏结束:在每一次游戏循环中判断蛇是否碰到边界或自身,如果是则游戏结束,弹出游戏结束提示框。 6. 计分和游戏速度调整:在游戏的界面上显示当前得分,并根据得分的增加调整游戏的速度。 通过以上步骤,可以初步实现一个简单的贪吃蛇小程序。为了提升游戏体验,还可以添加音效、障碍物、不同难度级别等功能来丰富游戏。 ### 回答3: 贪吃蛇是一种经典的游戏,现在我来用Java一个简单的贪吃蛇小程序。 首先,我们需要创建一个贪吃蛇的游戏窗口。可以使用JavaSwing库来创建一个窗口,并设置窗口的大小和标题。 然后,我们需要创建一个表示贪吃蛇的类。这个类包含贪吃蛇的身体坐标,方向以及移动的方法。 接下来,我们需要创建一个表示食物的类。这个类包含食物的坐标和随机生成的方法。 在主程序中,我们可以通过键盘监听来控制贪吃蛇的移动方向。根据用户的按键事件,我们可以改变贪吃蛇的方向。 在游戏的主循环中,我们可以不断更新贪吃蛇的位置,并判断是否吃到了食物。如果贪吃蛇吃到了食物,我们可以根据一定的规则来增加贪吃蛇的身体长度。 另外,我们还需要判断贪吃蛇是否碰到了自己的身体或者窗口的边缘。如果碰到了身体或者边缘,游戏结束。 最后,我们可以在窗口中绘制贪吃蛇和食物的位置,以及显示当前得分和游戏状态。 总的来说,编一个贪吃蛇小程序涉及到创建游戏窗口、贪吃蛇类、食物类,并实现用户操作、游戏逻辑和画图等功能。这只是一个简单的贪吃蛇小程序,还有很多细节和功能可以进一步完善。
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值