Java学习笔记(七)

给画图板增加按纽2018.06.12

我们之前已经实现了一个画图板了,那么现在给它来增加一些按钮,实现功能的可选。(请大家不要嫌弃我的画图板界面丑,毕竟审美不咋的2333)

一、实现画图板所需要用到的API:

        JFrame
MouseListener 鼠标事件接口,提供处理按下,释放,点击,进入和离开动作的方法
MouseEvent 获取事件源对象信息和动作信息的类
Graphics 画笔类,提供绘制各种图形的方法。

Color 颜色类

二、如何根据点击哪个按钮从而执行相应的功能?

首先贴一下我这个画图板界面吧:

Java学习笔记(七)

图案类型+颜色。

之前实现计算器界面的时候有用到一个叫getActionCommand()的方法,它可以返回按钮上的文字信息,颜色按钮上是空字符。(一定要注意,空字符和空格不一样,我就是在这里卡了很久,我打成空格了,空字符直接打出双引号即可。)然后根据返回的信息判断是点了颜色按钮还是图案类型的按钮,几个简单的if就好了。

三、如何设置图案的颜色:

当颜色按钮被点击的时候,我们要怎么拿到按钮上的颜色呢?

首先必须确定事件源对象:按钮!

然后按钮提供了获取背景颜色的方法,所以我们可以定义一个Color对象接收这个背景颜色。

代码如下:

(1)获取事件源对象:

            JButton button = getSource();

(2)得到按钮上的颜色:

            color = button.getBackground();

之后在鼠标被按下的时候就设置图案的颜色即可(调用setColor()方法即可,详情参考完整代码)

四、功能实现:

如上图,我的功能有绘制直线、等腰三角形、任意多边形、圆、虚线、喷枪等等。有一些Java提供了方法我就不阐述了,这里新出现的虚线和喷枪是Java没有提供的。

1.下面我说一下虚线如何实现。

首先Java提供了设置线条样式的类:Stroke | BasicStroke 线条样式的类(可以设置线条的样式,比如设置虚线)

BasicStroke是方法,有很多种。一般是六个参数的。下面我结合代码来说明:

 Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);

六个参数分别是:线的宽度、线的样式、拐角的样式、限制尖角、线长和缺口长度、开始画的偏移量

详情参考这位大佬的博客:https://blog.****.net/op_violet/article/details/18893917

然后调用setStroke方法即可。画出来的就是一条虚线了。

2.如何实现喷枪:

喷枪效果是一些离散的点对吧??首先点是一条特殊的直线(起点和终点重合),那么我们想一下如何让它离散呢?随机数啊!随机产生画点的位置,控制好你的随机数范围,就能控制住那个喷枪图案的范围了。(具体参考完整代码)

五、曲线的实现:

画曲线的时候鼠标在拖动对吧?那么如何画出跟随鼠标拖动的曲线呢?当然Java提供了鼠标拖动事件动作的捕获方法。

MouseAdapter 鼠标适配器类,该类实现MouseListener、MouseMotionListener和MouseWheelListener这三个鼠标事件接口,重写接口接口中所有的抽象方法。(咱们用这个,就可以使用所有鼠标动作信息捕获的方法了)

代码如下:

public void mouseDragged(MouseEvent e) {
if (shape.equals("曲线")) {
x2 = e.getX();
y2 = e.getY();
G.setStroke(new BasicStroke(10));
G.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}

}

简要提一下橡皮,橡皮其实就是画出与画板背景颜色相同的线条即可,刷子呢,刷出比较粗的线条即可,设置样式还是调用setStoke()方法。大概就是这样,大家可以尝试着增加一些更好玩的功能。

六、完整代码如下(如有问题,以后检查补充)

//DrawJFrame

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;


