21天养成好习惯_第十二天
今天继续学习Java GUI的后续课程
直接上实例:
package Mypaint;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
public class PaintOne {
public static void main(String[] args) {
M_paint m_paint = new M_paint();
m_paint.loadFrame();
//关闭窗口功能
m_paint.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class M_paint extends Frame{
public void loadFrame(){
setBounds(200,200,600,500);
setVisible(true);
}
//画笔
@Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawOval(100,100,100,100);//空心圆
g.fillOval(200,100,100,100);//实心圆
g.setColor(Color.yellow);
g.fillRect(100,200,100,100);
// repaint();//用于刷新界面的效果
}
}
Java的绘图paint功能很强大 我只简单的演示了一下
运行结果:
实现一个简易鼠标画点实例
package Mypaint;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
public class TestMouseListener {
public static void main(String[] args) {
MyFrame myFrame = new MyFrame("myMouseListener");
myFrame.setVisible(true);
myFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyFrame extends Frame{
//画画需要画笔, 需要监听鼠标当前的位置, 需要集合来存储这个点
ArrayList points;
public MyFrame (String title){
super(title);
setBounds(200,200,400,300);
//存鼠标的点 的数组
points = new ArrayList<>();
//鼠标监听器 ,监听这个窗口
this.addMouseListener(new MyMouseListener());
}
@Override
public void paint(Graphics g) {
//画画,监听鼠标事件
Iterator iterator = points.iterator(); //获得迭代器
Point point;
g.setColor(Color.BLUE);
while (iterator.hasNext()){
point = (Point) iterator.next();
g.fillOval(point.x,point.y,5,5);
}
}
public void addPoint(Point point){
points.add(point);
}
//适配器模式
private class MyMouseListener extends MouseAdapter {
//鼠标放下, 弹起,按住不放
@Override
public void mousePressed(MouseEvent e) {
MyFrame frame = (MyFrame) e.getSource();//获得本体的全部信息
//点击是产生一个点
frame.addPoint(new Point(e.getX(),e.getY()));
//每次点击后记得刷新 (有点多线程的味道)
frame.repaint();
}
}
}
运行结果: