例子:
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);
}
}