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 = "));
panel.add(inputA_text);
panel.add(new JLabel("b = "));
panel.add(inputB_text);
panel.add(new JLabel("c = "));
panel.add(inputC_text);
panel.add(confirm_button);
panel.add(display_label);
confirm_button.addActionListener(this);
inputA_text.addActionListener(this);
inputB_text.addActionListener(this);
inputC_text.addActionListener(this);
setLabel();
this.add(panel, BorderLayout.NORTH);
this.add(canvas, BorderLayout.CENTER);
this.setBounds(50, 50, 800, 600);
this.setVisible(true);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
try
{
a = Double.parseDouble(inputA_text.getText());
b = Double.parseDouble(inputB_text.getText());
c = Double.parseDouble(inputC_text.getText());
}
catch( NumberFormatException Ee )
{
a = 0;
b = 0;
c = 0;
}
canvas.set(a, b, c);
canvas.repaint();
setLabel();
}
public void setLabel()
{
String str = "方程:y = ";
str += a == 0 ? "" : (a == 1 ? " x^2 " : a + "x^2 ");
str += b == 0 ? "" : (a == 0 ? (b == 1 ? " x " : b + "x ") : (b == 1 ? "+ x " : "+" + b
+ "x "));
str += c == 0 ? "" : (a == 0 && b == 0 ? c : "+" + c);
display_label.setText(str);
}
public static void main(String args[])
{
new ParabolaFrame();
}
}
画抛物线的画板类:ParabolaCanvas.java
/**
* 画板类,在上面画抛物线
* @author 黎明你好
*/
class ParabolaCanvas extends Canvas
{
private static final long serialVersionUID = 1L;
double a, b, c;
/** 构造方法,抛物线初始状态 */
public ParabolaCanvas(double a, double b, double c)
{
this.a = a;
this.b = b;
this.c = c;
setBackground(new Color(100, 240, 240));
}
/**
* 设置抛物线系数
* @param a - 二次项系数
* @param b - 一次项系数
* @param c - 常数项
*/
public void set(double a, double b, double c)
{
this.a = a;
this.b = b;
this.c = c;
}
public void paint(Graphics g)
{
Graphics2D g2D = (Graphics2D) g;
// 画坐标系
g2D.drawLine(0, 300, 600, 300);// 横线
g2D.drawLine(300, 0, 300, 600);// 竖线 中心坐标300,300
g2D.drawLine(300, 0, 294, 10);
g2D.drawLine(300, 0, 306, 10);// y轴箭头
g2D.drawLine(600, 300, 590, 294);
g2D.drawLine(600, 300, 590, 306);// x轴箭头
g2D.drawLine(200, 300, 200, 308);
g2D.drawString("- 5", 197, 320);
g2D.drawLine(100, 300, 100, 308);
g2D.drawString("- 10", 97, 320);
g2D.drawLine(400, 300, 400, 308);
g2D.drawString("5", 397, 320);
g2D.drawLine(500, 300, 500, 308);
g2D.drawString("10", 497, 320);
g2D.drawLine(300, 100, 307, 100);
g2D.drawString("10", 310, 103);
g2D.drawLine(300, 200, 307, 200);
g2D.drawString("5", 310, 203);
g2D.drawLine(300, 400, 307, 400);
g2D.drawString("- 5", 310, 403);
g2D.drawLine(300, 500, 307, 500);
g2D.drawString("- 10", 310, 503);
g2D.drawString("0,0", 305, 318);
g2D.drawString("y轴", 310, 15);
g2D.drawString("x轴", 580, 290);
for (int i = 0; i < 600; i += 20)
{
g2D.drawLine(i, 300, i, 303);
g2D.drawLine(300, i, 303, i);
}
// 下面程序为画抛物线
double x0, y0, x1, y1, x2, y2, scale;
x0 = 300;
y0 = 0;
scale = 20.0;
g2D.setColor(Color.RED);
for (x1 = -15; x1 < 15; x1 += 0.001D)
{
y1 = a * x1 * x1 + b * x1 + c;
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
}
}
7.3 利用Graphics2D的平移,缩放,旋转功能。绘制一个六角星。
程序运行结果:
源文件:Work7_3.java
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
/**
* 7.3 利用Graphics2D的平移,缩放,旋转功能。绘制一个六角星。
* @author 黎明你好
*/
public class Work7_3 extends JFrame
{
private static final long serialVersionUID = 1L;
public Work7_3()
{
super("第七章,第三题");
this.add(new SixStarCanvas(80), BorderLayout.CENTER);
this.setBounds(50, 50, 400, 400);
this.setVisible(true);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new Work7_3();
}
}
画六角形的画板类:SixStarCanvas.java
/**
* 画板类,在上面画出六角星
* 通过先画一个三角形,然后旋转6次,得到六角形
* @author 黎明你好
*/
class SixStarCanvas extends Canvas
{
private static final long serialVersionUID = 1L;
/** 六角星外接圆的半径 */
private int radius;
/** 一个三角形三个顶点的x点坐标集 */
private int xPoints[];
/** 一个三角形三个顶点的y点坐标集 */
private int yPoints[];
/**
* 构造方法
* @param r - 初始化外接圆半径
*/
public SixStarCanvas(int r)
{
this.radius = r;
xPoints = new int[] { r, 2 * r, (int) (3 * r / 2) };
yPoints = new int[] { r, r, (int) (r - Math.sqrt(3) * r / 2) };
}
public void paint(Graphics g)
{
Graphics2D g2D = (Graphics2D) g;
BasicStroke bs = new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER);
g2D.setStroke(bs);
AffineTransform trans = new AffineTransform();
trans.translate(10, 10);// 移动
trans.scale(2, 2);// 放大
for (int i = 1; i <= 6; i++)
{
trans.rotate(60.0 * Math.PI / 180, radius, radius);// 旋转
g2D.setTransform(trans);
g2D.drawPolygon(xPoints, yPoints, 3);
}
}
}
7.4 编写画图程序。
程序运行结果:
控制画板的窗口类源文件:PaintFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* 7.4 编写画图程序。
* 控制画板的窗口类
* @author 黎明你好
*/
public class PaintFrame extends JFrame implements ItemListener, ActionListener
{
private static final long serialVersionUID = 1L;
/** 画板 */
private PaintCanvas canvas;
/** 画笔端点装饰,无装饰、圆形装饰、方形装饰 */
private JToggleButton cap_butt, cap_round, cap_square;
/** 橡皮 */
private JToggleButton eraser;
/** 画笔大小 */
private JComboBox width_box;
/** 选择颜色的按钮 */
private JButton selectColor;
/** 单选按钮分组 */
private ButtonGroup group;
private JPanel panel;
private String item[];
private int strokeWidth = 1, strokeCap = 0, strokeJoin = BasicStroke.JOIN_BEVEL;
public PaintFrame()
{
super("画图小程序");
canvas = new PaintCanvas();
selectColor = new JButton(" ");
cap_butt = new JToggleButton("标准");
cap_round = new JToggleButton("圆形");
cap_square = new JToggleButton("方形");
eraser = new JToggleButton("橡皮");
panel = new JPanel();
group = new ButtonGroup();
item = new String[20];
for (int i = 0; i < 20; i++)
{
item[i] = "" + (i + 1);
}
width_box = new JComboBox(item);
width_box.setEditable(true);// 组合框可以输入
cap_butt.setSelected(true);// 笔形,标准为开始默认
canvas.setPenColor(Color.BLACK);
selectColor.setBackground(Color.BLACK);// 画笔颜色,开始为黑色
// 添加监控
width_box.addItemListener(this);
width_box.addActionListener(this);
selectColor.addActionListener(this);
cap_butt.addItemListener(this);
cap_round.addItemListener(this);
cap_square.addItemListener(this);
eraser.addItemListener(this);
// 画笔形式单选按钮
group.add(cap_butt);
group.add(cap_round);
group.add(cap_square);
group.add(eraser);
// 添加按钮
panel.setLayout(new FlowLayout());
panel.setBorder(BorderFactory.createTitledBorder("设置区"));
panel.add(new JLabel("笔形:"));
panel.add(cap_butt);
panel.add(cap_round);
panel.add(cap_square);
panel.add(eraser);
panel.add(width_box);
panel.add(new JLabel(" 颜色:"));
panel.add(selectColor);
this.add(panel, BorderLayout.SOUTH);
this.add(canvas, BorderLayout.CENTER);
this.setBounds(100, 50, 850, 550);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == selectColor)
{
Color c = JColorChooser.showDialog(this, "选择颜色", Color.WHITE);// 用来选择字颜色
selectColor.setBackground(c);
canvas.setPenColor(c);
}
else if (e.getSource() == width_box)
{
try
{
strokeWidth = Integer.parseInt(width_box.getSelectedItem().toString());
}
catch( NumberFormatException e2 )
{
strokeWidth = 1;
}
}
canvas.setStroke(strokeWidth, strokeCap, strokeJoin);// 当在组合框输入画笔宽度时候,设置画笔
}
public void itemStateChanged(ItemEvent e)
{
if (e.getSource() == cap_butt)
{
canvas.setPenColor(Color.black);
strokeCap = BasicStroke.CAP_BUTT;
}
else if (e.getSource() == cap_round)
{
canvas.setPenColor(Color.black);
strokeCap = BasicStroke.CAP_ROUND;
}
else if (e.getSource() == cap_square)
{
canvas.setPenColor(Color.black);
strokeCap = BasicStroke.CAP_SQUARE;
}
else if (e.getSource() == eraser)
{
canvas.setPenColor(Color.white);
canvas.setStroke(strokeWidth, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL);
}
else if (e.getSource() == width_box)// 当在组合框里面选择画笔宽度时候,设置画笔宽度
{
try
{
strokeWidth = Integer.parseInt(width_box.getSelectedItem().toString());
}
catch( NumberFormatException e2 )
{
strokeWidth = 1;
}
}
canvas.setStroke(strokeWidth, strokeCap, strokeJoin);
}
public static void main(String args[])
{
new PaintFrame();
}
}
用来画图的画板类:PaintCanvas
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
/**
* 画板类,在上面作图。
* @author 黎明你好
*/
public class PaintCanvas extends Canvas implements MouseMotionListener, MouseListener
{
private static final long serialVersionUID = 1L;
private int x = -1, y = -1;
private int w = 800, h = 600;// 画布大小
private Color penColor;// 画笔颜色
private BufferedImage image;
private Graphics2D g2d;
private BasicStroke bs;// 画笔
public PaintCanvas()
{
bs = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
g2d = image.createGraphics();
penColor = Color.BLACK;
g2d.fillRect(0, 0, w, h);//初始画个白色的矩形
g2d.setColor(penColor);
this.addMouseMotionListener(this);
this.addMouseListener(this);
}
/**
* 设置画笔颜色
* @param c - 设置成的颜色
*/
public void setPenColor(Color c)
{
penColor = c;
}
/**
* 设置画笔
* @param width - BasicStroke 的宽度
* @param cap - BasicStroke 端点的装饰
* @param join - 应用在路径线段交汇处的装饰
*/
public void setStroke(int width, int cap, int join)
{
try
{
bs = new BasicStroke(width, cap, join);
}
catch( IllegalArgumentException ee )
{
bs = null;
}
}
/** 鼠标按键在组件上按下时调用。 */
public void mousePressed(MouseEvent e)
{
x = (int) e.getX();
y = (int) e.getY();
this.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));// 设置鼠标形状十字光标类型
g2d.drawLine(x, y, x, y);
this.repaint();
}
/** 鼠标按钮在组件上释放时调用。 */
public void mouseReleased(MouseEvent e)
{
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));// 设置鼠标形状默认光标类型
}
/** 鼠标按键在组件上按下并拖动时调用 */
public void mouseDragged(MouseEvent e)
{
int x2 = (int) e.getX();
int y2 = (int) e.getY();
if (x != -1 && y != -1)
{
if (penColor != null)
g2d.setColor(penColor);
if (bs != null)
g2d.setStroke(bs);
g2d.drawLine(x, y, x2, y2);
this.repaint();
}
x = x2;
y = y2;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
}
public void paint(Graphics g)
{
g.drawImage(image, 0, 0, this); // 将内存中的图像iamge绘制在画布上
}
public void update(Graphics g)
{
paint(g);
}
}
7.5 输入二次曲线的系数,画出二次曲线
程序运行结果:
主窗口源文件:ConicFrame
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* 输入二次曲线的系数以及区间,画出二次曲线
* @author 黎明你好
*/
public class ConicFrame extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private String helpString = "三种基本曲线方程:\\n1:椭圆(e<0); 2:双曲线(c<0,e<0); 3:抛物线(a=0或c=0);";
private BorderLayout borderLayout;// JFrame的布局
private JTextField inputA_text, inputB_text, inputC_text, inputD_text, inputE_text; // 三个文本框,接收方程系数
private JButton confirm_button, clean_button;// 确定按钮
private JPanel control_panel, north_panel;// 放置输入文本框,确定按钮,显示方程label
private DrawConicCanvas canvas;
private double a = 1, b = 1, c = 1, d = 1, e = 1;//二次曲线线三个系数
/**
* 构造方法
*/
public ConicFrame()
{
super("第七章,第五题,二次曲线");
borderLayout = new BorderLayout(5, 5);
inputA_text = new JTextField("", 3);
inputB_text = new JTextField("", 3);
inputC_text = new JTextField("", 3);
inputD_text = new JTextField("", 3);
inputE_text = new JTextField("", 3);
confirm_button = new JButton("确定");
clean_button = new JButton("清空");
control_panel = new JPanel();
north_panel = new JPanel();
canvas = new DrawConicCanvas();
control_panel.setBackground(Color.PINK);
confirm_button.addActionListener(this);
clean_button.addActionListener(this);
north_panel.setLayout(new GridLayout(2, 1));
control_panel.add(new JLabel("二次曲线方程:a"));
control_panel.add(inputA_text);
control_panel.add(new JLabel("X^2 + b"));
control_panel.add(inputB_text);
control_panel.add(new JLabel("X + c"));
control_panel.add(inputC_text);
control_panel.add(new JLabel("Y^2 + d"));
control_panel.add(inputD_text);
control_panel.add(new JLabel("Y + e"));
control_panel.add(inputE_text);
control_panel.add(new JLabel(" = 0"));
control_panel.add(confirm_button);
control_panel.add(clean_button);
north_panel.add(new JLabel(helpString, JLabel.CENTER));
north_panel.add(control_panel);
this.setLayout(borderLayout);
this.add(north_panel, BorderLayout.NORTH);
this.add(canvas, BorderLayout.CENTER);
this.add(new JLabel(" "), BorderLayout.SOUTH);
this.add(new JLabel(" "), BorderLayout.WEST);
this.add(new JLabel(" "), BorderLayout.EAST);
this.setBounds(50, 50, 800, 600);
this.setVisible(true);
this.validate();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent args)
{
if (args.getSource() == confirm_button)
{
try
{
a = Double.parseDouble(inputA_text.getText());
b = Double.parseDouble(inputB_text.getText());
c = Double.parseDouble(inputC_text.getText());
d = Double.parseDouble(inputD_text.getText());
e = Double.parseDouble(inputE_text.getText());
}
catch( NumberFormatException Ee )
{
JOptionPane.showMessageDialog(this, "输入非数字字符\\n请修改", "错误警告",
JOptionPane.ERROR_MESSAGE);
}
canvas.set(a, b, c, d, e);
canvas.repaint();
}
else if(args.getSource() == clean_button)
{
inputA_text.setText("");
inputB_text.setText("");
inputC_text.setText("");
inputD_text.setText("");
inputE_text.setText("");
}
}
public static void main(String[] args)
{
new ConicFrame();
}
}
面二次曲线的画板类: DrawConicCanvas.java
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
/**
* 画二次曲线的画布类
* @author 黎明你好
*/
public class DrawConicCanvas extends Canvas
{
private static final long serialVersionUID = 1L;
/** 方程的5个系数,ax^2 + bx + cy^2 + dy + e = 0 */
private double a, b, c, d, e;
/** 二次曲线的区间 */
private double min = -15, max = 15;// 如果需要控制区间,可以对这两值进行设置
/** 构造方法,二次曲线初始状态 */
public DrawConicCanvas()
{
setBackground(new Color(100, 240, 240));
}
/**
* 设置方程系数
*/
public void set(double a, double b, double c, double d, double e)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
public void paint(Graphics g)
{
Graphics2D g2D = (Graphics2D) g;
// 画坐标系
g2D.drawLine(0, 300, 600, 300);// 横线
g2D.drawLine(300, 0, 300, 600);// 竖线 中心坐标300,300
g2D.drawLine(300, 0, 294, 10);
g2D.drawLine(300, 0, 306, 10);// y轴箭头
g2D.drawLine(600, 300, 590, 294);
g2D.drawLine(600, 300, 590, 306);// x轴箭头
g2D.drawLine(200, 300, 200, 308);
g2D.drawString("- 5", 197, 320);
g2D.drawLine(100, 300, 100, 308);
g2D.drawString("- 10", 97, 320);
g2D.drawLine(400, 300, 400, 308);
g2D.drawString("5", 397, 320);
g2D.drawLine(500, 300, 500, 308);
g2D.drawString("10", 497, 320);
g2D.drawLine(300, 100, 307, 100);
g2D.drawString("10", 310, 103);
g2D.drawLine(300, 200, 307, 200);
g2D.drawString("5", 310, 203);
g2D.drawLine(300, 400, 307, 400);
g2D.drawString("- 5", 310, 403);
g2D.drawLine(300, 500, 307, 500);
g2D.drawString("- 10", 310, 503);
g2D.drawString("0,0", 305, 318);
g2D.drawString("y轴", 310, 15);
g2D.drawString("x轴", 580, 290);
for (int i = 0; i < 600; i += 20)
{
g2D.drawLine(i, 300, i, 303);
g2D.drawLine(300, i, 303, i);
}
// 下面程序为画二次曲线
double x0, y0, x1, y1 = 0, x2, y2, scale;
max = 15;
min = -15;
x0 = 300;
y0 = 0;
scale = 20.0;
g2D.setColor(Color.RED);
if (a == 0 && c != 0)// 抛物线,水平
{
if (b > 0)// 确定抛物线x轴的最大值,最小值
{
max = d * d / (4 * b * c) - e / b;
}
if (b < 0)
{
min = d * d / (4 * b * c) - e / b;
}
for (x1 = min; x1 <= max; x1 += 0.001D)
{
y1 = Math.sqrt(d * d / (4 * c * c) - b * x1 / c - e / c) - d / (2 * c);
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
for (x1 = min; x1 <= max; x1 += 0.001D)
{
y1 = -Math.sqrt(d * d / (4 * c * c) - b * x1 / c - e / c) - d / (2 * c);
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
}
else if (a != 0 && c == 0)// 抛物线,垂直
{
for (x1 = -15; x1 <= 15; x1 += 0.001D)
{
y1 = (a * x1 * x1 + b * x1 + e) / d;
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
}
else if (a == 0 && c == 0)// 直线方程
{
if (d != 0)
{
for (x1 = -15; x1 <= 15; x1 += 0.001D)
{
y1 = -(e + b * x1) / d;
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
}
if (b != 0)
{
for (y1 = -15; y1 <= 15; y1 += 0.001D)
{
x1 = -(e + d * y1) / d;
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
}
}
else if (e < 0) // 椭圆,双曲线方程
{
System.out.println("椭圆,双曲线");
double r = Math.sqrt(b * b / (4 * a * a) + d * d / (4 * a * c) - e / a);//横轴的半径
double unmin = 0,unmax = 0;//双曲线的时候点x取不到值得区间径
System.out.println("横轴半径" + r);
if (c > 0)// 椭圆的时候,计算半径,并确定x区间
{
max = r - b/(2*a);
min = -r - b/(2*a) ;
}
else
{
unmin = -r - b/(2*a);
unmax = r - b/(2*a);
}
for (x1 = min; x1 <= max; x1 += 0.001D)
{
if (c < 0 && ( x1 > unmin && x1 < unmax ))// 是双曲线的时候,不画点x取不到值得区间
continue;
y1 = Math.sqrt(b*b / (4 * a * c) + d*d / (4 * c * c) - e / c - a * (x1 + b / (2 * a)) * (x1 + b / (2 * a)) / c) - d / (c * 2);
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
for (x1 = min; x1 <= max; x1 += 0.001D)
{
if (c < 0 && ( x1 > unmin && x1 < unmax ))// 是双曲线的时候,不画点x取不到值得区间
continue;
y1 = -Math.sqrt(b*b / (4 * a * c) + d*d / (4 * c * c) - e / c - a * (x1 + b / (2 * a))* (x1 + b / (2 * a)) / c) - d / (c * 2);
x2 = x0 + x1 * scale;
y2 = y0 + y1 * scale;
g2D.fillOval((int) x2, 300 - (int) y2, 2, 2);
}
}
}
}
7.6. 写音乐播放器,只能播放wav,mid格式的。
程序运行结果:
音乐播放器源文件:AudioClipFrame.java
import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.applet.*;
import javax.swing.filechooser.FileFilter;
/**
* 编写音乐播放器,只能播放wav,mid格式的。
* @author 黎明你好
*/
public class AudioClipFrame extends JFrame implements ItemListener, ActionListener
{
private static final long serialVersionUID = 1L;
/** 组合框,用于存储音频列表 */
private JComboBox comboBox;
/** 添加音频时,选择文件的文件对话框 */
private JFileChooser filedialog;
/** 按钮:播放、循环、停止、添加、删除 */
private JButton play_button, loop_button, stop_button, open_button, del_button;
/** 显示当前播放音频的label */
private JLabel message_label;
/** 布局用的panel */
private JPanel list_panel, control_panel;
/** 存储添加的音频文件的绝对路径 */
private File fileArray[] = new File[100];
/** 播放用的类 */
private AudioClip clip = null;
/** 用来存储当前播放文件的文件名 */
private String fileName;
public AudioClipFrame()
{
super("音乐播放器 - 第七章,第六题");
filedialog = new JFileChooser("F:\\\钢琴曲\\\\midi");
filedialog.addChoosableFileFilter(new MyFileFilter("wav"));
filedialog.addChoosableFileFilter(new MyFileFilter("mid"));
list_panel = new JPanel();
control_panel = new JPanel();
comboBox = new JComboBox();
open_button = new JButton("添加");
del_button = new JButton("删除");
play_button = new JButton("播放");
loop_button = new JButton("循环");
stop_button = new JButton("停止");
message_label = new JLabel("请添加音频文件");
message_label.setHorizontalAlignment(JLabel.CENTER);
fileArray[0] = null;
comboBox.addItem("");
comboBox.setEditable(false);
comboBox.addItemListener(this);
open_button.addActionListener(this);
del_button.addActionListener(this);
play_button.addActionListener(this);
stop_button.addActionListener(this);
loop_button.addActionListener(this);
list_panel.setLayout(new BorderLayout());
list_panel.add(comboBox, BorderLayout.CENTER);
list_panel.setBorder(BorderFactory.createTitledBorder("音频列表"));
control_panel.add(open_button);
control_panel.add(del_button);
control_panel.add(play_button);
control_panel.add(stop_button);
control_panel.add(loop_button);
control_panel.setBorder(BorderFactory.createTitledBorder("控制按钮"));
this.setLayout(new BorderLayout(20, 10));
this.add(message_label, BorderLayout.NORTH);
this.add(list_panel, BorderLayout.CENTER);
this.add(control_panel, BorderLayout.SOUTH);
this.setBounds(300, 200, 450, 190);
this.setVisible(true);
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
this.validate();
}
/**
* 设置播放的音频文件
* @param file - 音频文件
*/
public void setClipName(File file)
{
if (file != null)
{
try
{
fileName = file.getName();
URL url = file.toURI().toURL();
clip = Applet.newAudioClip(url);
}
catch( MalformedURLException eee )
{
System.out.println("URL错误");
}
}
}
public void itemStateChanged(ItemEvent e)
{
if (e.getSource() == comboBox)
{
int i = comboBox.getSelectedIndex();// 用选中的item序号的对应的文件,设置音频文件
if (i >= 0 && fileArray[i] != null)
{
setClipName(fileArray[i]);
}
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == open_button)
{
int result;
filedialog.setDialogTitle("打开文件");
result = filedialog.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION)
{
int max = comboBox.getItemCount();// 取comboBox列表中的项数
fileArray[max] = filedialog.getSelectedFile();// 把选中的文件复制到对应的文件数组中
comboBox.addItem(fileArray[max].getName());// 把选中的文件添加到comboBox组合框中
comboBox.setSelectedIndex(max); // 把刚添加的文件,设置成当前显示
message_label.setText("成功添加:" + fileArray[max].getName());
}
}
else if (e.getSource() == del_button)
{
int index = comboBox.getSelectedIndex();// 返回指定索引处的列表项
if (index >= 1)
{
comboBox.removeItemAt(index); // 删除指定索引处的列表项
message_label.setText("删除了:" + fileArray[index].getName());
for (int i = index; i < comboBox.getItemCount(); i++)
{
fileArray[i] = fileArray[i + 1];// 从删除位置开始,把后面文件前移
}
}
}
else if (e.getSource() == play_button)
{
if (clip != null)
{
message_label.setText("正在播放:" + fileName);
clip.stop();
clip.play();
}
}
else if (e.getSource() == loop_button)
{
message_label.setText("循环播放:" + fileName);
clip.loop();
}
else if (e.getSource() == stop_button)
{
message_label.setText(" ");
clip.stop();
}
}
public static void main(String args[])
{
new AudioClipFrame();
}
}
文件筛选类源文件:MyFileFilter.java
/**
* 文件筛选类
* @author 黎明你好
*/
class MyFileFilter extends FileFilter
{
String postfix;
MyFileFilter(String t)
{
postfix = t;
}
public boolean accept(File file)
{
if (file.isDirectory())
return true;
String fileName = file.getName();
int index = fileName.lastIndexOf('.');
if (index > 0 && index < fileName.length() - 1)
{
String extension = fileName.substring(index + 1).toLowerCase();
if (extension.equals(postfix))
return true;
}
return false;
}
public String getDescription()
{
if (postfix.equals("wav"))
return "Wav 音频文件(*.wav)";
return "*." + postfix + "文件";
}
}