Java学习笔记(图形)
- 学习说明
- 第十五章 图形
- 图形坐标系
- Graphics类
- 绘制字符串、直线、矩形、椭圆
- 实例讲解:FigurePanel类
- 绘制弧形
- 绘制多边形和折线段
-
- 使用FontMetrics类使字体居中
- 案例:MessagePanel类
- 案例:StillClock
- 显示图像
- ImageViewer类实例讲解
学习说明
要点:
了解图形坐标系的概念(以窗体左上角进行定位)
熟悉Graphics类的常用函数及属性
熟悉基本的绘图步骤
熟悉绘制字符串、线段、矩形、椭圆的方法
熟悉绘制弧形的方式(以绘制转动的小风车为例)
熟悉绘制折线
熟悉使字体居中的方式
熟悉显示图像的方法
学习资料为:《Java语言程序设计》梁勇
第十五章 图形
图形坐标系
相较于左上角的点进行定位
public static void main(String[] args) {
JButton jbtn = new JButton("OK");
JFrame frame = new JFrame();
frame.add(jbtn);
frame.setTitle("");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
System.out.println(jbtn.getX());
System.out.println(jbtn.getY());
}
Graphics类
常用的属性及方法
setColor
setFont
drawString
drawLine
drawRecct
FillRect
drawRoundRect
fillRoundRect
draw3DRect
drawOval
fillOval
drawArc
fillArc
drawPloygon(有重载)
fillPloygon(有重载)
drawPloyline
// 将JPanel添加到JFame窗口内
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new NewPanel());
frame.setTitle("Test Paint Components");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// 这里选择继承JPanel类,和调用super方法是因为直接创建Graphics对象需要实现太多函数了;推荐采用JPanel作为画布
class NewPanel extends JPanel{
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.drawLine(0, 0, 50, 50);
graphics.drawString("Banana", 0, 40);
}
}
绘制字符串、直线、矩形、椭圆
绘制直线和字符串在上面演示过了,当然,只是最简单的演示
drawString(String s, int x, int y) 绘制从(x, y)点开始的字符串(默认水平绘制)
drawLine(int x1, int y1, int x2, int y2) 绘制两点形成的线段
// 绘制矩形,(30, 40)为左上角,100为宽度,80为高度
graphics.drawRect(30, 40, 100, 80);
// 绘制填充矩形,默认黑色填充,(130, 130)为左上角坐标,200为宽度,160为高度
graphics.fillRect(130, 130, 200, 160);
// 绘制带圆角矩形,(30, 30)为左上角坐标,300为宽度,200为高度,后面的为椭圆的长轴与短轴的长度,此时就是一个规整的椭圆,当长宽相等时,就是圆了
graphics.drawRoundRect(30, 30, 300, 200, 300, 200);
graphics.drawRoundRect(30, 30, 300, 300, 300, 300); // 此时变成了圆
// 绘制椭圆,(30, 30)为左上角坐标,200为长轴长度,140为短轴长度
graphics.drawOval(30, 30, 200, 140);
// 和上面的椭圆长得一样,就是默认是黑色的填充椭圆
graphics.fillOval(30, 30, 200, 140);
实例讲解:FigurePanel类
// 创建绘图类
public class FigurePanel extends JPanel {
public final static int LINE = 1;
public final static int RECTANGLE = 2;
public final static int ROUND_RECTANGLE = 3;
public final static int OVAL = 4;
private int type = 1;
private boolean filled = false;
public FigurePanel() {
// TODO Auto-generated constructor stub
}
public FigurePanel(int type) {
// TODO Auto-generated constructor stub
this.type = type;
}
public FigurePanel(int type, boolean filled) {
// TODO Auto-generated constructor stub
this.type = type;
this.filled =filled;
}
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
// 这个地方的 getWidth 函数调用得到JFame主窗口的宽度大小
int width = getWidth();
int height = getHeight();
switch (type) {
case LINE:
graphics.setColor(Color.BLACK);
graphics.drawLine(10, 10, width - 10, height - 10);
graphics.drawLine(width - 10, 10, 10, height - 10);
break;
case RECTANGLE:
graphics.setColor(Color.BLUE);
if(filled)
graphics.fillRect((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height));
else
graphics.drawRect((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height));
break;
case ROUND_RECTANGLE:
graphics.setColor(Color.RED);
if(filled)
graphics.fillRoundRect((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height), 20, 20);
else
graphics.drawRoundRect((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height), 20, 20);
break;
case OVAL:
graphics.setColor(Color.BLACK);
if(filled)
graphics.fillOval((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height));
else
graphics.drawOval((int)(0.1 * width), (int)(0.1 * height), (int)(0.8 * width), (int)(0.8 * height));
break;
default:
break;
}
}
public int getType() {
return type;
}
// 这个地方的 repaint 函数是Component类中定义的,调用后会自动调用 paintComponent 函数,以重新绘制
public void setType(int type) {
this.type = type;
repaint();
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
repaint();
}
// 这个方法的用途还没搞明白,表示获得期望的尺寸,似乎并没有发挥啥作用
public Dimension getPreferredSize() {
return new Dimension(80, 80);
}
}
// 测试主函数
public class TestFigurePanel extends JFrame {
public static void main(String[] args) {
TestFigurePanel frame = new TestFigurePanel();
frame.setTitle("Test Figure Panel");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// 统一进行构造函数内书写组件的添加等操作,放在 main 函数里面,显得太过复杂
public TestFigurePanel() {
// TODO Auto-generated constructor stub
setLayout(new GridLayout(2, 3, 5, 5));
add(new FigurePanel(FigurePanel.LINE));
add(new FigurePanel(FigurePanel.RECTANGLE));
add(new FigurePanel(FigurePanel.ROUND_RECTANGLE));
add(new FigurePanel(FigurePanel.OVAL));
add(new FigurePanel(FigurePanel.RECTANGLE, true));
add(new FigurePanel(FigurePanel.ROUND_RECTANGLE, true));
}
}
绘制弧形
drawArc
fillArc
// (30, 30)表示左上角坐标(这个左上角是按照矩形进行确定的),100表示椭圆长轴,80表示短轴,20为起始角度,160为弧形的角度;这里的角度按照一般的极坐标思想计算
// 所以这里成了左边是水平的
graphics.drawArc(30, 30, 100, 80, 20, 160);
// 和上面表示的含义一致,默认为黑色填充
graphics.fillArc(30, 30, 200, 140, 30, 150);
// 角度是可以为负数的,那样的话,就是顺时针计算
graphics.fillArc(x, y, 2 * radius, 2 * radius, 0, -30);
// 具体的实例,形成了一个扇形
public class Test {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.add(new NewPanel());
frame.setTitle("Test Paint Components");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class NewPanel extends JPanel{
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
int x = xCenter - radius;
int y = yCenter - radius;
graphics.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
graphics.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
graphics.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
graphics.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
}
}
会转动的小风扇
用到了让线程等待一会的函数 Thread.currentThread().sleep(100); 停止0.1秒
以及窗体重新绘制函数 frame.repaint();
public class Test {
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame();
frame.add(new NewPanel());
frame.setTitle("Test Paint Components");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
for (int i = 0; i < 90; i++) {
NewPanel.startAngle = i;
frame.add(new NewPanel());
frame.repaint();
Thread.currentThread().sleep(100);
if(i == 89)
i = 0;
}
}
}
class NewPanel extends JPanel{
public static int startAngle = 0;
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
int x = xCenter - radius;
int y = yCenter - radius;
graphics.fillArc(x, y, 2 * radius, 2 * radius, startAngle, 30);
graphics.fillArc(x, y, 2 * radius, 2 * radius, startAngle + 90, 30);
graphics.fillArc(x, y, 2 * radius, 2 * radius, startAngle + 180, 30);
graphics.fillArc(x, y, 2 * radius, 2 * radius, startAngle + 270, 30);
}
}
绘制多边形和折线段
多边形:ploygon
示例如下:
// 逐个添加点
Polygon polygon = new Polygon();
polygon.addPoint(30, 50);
polygon.addPoint(80, 100);
// 如果点超出了屏幕大小,仍然会绘制出来,只是超出的部分看不到而已
polygon.addPoint(200, 360);
// 绘制简单的折线段
graphics.drawPolygon(polygon);
// 绘制折线段,但内部都用黑色填充了
graphics.fillPolygon(polygon);
// 也有一些简单的方式
int[] x = {30, 50, 200};
int[] y = {30, 50, 80};
// 直接添加点,每个点是(x[i], y[i])
graphics.drawPolygon(x, y, x.length);
// 填充的方式
graphics.fillPolygon(x, y, x.length);
折线段:和多边形的区别就在于,不会首尾相连
int[] x = {30, 50, 200};
int[] y = {30, 50, 80};
graphics.drawPolyline(x, y, x.length);
绘制六边形
使用FontMetrics类使字体居中
常用的方法:
getAscent
getDescent
getLeading
getHeight
stringWidth
public class Test {
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame();
CenterMessage centerMessage = new CenterMessage();
frame.add(centerMessage);
centerMessage.setBackground(Color.WHITE); // 这里设置背景与字体
centerMessage.setFont(new Font("Times New Roman", Font.BOLD, 30));
frame.setTitle("Test Paint Components");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class CenterMessage extends JPanel{
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
FontMetrics fontMetrics = graphics.getFontMetrics();
String str = "Hello BBYH 2022";
int stringWidth = fontMetrics.stringWidth(str); // 这里进行字符串的设置
int stringAscent = fontMetrics.getAscent();
int xCoordinate = getWidth() / 2 - stringWidth / 2;
int yCoordinate = getHeight() / 2 - stringAscent / 2;
graphics.drawString(str, xCoordinate, yCoordinate);
}
}
案例:MessagePanel类
复习之前的知识,使用一下字体,以及居中效果
public class MessagePanel extends JPanel {
private int xCoordinate = 20;
private int yCoordinate = 20;
private boolean centered;
private String message = "Hello BBYH 2022";
private int interval = 10;
public MessagePanel() {
}
public MessagePanel(String message) {
this.message = message;
}
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int xCoordinate) {
this.xCoordinate = xCoordinate;
repaint();
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int yCoordinate) {
this.yCoordinate = yCoordinate;
repaint();
}
public boolean isCentered() {
return centered;
}
public void setCentered(boolean centered) {
this.centered = centered;
repaint();
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
repaint();
}
public int getInterval() {
return interval;
}
public void setInterval(int interval) {
this.interval = interval;
repaint();
}
public void moveLeft() {
xCoordinate -= interval;
repaint();
}
public void moveRight() {
xCoordinate += interval;
repaint();
}
public void moveUp() {
yCoordinate -= interval;
repaint();
}
public void moveDown() {
yCoordinate += interval;
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(200 ,30);
}
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if(centered) {
FontMetrics fontMetrics = graphics.getFontMetrics();
int stringWidth = fontMetrics.stringWidth(message);
int stringAscent = fontMetrics.getAscent();
xCoordinate = getWidth() / 2 - stringWidth / 2;
yCoordinate = getHeight() / 2 - stringAscent / 2;
}
graphics.drawString(message, xCoordinate, yCoordinate);
}
}
// 测试主类(现在已经一律采取这样的生成方案了)
public class Test extends JFrame {
public static void main(String[] args) throws InterruptedException {
JFrame frame = new Test();
frame.setTitle("Test Paint Components");
frame.setSize(600, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public Test() {
// TODO Auto-generated constructor stub
MessagePanel messagePanel1 = new MessagePanel("Hello BBYH");
MessagePanel messagePanel2 = new MessagePanel("Love xiaolin");
MessagePanel messagePanel3 = new MessagePanel("for every day");
MessagePanel messagePanel4 = new MessagePanel("whenever wherever");
messagePanel1.setFont(new Font("Consolos", Font.BOLD, 30));
messagePanel2.setFont(new Font("Times New Roman", Font.BOLD, 30));
messagePanel3.setFont(new Font("Courier", Font.BOLD, 30));
messagePanel4.setFont(new Font("Times New Roman", Font.BOLD, 30));
messagePanel1.setBackground(Color.RED);
messagePanel2.setBackground(Color.CYAN);
messagePanel3.setBackground(Color.green);
messagePanel4.setBackground(Color.WHITE);
messagePanel1.setCentered(true);
setLayout(new GridLayout(2, 2));
add(messagePanel1);
add(messagePanel2);
add(messagePanel3);
add(messagePanel4);
}
}
案例:StillClock
这里采用了StillClock类和之前的MessagePanel类
public class StillClock extends JPanel {
private int hour;
private int minute;
private int second;
public StillClock() {
// TODO Auto-generated constructor stub
setCurrentTime();
}
public StillClock(int hour, int minute, int second) {
// TODO Auto-generated constructor stub
this.hour = hour;
this.minute = minute;
this.second = second;
}
public void setCurrentTime() {
Calendar calendar = new GregorianCalendar();
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
repaint();
}
public int getMinute() {
return minute;
}
public void setMinute(int minute) {
this.minute = minute;
repaint();
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
repaint();
}
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
graphics.setColor(Color.BLACK);
graphics.drawOval(xCenter - clockRadius, yCenter - clockRadius, 2 * clockRadius, 2 * clockRadius);
graphics.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
graphics.drawString("9", xCenter - clockRadius + 3, yCenter + 5);
graphics.drawString("3", xCenter + clockRadius - 10, yCenter + 3);
graphics.drawString("6", xCenter - 3, yCenter + clockRadius - 3);
int sLength = (int)(clockRadius * 0.8);
int xSecond = (int)(xCenter + sLength * Math.sin(second * (2 * Math.PI / 60)));
int ySecond = (int)(yCenter - sLength * Math.cos(second * (2 * Math.PI / 60)));
graphics.setColor(Color.RED);
graphics.drawLine(xCenter, yCenter, xSecond, ySecond);
int mLength = (int)(clockRadius * 0.65);
int xMinute = (int)(xCenter + mLength * Math.sin(minute * (2 * Math.PI / 60)));
int yMinute = (int)(yCenter - mLength * Math.cos(minute * (2 * Math.PI / 60)));
graphics.setColor(Color.BLUE);
graphics.drawLine(xCenter, yCenter, xMinute, yMinute);
int hLength = (int)(clockRadius * 0.5);
int xHour = (int)(xCenter + hLength * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
int yHour = (int)(yCenter - hLength * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
graphics.setColor(Color.GREEN);
graphics.drawLine(xCenter, yCenter, xHour, yHour);
}
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
// 测试主类
public class DisplayClock extends JFrame {
public static StillClock clock = new StillClock();
public static MessagePanel messagePanel = new MessagePanel(clock.getHour() + ":" + clock.getMinute() + ":" + clock.getSecond());
public static void main(String[] args) throws InterruptedException {
JFrame frame = new DisplayClock();
frame.setTitle("Test Paint Components");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// 这里采用线程进行停止,每次重新绘制
for (int i = 0; i < 600; i++) {
clock.setCurrentTime();
messagePanel.setMessage((clock.getHour() + ":" + clock.getMinute() + ":" + clock.getSecond()));
frame.repaint();
Thread.currentThread().sleep(1000);
}
}
public DisplayClock() throws InterruptedException {
// TODO Auto-generated constructor stub
messagePanel.setCentered(true);
messagePanel.setForeground(Color.BLUE);
messagePanel.setFont(new Font("Times New Roman", Font.BOLD, 10));
add(clock);
add(messagePanel, BorderLayout.SOUTH);
}
}
显示图像
采用方式 drawImage(有很多重载)
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
frame.add(new ImagePanel());
frame.setTitle("Test Paint Components");
frame.setSize(400, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ImagePanel extends JPanel{
// 注意路径,Eclipse里面的工作路径是项目当前路径,而不是bin目录或者src目录
private ImageIcon imageIcon = new ImageIcon("./1.jpg");
// 这里采用imageIcon的方法,而不是生成新对象,是因为生成新对象需要实现需要函数
private Image image = imageIcon.getImage();
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if(image != null) {
graphics.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
}
ImageViewer类实例讲解
public class ImageViewer extends JPanel {
private Image image;
private boolean stretched = true;
private int xCoordinate;
private int yCoordinate;
public ImageViewer() {
// TODO Auto-generated constructor stub
}
public ImageViewer(Image image) {
// TODO Auto-generated constructor stub
this.image = image;
}
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
// 这里进行判断,是否伸展图片,如果不伸展,则不会绘制出来
if(image != null) {
if(isStretched())
graphics.drawImage(image, xCoordinate, yCoordinate, getWidth(), getHeight(), this);
}
else
graphics.drawImage(image, xCoordinate, yCoordinate, this);
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
repaint();
}
public boolean isStretched() {
return stretched;
}
public void setStretched(boolean stretched) {
this.stretched = stretched;
repaint();
}
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int xCoordinate) {
this.xCoordinate = xCoordinate;
repaint();
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int yCoordinate) {
this.yCoordinate = yCoordinate;
repaint();
}
}
// 测试主类
public class Test extends JFrame {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new Test();
frame.setTitle("Test Draw Icon");
frame.setSize(200, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public Test() {
// TODO Auto-generated constructor stub
Image image1 = new ImageIcon("./1.jpg").getImage();
Image image2 = new ImageIcon("./2.jpg").getImage();
setLayout(new GridLayout(2, 0, 5, 5)); // 采用网格布局,好看一些
add(new ImageViewer(image1));
add(new ImageViewer(image2));
}
}