随机绘制多边形图案

 

package result;

 

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

 

public class F8 extends JFrame {
JButton j1 = new JButton("确定");
JTextField j2 = new JTextField(6);

 

public F8() {
super("多边形绘制");
setSize(400, 300);
setVisible(true);
setBackground(Color.cyan);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
add(new JLabel("请输入边数:"));
add(j2);
add(j1);
MyCanvas myCanvas = new MyCanvas();
add(myCanvas);
j1.addActionListener(new ActionListener() {

 

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int N = Integer.parseInt(j2.getText());
int x[] = new int[N];
int y[] = new int[N];
for (int i = 0; i < N; i++) {
x[i] = (int) (Math.random() * 200);
y[i] = (int) (Math.random() * 200);
}
try {
myCanvas.setPolygon(x, y, N);
} catch (Exception e2) {
// TODO: handle exception
System.out.println("不能输入" + N);
}
myCanvas.repaint();
}
});
validate();
}

 

public static void main(String[] args) {
new F8();
}
}

 

//异常类
class IException extends Exception {
IException(String string) {
System.out.println(string);
}
}

 

class MyCanvas extends Canvas {
// 数据成员
int N = 15;// 重复使用,即当初始,又当边数
int x[] = new int[N];
int y[] = new int[N];

 

// 成员方法
public MyCanvas() {
setSize(300, 200);
setBackground(Color.green);
}

 

public void setPolygon(int[] x, int[] y, int N) throws IException {
if (N == 0 || N == 1 || N == 2) {
IException ie = new IException("没有" + N + "边形,输入错误");
throw ie;
}
this.N = N;
for (int i = 0; i < N; i++) {
this.x[i] = x[i];
this.y[i] = y[i];
}
}

 

public void paint(Graphics g) {
g.drawPolygon(x, y, N);
}
}

 

 

posted @ 2020-09-16 14:55  nanfengnan  阅读(191)  评论(0编辑  收藏  举报