繪製n邊形:用兩個以上的控件來控制矩形的顏色、大小、位置及空實心。(n由鍵盤輸入)java
package lzy.di9zhang;ide
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;this
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;spa
public class Shiyan4 extends JFrame implements ActionListener, FocusListener {
private JLabel jl;
private JTextField jtf;
private JButton jb;
private JPanel jp2;
private MyPanel mp;orm
public Shiyan4() {
jl = new JLabel("請輸入正多邊形的邊數:");
jtf = new JTextField(10);
jtf.addFocusListener(this);
jb = new JButton("肯定");
jb.addActionListener(this);
mp = new MyPanel();
jp2 = new JPanel();
jp2.add(jl);
jp2.add(jtf);
jp2.add(jb);
this.add(mp);
this.add(jp2, BorderLayout.SOUTH);
this.setSize(500, 500);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}blog
public static void main(String[] args) {
Shiyan4 shiyan4 = new Shiyan4();
}get
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jb) {
String bianshu = jtf.getText();
mp.bianshu = Integer.parseInt(bianshu);
mp.repaint();
}
}io
@Override
public void focusGained(FocusEvent e) {
if (e.getSource() == jtf) {
jtf.setText("");
}
}event
public void focusLost(FocusEvent e) {
}
}form
class MyPanel extends JPanel {
int bianshu;
private int bianshuMax = 20;
private int[] x = new int[bianshuMax];
private int[] y = new int[bianshuMax];
MyPolygon mplg = new MyPolygon(x, y);
public void paint(Graphics g) {
g.clearRect(0, 0, this.getWidth(), this.getHeight());//由於repaint不調用update,因此本身清空面板
if (bianshu <= bianshuMax) {
mplg.posOfPoint(bianshu);
g.drawPolygon(x, y, bianshu);
} else {
bianshuMax += 20;
x = new int[bianshuMax];
y = new int[bianshuMax];
mplg = new MyPolygon(x, y);
paint(g);
}
}
}
class MyPolygon {// 求正多邊形的頂點座標
private int[] x;
private int[] y;
private int startX;// 頂點的X座標
private int startY;// 頂點的Y座標
private int r;// 外接圓的半徑
public MyPolygon(int[] x, int[] y) {
this.x = x;
this.y = y;
startX = 200;
startY = 10;
r = 200;
}
public void posOfPoint(int bianshu) {
x[0] = startX;
y[0] = startY;
Point p = new Point();
for (int i = 1; i < bianshu; i++) {
p = nextPoint(((2 * Math.PI) / bianshu) * i);
x[i] = p.x;
y[i] = p.y;
}
}
public Point nextPoint(double arc) {// arc爲弧度,在頂點處創建直角座標系,用r和arc肯定下一個點的座標
Point p = new Point();
p.x = (int) (x[0] - r * Math.sin(arc));
p.y = (int) (y[0] + r - r * Math.cos(arc));
return p;
}
}
核心代碼:
public Point nextPoint(double arc) {// arc爲弧度,在頂點(x[0],y[0])處創建直角座標系,
//用 r 和 arc 肯定下一個點的座標。
Point p = new Point();
p.x = (int) (x[0] - r * Math.sin(arc));
p.y = (int) (y[0] + r - r * Math.cos(arc));
return p;
}
運行界面: