Глава 3
Задача 3.21 "Девять точек. "
Напишите программу, которая соединяет девять точек, расположенных как указано на рисунке, четыремя прямыми линиями, "не отрывая карандаша от бумаги".
Решение
Три внутренних цикла for рисуют три точки в линию. Внешний цикл for повторяет эту линию три раза, смещая их координаты. Ну а затем, чертим четыре линии!
Код программы:
import java.awt.*;
import java.awt.event.*;
class NinePoints extends Frame {
NinePoints () {
add ("Center", new Points());
// Enable the program to end when the window is closed
addWindowListener(new WindowAdapter () {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Set the frame's title and size and activate the drawing
// described by the paint method.
setTitle ("NinePoints");
setSize (300, 200);
setVisible (true);
}
public static void main (String [ ] args) {
new NinePoints ();
}
}
class Points extends Canvas {
public void paint (Graphics g) {
int x,y,width,height;
int center_x = 60;
int center_y = 60;
int radius = 5;
int m = 30;
for(int j=0;j<3;j++){
for(int i=0;i<3;i++){
x=(center_x-radius);
y=(center_y-radius);
width=2*radius;
height=2*radius;
g.setColor (Color.red);
g.drawOval(x,y,width,height);
g.fillOval(x,y,width,height);
center_x =center_x +m;
}
center_x =center_x - m;
center_x =center_x - m;
center_x =center_x - m;
center_y = center_y+m;
}
center_x = 0;
center_y = 0;
center_x = 60;
center_y = 60;
g.setColor (Color.black);
g.drawLine(center_x,center_y,(center_x+2*m),(center_y+2*m));
g.drawLine((center_x+2*m),(center_y+2*m),(center_x+2*m),(center_y-m));
g.drawLine((center_x+2*m),(center_y-m),(center_x-m),(center_y+2*m));
g.drawLine((center_x-m),(center_y+2*m),(center_x+2*m),(center_y+2*m));
// Label the drawing
g.setColor (Color.black);
g.drawString("Germany",100,180);
}
}
Результат :
Назад |
Начало урока |
Вверх |
Вперед
Содержание