更新時間:2021-09-29 09:05:16 來源:動力節點 瀏覽963次
有一個簡單的工具來繪制基本的幾何形狀。該Java開發工具是使用 AWT 組件編寫的,并詳細闡述了諸如內部類、事件處理、多態性和菜單處理等功能。在本文中,我們將逐塊逐步執行代碼以構建我們的簡單繪圖工具。
首先,我們從一個空的類結構開始,我們從 java.awt.Frame 類擴展/繼承它。我們設置框架的標題和大小并使其可見。
//Title: A Simple Drawing Tool
//Version: 1.0
//Copyright: Copyright (c) 2001
//Author: Yasir Feroze Minhas
//Company: KAPS Computing (pvt) Ltd.
//Description: This is a simple tool written using AWT for drawing basic shapes.
package graph;
import java.awt.*;
public class SimpleDrawingTool extends Frame{
public SimpleDrawingTool() {
//set frame's title
super("Simple Drawing Tool");
//set frame size
this.setSize(400, 400);
//make this frame visible
this.setVisible(true);
}
public static void main(String[] args) {
SimpleDrawingTool simpleDrawingTool = new SimpleDrawingTool();
}
}
接下來,我們將菜單欄附加到我們的繪圖工具,并用最少的菜單項對其進行裝飾。
//Title: A Simple Drawing Tool
//Version: 1.0
//Copyright: Copyright (c) 2001
//Author: Yasir Feroze Minhas
//Company: KAPS Computing (pvt) Ltd.
//Description: This is a simple tool written using AWT for drawing basic shapes.
package graph;
import java.awt.*;
public class SimpleDrawingTool extends Frame{
//constants for menu shortcuts
private static final int kControlA = 65;
private static final int kControlD = 68;
private static final int kControlC = 67;
private static final int kControlR = 82;
private static final int kControlP = 80;
private static final int kControlT = 84;
private static final int kControlX = 88;
public SimpleDrawingTool() {
//set frame's title
super("Simple Drawing Tool");
//add menu
addMenu();
//set frame size
this.setSize(400, 400);
//make this frame visible
this.setVisible(true);
}
public static void main(String[] args) {
SimpleDrawingTool simpleDrawingTool = new SimpleDrawingTool();
}
/**
This method creates menu bar and menu items and then attach the menu bar
with the frame of this drawing tool.
*/
private void addMenu()
{
//Add menu bar to our frame
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File");
Menu shape = new Menu("Shapes");
Menu about = new Menu("About");
//now add menu items to these Menu objects
file.add(new MenuItem("Exit", new MenuShortcut(kControlX)));
shape.add(new MenuItem("Rectangle", new MenuShortcut(kControlR)));
shape.add(new MenuItem("Circle", new MenuShortcut(kControlC)));
shape.add(new MenuItem("Triangle", new MenuShortcut(kControlT)));
shape.add(new MenuItem("Polygon", new MenuShortcut(kControlP)));
shape.add(new MenuItem("Draw Polygon", new MenuShortcut(kControlD)));
about.add(new MenuItem("About", new MenuShortcut(kControlA)));
//add menus to menubar
menuBar.add(file);
menuBar.add(shape);
menuBar.add(about);
//menuBar.setVisible(true);
if(null == this.getMenuBar())
{
this.setMenuBar(menuBar);
}
}//addMenu()
}
菜單欄就位,您可以導航不同的菜單和菜單項。但由于它們尚未附加任何事件處理程序,因此您只能做導航。下一步是添加事件處理程序,以便我們可以捕獲用戶的選擇并采取相應的行動。
package graph;
import java.awt.*;
//import event package
import java.awt.event.*;
//import swing package for pop up message box
import javax.swing.*;
public class SimpleDrawingTool extends Frame{
...
private void addMenu()
{
...
file.add(new MenuItem("Exit", new MenuShortcut(kControlX))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Rectangle", new MenuShortcut(kControlR))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Circle", new MenuShortcut(kControlC))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Triangle", new MenuShortcut(kControlT))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Polygon", new MenuShortcut(kControlP))).addActionListener(new WindowHandler());
shape.add(new MenuItem("Draw Polygon", new MenuShortcut(kControlD))).addActionListener(new WindowHandler());
about.add(new MenuItem("About", new MenuShortcut(kControlA))).addActionListener(new WindowHandler());
...
}
...
//Inner class to handle events
private class WindowHandler extends WindowAdapter implements ActionListener
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand());
//check to see if the action command is equal to exit
if(e.getActionCommand().equalsIgnoreCase("exit"))
{
System.exit(0);
}
else if(e.getActionCommand().equalsIgnoreCase("About"))
{
JOptionPane.showMessageDialog(null, "This small freeware program is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "You asked for a "+e.getActionCommand(), "A Simple Drawing Tool", JOptionPane.PLAIN_MESSAGE);
}
}//actionPerformed()
}//windowHandler - Inner Class ends here
}
現在是時候寫下我們的 Shapes 類了。我們使用一種方法將 Shapes 類定義為抽象類draw(),然后將其擴展為 Rectangle、Oval、Triangle 和 Polygon 的具體類。然后我們使用多態根據傳遞的上述具體類的運行時對象繪制不同的形狀。
/**
This is the abstract parent class for different shape classes,
like rectangle, oval, polygon and triangle. It provides an abstract
method draw().
*/
package graph;
import java.util.*;
import java.awt.*;
public abstract class Shapes
{
/**abstract method draw()
@return void
*/
public abstract void draw(java.util.List list, Graphics g);
}
//different implementations of Shape class
class RectangleShape extends Shapes
{
Point sPoint = null;
Point ePoint = null;
public void draw(java.util.List list, Graphics g)
{
Iterator it = list.iterator();
//if the list does not contain the required two points, return.
if(list.size()<2)
{
return;
}
sPoint = (Point)it.next();
ePoint = (Point)it.next();
if(sPoint == null || ePoint == null)
{
return;
}
else
{
g.fillRect((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()),
(int)(ePoint.getY()-sPoint.getY()));
}//end of if
list.clear();
}//end of draw for rectangle
}//rectangle
class OvalShape extends Shapes
{
Point sPoint = null;
Point ePoint = null;
public void draw(java.util.List list, Graphics g)
{
Iterator it = list.iterator();
//if the list does not contain the required two points, return.
if(list.size()<2)
{
return;
}
sPoint = (Point)it.next();
ePoint = (Point)it.next();
if(sPoint == null || ePoint == null)
{
return;
}
else
{
g.fillOval((int)sPoint.getX(), (int)sPoint.getY(), (int)(ePoint.getX()-sPoint.getX()),
(int)(ePoint.getY()-sPoint.getY()));
}//end of if
list.clear();
}//end of draw for Oval
}//OvalShape
class TriangleShape extends Shapes
{
public void draw(java.util.List list, Graphics g)
{
Point point = null;
Iterator it = list.iterator();
//if the list does not contain the required two points, return.
if(list.size()<3)
{
return;
}
Polygon p = new Polygon();
for(int i = 0; i < 3; i++)
{
point = (Point)it.next();
p.addPoint((int)point.getX(), (int)point.getY());
}
g.fillPolygon(p);
list.clear();
}//end of draw for Triangle
}//Triangle
class PolygonShape extends Shapes
{
public void draw(java.util.List list, Graphics g)
{
Point point = null;
Iterator it = list.iterator();
//if the list does not contain the required two points, return.
if(list.size()<3)
{
return;
}
Polygon p = new Polygon();
for(;it.hasNext();)
{
point = (Point)it.next();
p.addPoint((int)point.getX(), (int)point.getY());
}
g.fillPolygon(p);
list.clear();
}//end of draw for Polygon
}//Polygon
現在我們向我們的簡單繪圖工具添加一個面板并重寫我們的 WindowHandler 類,以便它啟用/禁用菜單選擇并將相應的 Shapes 對象傳遞給面板進行繪圖。這是actionPerformedSimpleDrawingTool 和 DrawingPanel 類的更改方法。
public void actionPerformed(ActionEvent e)
{
//check to see if the action command is equal to exit
if(e.getActionCommand().equalsIgnoreCase("exit"))
{
System.exit(0);
}
else if(e.getActionCommand().equalsIgnoreCase("Rectangle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlR)).setEnabled(false);
panel.drawShape(rectangle);
}
else if(e.getActionCommand().equalsIgnoreCase("Circle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlC)).setEnabled(false);
panel.drawShape(oval);
}
else if(e.getActionCommand().equalsIgnoreCase("Triangle"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlT)).setEnabled(false);
panel.drawShape(triangle);
}
else if(e.getActionCommand().equalsIgnoreCase("Polygon"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false);
panel.drawShape(polygon);
}
else if(e.getActionCommand().equalsIgnoreCase("Draw Polygon"))
{
Menu menu = getMenuBar().getMenu(1);
for(int i = 0;i < menu.getItemCount();menu.getItem(i).setEnabled(true),i++);
getMenuBar().getShortcutMenuItem(new MenuShortcut(kControlP)).setEnabled(false);
panel.repaint();
}
else if(e.getActionCommand().equalsIgnoreCase("About"))
{
JOptionPane.showMessageDialog(null, "This small freeware program is written by Yasir Feroze Minhas.", "About", JOptionPane.PLAIN_MESSAGE);
}
}//actionPerformed()
class DrawingPanel extends Panel implements MouseListener
{
private Point sPoint = null;
private Point ePoint = null;
private Shapes shape = null;
private java.util.ArrayList list = new java.util.ArrayList();
//override panel paint method to draw shapes
public void paint(Graphics g)
{
g.setColor(Color.green);
shape.draw(list, g);
}
public void drawShape(Shapes shape)
{
this.shape = shape;
}
//define mouse handler
public void mouseClicked(MouseEvent e)
{
//if user wants to draw triangle, call repaint after 3 clicks
if(shape instanceof TriangleShape)
{
list.add(e.getPoint());
if(list.size() > 2)
{
repaint();
}
}
else if(shape instanceof PolygonShape)
{
list.add(e.getPoint());
}
}//mouseClicked
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
sPoint = e.getPoint();
}//mousePressed
public void mouseReleased(MouseEvent e)
{
ePoint = e.getPoint();
if(ePoint.getX() < sPoint.getX())
{
Point temp = ePoint;
ePoint = sPoint;
sPoint = temp;
}
if(ePoint.getY() < sPoint.getY())
{
int temp = (int)ePoint.getY();
ePoint.y = (int)sPoint.getY();
sPoint.y = temp;
}
if(shape instanceof RectangleShape || shape instanceof OvalShape)
{
list.clear();
list.add(sPoint);
list.add(ePoint);
repaint();
}
}//mouseReleased
}//DrawingPanel
現在我們完成了我們的 SimpleDrawingTool,并且可以使用鼠標在其面板上繪制基本的幾何形狀。然而,這段代碼仍然存在一些問題,我們將在下一版本的 SimpleDrawingTool 中回來重新審視這段代碼,并增強它以包括填充顏色選擇和鼠標移動跟蹤線,同時繪制具有更好菜單的形狀對象選擇選項。
在Java學習中會運用到很的開發工具,大家可都要熟練使用哦。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習