import javax.swing.JButton;
import javax.swing.JFrame;
public class DrawJFrame extends JFrame{
public static void main(String []args)
{
DrawJFrame J = new DrawJFrame();
J.initUI();
}

public void initUI()
{
this.setTitle("画板");
this.setSize(700, 500);
this.setDefaultCloseOperation(3);
this.setLocationRelativeTo(null);
this.setLayout(new FlowLayout());
DrawListener Dr = new DrawListener();
String[] shape ={"直线","圆","等腰三角形","任意多边形","铅笔","刷子","喷枪","橡皮","曲线","虚线"};
for(int i=0;i<shape.length;i++)
{
JButton button = new JButton(shape[i]);
button.setPreferredSize(new Dimension(100,20));
button.addActionListener(Dr);
this.add(button);
}
Color[] color={Color.red,Color.BLACK,Color.green};
for(int i=0;i<color.length;i++)
{
JButton button = new JButton();
button.setBackground(color[i]);
button.setPreferredSize(new Dimension(50,50));
button.addActionListener(Dr);
this.add(button);
}
this.setVisible(true);

Dr.setG(getGraphics());
Dr.setF(this);//重点
this.addMouseListener(Dr);
this.addMouseMotionListener(Dr);
}

}

//DramListener

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;


import javax.swing.JButton;
import javax.swing.JFrame;


import java.awt.Image;
import java.lang.Math;
import java.util.Random;
public class DrawListener extends MouseAdapter implements ActionListener {

   private int x1,x2,y1,y2;
   private Graphics2D G;
   private int sx,sy,ex,ey;
   private int flag = 1;
   private Color color = Color.BLACK;
   private String shape="直线";
   private JFrame frame;
   
  public void setF(JFrame J)
  {
  frame =J;
  }
   

public void setG(Graphics g)
{
G = (Graphics2D)g;
this.G.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
 
  public void actionPerformed(ActionEvent e)
  {
  if(e.getActionCommand().equals(""))//表示点击的当时选择颜色的按钮
  {
  JButton button = (JButton)e.getSource();
  color = button.getBackground();//获取按钮的颜色

  }
  else//点击的是有文字的按钮
  {
  shape = e.getActionCommand();
  }
  }
 
 
public void drawTrangle(int x1,int y1,int x2,int y2)
{
if(y1-y2!=0 && x1-x2!=0)
{
int T = (y1-y2)/(x1-x2);
int a = (int) Math.atan(T);
int L = (int) Math.sqrt((y1-y2)*(y1-y2)+(x1-x2)*(x1-x2));
int x3 = (int) (x2+(int)L*Math.cos(a+60));
int y3 = (int) (y2+(int)L*Math.sin(a+60));
int[]x={x1,x2,x3};
int[]y={y1,y2,y3}; 
G.drawPolygon(x, y, 3);
}

}
int count = 0;
int temp1 = 0;
int temp2 = 0;
int tempx2 = 0;
int tempy2 = 0;
int close = 0;
public void drawduobian(int x1,int y1,int x2,int y2)
{


G.drawLine(x1, y1, x2, y2);
if(Math.abs(x2-temp1)<10|| Math.abs(y2-temp2)<10)
    {
    G.drawLine(temp1, temp2, x2, y2);
    count=0;
    }


}

public void mouseClicked(MouseEvent e){
if (shape.equals("任意多边形") && flag == 2) {
x2 = e.getX();
y2 = e.getY();
G.drawLine(ex, ey, x2, y2);
if (e.getClickCount() == 2
|| (Math.abs(x2 - sx) < 15 && Math.abs(y2 - sy) < 15)) {
G.drawLine(sx, sy, x2, y2);
flag = 1;
}
ex = x2;
ey = y2;
}
 
}


    /**
     * Invoked when a mouse button has been pressed on a component.
     */

    public void mousePressed(MouseEvent e){
   
    System.out.println("鼠标被按下!");
    G.setColor(color);
    x1 = e.getX();
    y1 = e.getY();
    if(count==0)
    {
    temp1 = x1;
    temp2 = y1;
    }
    count++;
   
   


    }
    public void drawDashedLine(int x1, int y1, int x2, int y2){
        Graphics2D g2d = (Graphics2D) G;
        //float dash[] = {10.0f};
        Stroke dashed = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
        g2d.setStroke(dashed);//线的宽度、线的样式、拐角的样式、限制尖角、线长和缺口长度、开始画的偏移量
        g2d.drawLine(x1, y1, x2, y2);
    }


    /**
     * Invoked when a mouse button has been released on a component.
     */
    public void mouseReleased(MouseEvent e){
    System.out.println("鼠标被释放!");
    x2 = e.getX();
    y2 = e.getY();
    tempx2 = x2;
    tempy2 = y2;
    if(shape.equals("直线"))
    {
    G.setStroke(new BasicStroke(2));
    G.drawLine(x1, y1, x2, y2);
    }
    else if(shape.equals("等腰三角形"))
    {
    G.setStroke(new BasicStroke(2));
    this.drawTrangle( x1, y1, x2, y2);
    }


    else if (shape.equals("任意多边形") && flag == 1) {
    G.setStroke(new BasicStroke(2));
G.drawLine(x1, y1, x2, y2);
sx = x1;
sy = y1;
ex = x2;
ey = y2;
flag++;
}
    else if(shape.equals("圆"))
    {
    G.setStroke(new BasicStroke(2));
    G.drawOval(Math.min(x1,x2), Math.min(y1, y2), Math.abs(x1-x2), Math.abs(y1-y2));
    }
    else if(shape.equals("橡皮"))
    {
    color = frame.getContentPane().getBackground();
    G.setColor(color);
    x2 = e.getX();
y2 = e.getY();
G.setStroke(new BasicStroke(100));
G.drawLine(x1, y1, x2, y2);

    }
    else if(shape.equals("刷子"))
    {
    G.setStroke(new BasicStroke(20));
G.drawLine(x1, y1, x2, y2);
    }
    else if(shape.equals("喷枪"))
    {
    Random random = new Random();
    G.drawLine(x2, y2, x2, y2);   
             for (int i = 0; i < 10; i++) {  
                 int p = random.nextInt(10);  
                 int q = random.nextInt(10);  
                 G.drawLine(x2 + p, y2 + q, x2 + p, y2 + q);  
    }
    }
    else if(shape.equals("虚线"))
    {
    drawDashedLine(x1,y1, x2,  y2);
   
    }
   
    //G.drawLine(x1, y1, x2, y2);
    //G.drawOval(x2, y2, 100, 100);//画圆的
    //G.drawRect(x1, y1, 200, 100);//画矩形的
    //G.drawString("AAA", x1, y1);//画文字的
    //javax.swing.ImageIcon IMG = new javax.swing.ImageIcon("C:\\Users\\25280\\Desktop\\综合文件夹\\收稿\\摄影作品_张雨泉\\5.jpg");
    //Image img = IMG.getImage();
    //G.drawImage(img, x1, y1,null);
    //G.fill3DRect(x1, y1, 100, 100, true);
    //G.fillOval(x1, y1, 100, 100);
    //G.fillRoundRect(x1, y1, 100, 100, 50, 50);
    //this.drawTrangle(x1, y1, x2, y2);
    //this.drawduobian(x1, y1, x2, y2);
      
    }
    private int nextInt(int i) {
// TODO Auto-generated method stub
return 0;
}




public void mouseDragged(MouseEvent e) {
if (shape.equals("曲线")) {
x2 = e.getX();
y2 = e.getY();
G.setStroke(new BasicStroke(10));
G.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
}

}


    /**
     * Invoked when the mouse enters a component.
     */
    public void mouseEntered(MouseEvent e){
    System.out.println("鼠标进入画板!");
   
    }


    /**
     * Invoked when the mouse exits a component.
     */
    public void mouseExited(MouseEvent e){
    System.out.println("鼠标离开画板!");
   
    }
    

}

加油!