今天上午左哥给我补课,讲了类的继承和接口。
方法有三种:普通,构造和抽象。类也有三种:普通,抽象和接口。extends只能单继承,但implements可多实现接口。
今天还做了图画板.可以实现画直线、矩形、椭圆和实心椭圆。
package draw; import java.awt.FlowLayout; import java.awt.Graphics; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JRadioButton; public class Draw extends JFrame{ public static void main(String[] args) { //创建一个当前类的对象 Draw draw = new Draw(); //调用对象的方法 draw.initFrame(); } public void initFrame(){ this.setTitle("图画板"); this.setSize(500, 500); this.setDefaultCloseOperation(3); FlowLayout ly = new FlowLayout(); this.setLayout(ly); //设置JRadioButton单选按钮 JRadioButton j1 = new JRadioButton("直线",true); //逐个按钮设置名称 j1.setActionCommand("line"); this.add(j1); JRadioButton j2 = new JRadioButton("矩形"); j2.setActionCommand("rect"); this.add(j2); JRadioButton j3 = new JRadioButton("椭圆"); j3.setActionCommand("oval"); this.add(j3); JRadioButton j4 = new JRadioButton("实心椭圆"); j4.setActionCommand("filloval"); this.add(j4); //将4个单选按钮设为一组 ButtonGroup bg = new ButtonGroup(); bg.add(j1); bg.add(j2); bg.add(j3); bg.add(j4); this.setVisible(true); //获取当前界面的图片操作 Graphics g = this.getGraphics(); //创建一个鼠标监听器的对象,并且传递参数 Draw_p dp = new Draw_p(g,bg); //为当前界面添加鼠标监听器的对象 this.addMouseListener(dp); } }这是主函数
JRadioButton是一个新的知识点,是选择单选按钮。
package draw; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ButtonGroup; public class Draw_p implements MouseListener{ //定义全局变量 private int x1,x2,y1,y2; private Graphics g ; private String s ; private ButtonGroup bg ; //构造方法接收主函数传递的参数 public Draw_p(Graphics g,ButtonGroup bg){ this.g = g; this.bg = bg ; } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { x1 = e.getX(); y1 = e.getY(); s = bg.getSelection().getActionCommand(); } public void mouseReleased(MouseEvent e) { x2 = e.getX(); y2 = e.getY(); if("line".equals(s)){g.drawLine(x1, y1, x2, y2);} else if("rect".equals(s)){g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));} else if("oval".equals(s)){g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));} else if("filloval".equals(s)){g.fillOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));} } }
这是java面向对象的思想,结构分明,条理清晰,不会再像五子棋那个程序那样,一个类里面写完,密密麻麻的代码,看得头都晕了。
今天还有一个小知识点就是,类与类之间的传值问题:通过构造函数进行传值,把参数写到构造函数的参数里面去,可以对别的对象的参数进行操作。
That's all.