自考JAVA语言程序设计(一)课后习题答案和源代码(第七章)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
第七章
7.1 编写一个应用程序,绘制一个五角星。
程序运行结果:
源文件:Work7_1.java
import java.awt.*;
import javax.swing.*;
/**
*7.1画一个五角星
*@author黎明你好
*/
public class Work7_1
{
public static void main(String args[])
{
JFrame win = new JFrame("第七章,第一题");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setBounds(50, 50, 210, 250);
win.add(new FiveStarCanvas(100), BorderLayout.CENTER);
win.setVisible(true);
win.validate();
}
}
画板类源文件: FiveStarCanvas.java
/**
*画板类,在上面画出五角星
*@author黎明你好
*/
class FiveStarCanvas extends Canvas
{
private static final long serialVersionUID = 1L;
/**五角星外接圆的半径*/
private int radius;
/**
*构造方法
*@param r-初始化外接圆半径
*/
public FiveStarCanvas(int r)
{
this.radius = r;
}
public void paint(Graphics g)
{
int ax = radius; int ay = 0;
int bx = (int) (radius * (1 - Math.cos((18 * Math.PI) / 180)));
int cx = (int) (radius * (1 + Math.cos((18 * Math.PI) / 180)));
int dx = (int) (radius * (1 - Math.cos((54 * Math.PI) / 180)));
int ex = (int) (radius * (1 + Math.cos((54 * Math.PI) / 180)));
int by = (int) (radius * (1 - Math.sin((18 * Math.PI) / 180)));
int cy = (int) (radius * (1 - Math.sin((18 * Math.PI) / 180)));
int dy = (int) (radius * (1 + Math.sin((54 * Math.PI) / 180)));
int ey = (int) (radius * (1 + Math.sin((54 * Math.PI) / 180)));
g.setColor(Color.RED);
g.drawLine(dx, dy, ax, ay);
g.drawLine(ax, ay, ex, ey);
g.drawLine(ex, ey, bx, by);
g.drawLine(bx, by, cx, cy);
g.drawLine(cx, cy, dx, dy);
g.setColor(Color.BLUE);
g.drawOval(0, 0, 2 * radius, 2 * radius);
g.drawLine(radius, radius, ax, ay);
g.drawLine(radius, radius, bx, by);
g.drawLine(radius, radius, cx, cy);
g.drawLine(radius, radius, dx, dy);
g.drawLine(radius, radius, ex, ey);
}
}
7.2 用Graphics2D绘制一条抛物线,设抛物线方程的系数从图形界面输入。
程序运行结果:
frame源文件:ParabolaFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*7.2用Graphics2D画抛物线,抛物线方程的系数从图形界面输入.
*@author黎明你好
*/
public class ParabolaFrame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private ParabolaCanvas canvas;// 画出抛物线的花瓣
private JTextField inputA_text, inputB_text, inputC_text; // 三个文本框,接收方程系数
private JButton confirm_button;// 确定按钮
private JLabel display_label;
private JPanel panel;// 布局面板
private double a, b, c;// 抛物线三个系数
public ParabolaFrame()
{
super("第七章,第二题");
a = 1;
b = 0;
c = 0;
panel = new JPanel();
canvas = new ParabolaCanvas(a, b, c);
inputA_text = new JTextField("" + a, 3);
inputB_text = new JTextField("" + b, 3);
inputC_text = new JTextField("" + c, 3);
confirm_button = new JButton("确定");
display_label = new JLabel();
panel.add(new JLabel("a = "));