一、绘图坐标体系
- 坐标原点位于左上角,以像素为单位;
- 坐标原点(0,0):
- 第一个是 X 坐标,表示当前位置 水平 方向距离原点 X 个像素;
- 第二个是 Y 坐标,表示当前位置 垂直 方向距离原点 Y 个像素;
Graphics 常用方法:
画直线 | drawLine(int x1, int y1,intx2,inty2) |
---|
画矩形边框 | drawRect(int x,int y, int width, int height) |
画椭圆边框 | drawOval (int x, int y, int width, int height) |
填充矩形 | fillRect (int x, int y, int width, int height) |
填充椭圆 | fillOval (int x, int y, int width, int height) |
画图片 | drawImage (Image img, int x, int y, …) |
画字符串 | drowString (String str, int x, int y) |
设置画笔字体 | setFont (Font font) |
设置画笔颜色 | setColor (Color c) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
public class DrawCircle extends JFrame{ private MyPanel mp = null; public static void main(String[] args) { new DrawCircle(); }
public DrawCircle(){ mp = new MyPanel(); this.add(mp); this.setSize(400,400); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } }
class MyPanel extends JPanel{ @Override public void paint(Graphics g) { super.paint(g); g.drawOval(10, 10, 100,100); g.drawLine(120,10,120,224);
Image img = Toolkit.getDefaultToolkit().getImage(MyPanel.class.getResource("/1.png")); g.drawImage(img,130,10,224,224,this);
g.setColor(Color.BLUE); g.setFont(new Font("隶属",Font.BOLD, 50)); g.drawString("学习 Java",10,280); } }
|
Componest 类提供了两个和绘图相关的重要方案:
- paint(Graphics g):绘制组件外观;
- 当组件第一次显示时,程序会自动调用该方法来绘制组件;
- 当窗口方法变化时,该方法也会被调用;
- repaint 方法被调用时,paint 也会被调用;
- repaint() : 刷新组件的外观;
二、事件处理机制
事件监听接口一般在 java.awt.event 包中;
通过 KeyListevent 来监听键盘事件,KeyEvent 提供了多种监听方法,如:code 值,char 字符,test 内容等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| public class BollMove extends JFrame{ public static void main(String[] args) { new BollMove(); } private MyPanel mp; public BollMove(){ mp = new MyPanel(); this.add(mp); this.addKeyListener(mp); this.setSize(300,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } }
class MyPanel extends JPanel implements KeyListener { int x = 10; int y = 10;
@Override public void paint(Graphics g) { super.paint(g); g.fillOval(x,y,20,20); }
@Override public void keyTyped(KeyEvent e) {
}
@Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT){ x++; }else if (e.getKeyCode() == KeyEvent.VK_LEFT){ x--; }else if (e.getKeyCode() == KeyEvent.VK_UP){ y--; }else if (e.getKeyCode() == KeyEvent.VK_DOWN){ y++; } this.repaint();
}
@Override public void keyReleased(KeyEvent e) {
} }
|