有一个简单的工具来绘制基本的几何形状。该Java开发工具是使用 AWT 组件编写的,并详细阐述了诸如内部类、事件处理、多态性和菜单处理等功能。在本文中,我们将逐块逐步执行代码以构建我们的简单绘图工具。
第 1 步:空的类结构
首先,我们从一个空的类结构开始,我们从 java.awt.Frame 类扩展/继承它。我们设置框架的标题和大小并使其可见。
//Title: A Simple Drawing Tool
//Version: 1.0
//Copyright: Copyright © 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();
}
}
第 2 步:添加菜单
接下来,我们将菜单栏附加到我们的绘图工具,并用最少的菜单项对其进行装饰。
//Title: A Simple Drawing Tool
//Version: 1.0
//Copyright: Copyright © 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.ad