/**
* 对话框
*
* @time 11:09:20 AM
* @author retacn yue
* @Email zhenhuayue@sina.com
*/
public class Test_Dialog extends Frame {
private static final long serialVersionUID = 1L;
TextField rows = new TextField("3");
TextField cols = new TextField("3");
/**
* 构造器
*
* @param owner
*/
public Test_Dialog() {
setTitle("Dialog Test");
// 实例化面板
Panel panel = new Panel();
panel.setLayout(new GridLayout(2, 2));
panel.add(new Label("Row", Label.CENTER));
panel.add(rows);
panel.add(new Label("Columns", Label.CENTER));
panel.add(cols);
// 将面板添加到帧窗口
add("North", panel);
add("South", new Button("GO"));
}
public boolean handleEvent(Event event) {
if (event.id == Event.WINDOW_DESTROY) {
System.exit(0);
} else {
return super.handleEvent(event);
}
return true;
}
public boolean action(Event event, Object object) {
if (object.equals("GO")) {
// 弹绘制差图对话框
Dialog dialog = new TestDialog(this, Integer.parseInt(rows.getText()), Integer.parseInt(cols.getText()));
dialog.show();
} else {
return super.action(event, object);
}
return true;
}
public static void main(String[] args) {
Test_Dialog dialog = new Test_Dialog();
dialog.resize(200, 100);
dialog.show();
}
}
/**
* 自定义对话框
*/
class TestDialog extends Dialog {
private static final long serialVersionUID = 1L;
static final int BLANK = 0;
static final int XX = 1;
static final int OO = 2;
int turn = XX;
public TestDialog(Frame frame, int w, int h) {
super(frame, "", false);
setLayout(new GridLayout(w, h));
// 添加自定义按钮
for (int i = 0; i < w * h; i++) {
add(new TestButton(this));
resize(w * 50, h * 50);
}
}
@Override
public boolean handleEvent(Event evt) {
if (evt.id == Event.WINDOW_DESTROY) {
dispose();
} else {
return super.handleEvent(evt);
}
return true;
}
}
/**
* 自定义按钮
*/
class TestButton extends Canvas {
private static final long serialVersionUID = 1L;
int state = TestDialog.BLANK;
TestDialog parentDialog;
/**
* 构造器
*/
TestButton(TestDialog parent) {
this.parentDialog = parent;
}
@Override
public void paint(Graphics g) {
int x1 = 0;
int y1 = 0;
int x2 = size().width - 1;
int y2 = size().height - 1;
// 画矩形
g.drawRect(x1, y1, x2, y2);
x1 = x2 / 4;
y1 = y2 / 4;
int wide = x2 / 2;
int high = y2 / 2;
// 画差
if (state == TestDialog.XX) {
g.drawLine(x1, y1, x1 + wide, y1 + high);
g.drawLine(x1, y1 + high, x1 + wide, y1);
}
// 画圈
if (state == TestDialog.OO) {
g.drawOval(x1, y1, x1 + wide / 2, y1 + high / 2);
}
}
// 按下画圈或是画差
@Override
public boolean mouseDown(Event evt, int x, int y) {
if (state == TestDialog.BLANK) {
//
state = parentDialog.turn;
parentDialog.turn = (parentDialog.turn == TestDialog.XX ? TestDialog.OO : TestDialog.XX);
} else {
state = (state == TestDialog.XX ? TestDialog.OO : TestDialog.XX);
}
// 重绘
repaint();
return true;
}
}