十、CDrawApp类
主程序由CDrawApp类所构成。它包含main()方法,main()方法建立类CDraw的对象,然后调用该对象的run()方法。其中CDraw类属于内部类,当然你也可以将它单独作为一个类文件编辑、编译,其效果是一样的。
其中类与内部类之间的关系,用关联关系来表达,外部类用一个十字交叉圆圈表示,箭头指向内部类。如下图所示:

其代码实现为:
import java.lang.System;
import java.io.DataInputStream;
import java.io.IOException;
//CDrawApp.java
class CDrawApp {
public static void main(String args[]) throws IOException {
CDraw program = new CDraw();
program.run();
}
}
class CDraw {
// Variable declarations
static KeyboardInput kbd = new KeyboardInput(System.in);
BorderedPrintCGrid grid;
// Method declarations
CDraw() {
grid = new BorderedPrintCGrid();
}
void run() throws IOException {
boolean finished = false;
do {
char command = getCommand();
switch(command){
case 'P':
addPoint();
System.out.println();
break;
case 'B':
addBox();
System.out.println();
break;
case 'T':
addText();
System.out.println();
break;
case 'U':
grid.deleteLastObject();
System.out.println();
break;
case 'C':
grid.clearGrid();
System.out.println();
break;
case 'S':
grid.show();
break;
case 'X':
finished = true;
default:
System.out.println();
}
} while (!finished);
}
char getCommand() throws IOException {
System.out.println("CDrawApp P - Add a Point U - Undo Last Add");
System.out.print ("Main Menu B - Add a Box C - Clear Grid");
System.out.println(" X - Exit CDrawApp");
System.out.print (" T - Add Text S - Show Grid ");
System.out.print (" Enter command: ");
System.out.flush();
return Character.toUpperCase(kbd.getChar());
}
void addPoint() throws IOException {
System.out.println("Add Point Menu");
System.out.println(" Location:");
Point p = kbd.getPoint();
System.out.print(" Character: ");
System.out.flush();
char ch = kbd.getChar();
if(ch==' ') ch = '+';
CGPoint cgp = new CGPoint(p,ch);
cgp.addToGrid(grid);
}
void addBox() throws IOException {
System.out.println("Add Box Menu");
System.out.println(" Upper Left Corner:");
Point ul = kbd.getPoint();
System.out.println(" Lower Right Corner:");
Point lr = kbd.getPoint();
System.out.print(" Character: ");
System.out.flush();
char ch = kbd.getChar();
if(ch==' ') ch = '#';
CGBox box = new CGBox(ul,lr,ch);
box.addToGrid(grid);
}
void addText() throws IOException {
System.out.println("Add Text Menu");
System.out.println(" Location:");
Point p = kbd.getPoint();
System.out.print(" Text: ");
System.out.flush();
String text = kbd.getText();
CGText cgt = new CGText(p,text);
cgt.addToGrid(grid);
}
}
主程序CDrawApp类与相应类之间的关系为:

按照本文次序分别编译以上的10个大类,然后运行主程序CdrawApp即可。在程序运行时请注意:当选择增加点、框或者文本串后,选择Show Grid才能出现网格,并显示结果。
本文通过一个具体的程序开发过程,详细说明了如何使用UML类图来设计Java应用程序,使得程序开发可视化,文档标准化,便于相互协作与管理,是Java应用程序开发的方向 。
