画笔:Piant
学习Piant的时候我记得当时学习Python的海龟作图的时候就写过奥运五环,没想到在Java也能实现。
想看python的奥运五环参照:奥运五环
package 狂神说__Paint;import java.awt.*;public class TestPaint {public static void main(String[] args) {new MyPaint().loadFrame();}
}
class MyPaint extends Frame{public void loadFrame(){setBounds(200,200,600,400);setVisible(true);}public void paint(Graphics g){super.paint(g);g.setColor(Color.blue);//g.drawOval(100,100,100,100);g.drawOval(100,100,100,100);g.setColor(Color.black);g.drawOval(200,100,100,100);g.setColor(Color.red);g.drawOval(300,100,100,100);g.setColor(Color.yellow);g.drawOval(150,150,100,100);g.setColor(Color.green);g.drawOval(250,150,100,100);}
}
画图:在空白板中点点
package 狂神说__Paint;import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;public class TestMouseListener {public static void main(String[] args) {new MyFrame("画图");}
}
class MyFrame extends Frame{//画笔,需要集合存储点ArrayList points;//动态数组存储点public MyFrame(String title){super(title);setBounds(200,200,400,300);//存储鼠标的点points=new ArrayList<>();//鼠标监听器this.addMouseListener(new MyMouseListener());setVisible(true);}public void paint(Graphics g){//监听鼠标事件Iterator iterator=points.iterator();while(iterator.hasNext()){Point point=(Point)iterator.next();g.setColor(Color.blue);g.fillOval(point.x,point.y,10,10);}}//添加点到界面上
public void addPaint(Point point){points.add(point);
}//适配器模式private class MyMouseListener extends MouseAdapter{//鼠标点击public void mousePressed(MouseEvent e){MyFrame myFrame=(MyFrame)e.getSource();//点击鼠标时会出现一个点myFrame.addPaint(new Point(e.getX(),e.getY()));//每次点击鼠标都需要重新画一次myFrame.repaint();//刷新}}
}
键盘的监听事件:按下上下左右给出动作
package 狂神说__Paint;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class TestKeyListener {public static void main(String[] args) {new KeyFrame();}
}
class KeyFrame extends Frame{public KeyFrame() {setBounds(1,2,300,400);setVisible(true);this.addKeyListener(new KeyAdapter() {//键盘按下出现的事件@Overridepublic void keyPressed(KeyEvent e) {//键盘按键int keyCode=e.getKeyCode();if(keyCode==KeyEvent.VK_UP){System.out.println("按下了上键");}else if(keyCode==KeyEvent.VK_DOWN){System.out.println("按下了下键");}else if(keyCode==KeyEvent.VK_LEFT){System.out.println("按下了左键");}else if(keyCode==KeyEvent.VK_RIGHT){System.out.println("按下了右键");}else{System.out.println("按下了其他键");}}});}
}