swing中绘图

例子:

import java.awt.Color;
import java.awt.Frame;
import java.awt.*;

import javax.swing.*;

public class MyFrame extends JFrame {
 public MyFrame() {
  this.setTitle("我的第一个窗体");// 设置窗体的标题
  MyPanel panel = new MyPanel();
  this.getContentPane().add(panel);
  this.setSize(300, 300);// 设置窗体的大小
  this.setLocation(260, 150);// 设置窗体的初始位置
  this.setResizable(false);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  System.out.println("asd");
  // this.setBounds(260, 150, 300, 300);//设置窗体的坐标、大小,相当于前面2行代码
 }
 public static void main(String[] args) {
  MyFrame frame = new MyFrame();
  frame.setVisible(true);
 }
}

class MyPanel extends JPanel {
 // 覆盖JPanel的paint方法,程序自动调用paint方法,窗口最小化,再最大化,窗口大小变化
 // Graphics是绘图的重要类,可以理解成一只画笔
 public void paint(Graphics g) {
  // 1.调用父类函数完成初始化
  // 这句话不能少
  super.paint(g);
  System.out.println("paint coming");
  // 画圆,还可话直线,矩形边框,等图像
  g.drawOval(10, 10, 30, 30);
  Image im = Toolkit.getDefaultToolkit().getImage(
    Panel.class.getResource("/images/dog.jpg"));//获取图片,其中"/images/dog.jpg"表示bin目录下的images/dog.jpg
  System.out.println(Panel.class.getResource("/images/dog.jpg"));
  // 显示图片
  g.drawImage(im, 10, 10, 200, 150, this);
  // 如何画出字
  g.setColor(Color.red);
  g.setFont(new Font("华文彩云", Font.BOLD, 30));
  g.drawString("祖国万岁", 100, 100);
  g.setColor(Color.yellow);
  // 画出我的坦克(到时再封装成一个函数)
  // 1.画出左边的矩形
  g.fillRect(10, 10, 15, 15);
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值