Java swing实现Visio中对直线、曲线、折线的画及拖动删除

原文:http://blog.csdn.net/cuiyaoqiang/article/details/46361133

这里写图片描述
最终线条如图显示,可以实现线条的拖动、删除等

以下是两个核心的类:


package com.bh.realTimeMonitor.entity;
import java.awt.geom.GeneralPath;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.QuadCurve2D;
/**
       线条的实体类
 * @author 崔耀强  20150507-20150822
 * @version 1.1
 * */
public class Line {

public boolean isSelected;
public boolean isSelectP0; //选择线段的第一个端点
public boolean isSelectP1; //选择线段的另一个端点
public boolean isSelectP2; //选择线段的中间的端点
public double distance;    //实际线的长度
public double length;      //所画的线的长度
public GeneralPath shape;  //线的构造路径
private float len = 3.0f;  //线宽的改变主要靠该参数

private int id;
public  int startX,startY,endX,endY,middleX,middleY;
public  int lineShape;     //线形状 0直线1折线2曲线
public  float lineWidth = 0.6f; // 画笔宽
private LineType lineType;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public   float getLen() {
return this.len;
}

public   void setLen(float len) {
this.len = len;
}

public double getDistance() {
return distance;
}

public void setDistance(double distance) {
this.distance = distance;
}

public LineType getLineType() {
return lineType;
}
public void setLineType(LineType lineType) {
this.lineType = lineType;
}


public int getStartX() {
return startX;
}

public void setStartX(int startX) {
this.startX = startX;
}

public int getStartY() {
return startY;
}

public void setStartY(int startY) {
this.startY = startY;
}

public int getEndX() {
return endX;
}

public void setEndX(int endX) {
this.endX = endX;
}

public int getEndY() {
return endY;
}

public void setEndY(int endY) {
this.endY = endY;
}

public int getMiddleX() {
return middleX;
}

public void setMiddleX(int middleX) {
this.middleX = middleX;
}

public int getMiddleY() {
return middleY;
}

public void setMiddleY(int middleY) {
this.middleY = middleY;
}

public int getLineShape() {
return lineShape;
}

public void setLineShape(int lineShape) {
this.lineShape = lineShape;
}

/**
 * @Description 构造线路径 ,Polyline 为0:直线;1折线;2:曲线
 * 可以使用的策略模式,针对不同的lineShape,分配不同的路径算法(降低耦合度)
 */
public void constructShape() {
//GeneralPath 类表示根据直线、二次曲线和三次 (Bézier) 曲线构造的几何路径
shape = new GeneralPath();

switch (lineShape) {
case 0://直线
straightLine();
break;
case 1://折线
polygonalLine();
break;
case 2://曲线
curveLine();
break;
default:
break;
}
}
/**
 * @Description 画曲线,曲线路径的定义
 */
private void curveLine() {

double[] px = new double[6];
double[] py = new double[6];
int a,b,c,d;
if(startY>=endY){
a = endX;
b = endY;
c = startX;
d = startY;
}else{
a = startX;
b = startY;
c = endX;
d = endY;
}  

px[0] = a;
py[0] = b;
px[4] = middleX;
py[4] = middleY;
px[1] = c;
py[1] = d;

double sina = (middleY-b)/Math.hypot(middleY-b,middleX-a);
double cosa=(middleX-a)/Math.hypot(middleY-b,middleX-a);
double cosa1=(a-middleX)/Math.hypot(middleY-b,middleX-a);
double sinb=(d-middleY)/Math.hypot(d-middleY,middleX-c);
double cosb=(middleX-c)/Math.hypot(d-middleY,middleX-c);
double cosb1=(c-middleX)/Math.hypot(d-middleY,c-middleX);
if(middleX>=a&&middleX<=c){

px[2] = c +len*sinb;
py[2] = d +len*cosb;
/*px[5] =(cosa*sinb*(c +len*sinb)+sina*cosb*(a+len*sina)-cosb*cosa*(b -len*cosa)+cosb*cosa*(d +len*cosb))/(cosa*sinb+sina*cosb);  
     py[5] = b -len*cosa+sina/cosa*(px[5]-a+len*sina);*/
px[5] = middleX+len*Math.sqrt(2)/2;
py[5] = middleY-len*Math.sqrt(2)/2; 
px[3] = a+len*sina;
py[3] = b -len*cosa;
}else if(middleX==a&&middleX>c){

px[2] = c;
py[2] = d-len ;
px[5] = middleX-len;  
py[5] = middleY-len;
px[3] = a -len;
py[3] = b;
} 
else {

px[2] = c-len* sinb;
py[2] = d+len*cosb1;
px[5] =(cosa1*cosb1*(b -len*cosa1)+cosb1*(a-len*sina)*sina-cosa1*cosb1*(d+len*cosb1)+cosa1*sinb*(c-len* sinb))/(cosa1*sinb+sina*cosb1);  
py[5] = ((a-len*sina)-px[5])*sina/cosa1+(b -len*cosa1); 
px[3] = a-len*sina;
py[3] = b -len*cosa1; 
} 
//二次曲线函数
QuadCurve2D.Double quadCurve2D_double1=new QuadCurve2D.Double(px[0], py[0],px[4], py[4], px[1], py[1]);
QuadCurve2D.Double quadCurve2D_double2=new QuadCurve2D.Double(px[2], py[2],px[5], py[5], px[3], py[3]);

shape=new GeneralPath(quadCurve2D_double1);
shape.lineTo(px[2], py[2]);
shape.append(quadCurve2D_double2,true);
shape.lineTo(px[0], py[0]);
shape.closePath();
/*int x=(int) (quadCurve2D_double1.getBounds2D().getCenterX());
int y = 0;
if(startX-2*middleX+endX!=0){
贝塞尔曲线
 * y=(1-t)^2P0+2t(1-t)P1+t^2P2
 * 
double t= (2*startX-2*middleX-Math.sqrt(4*(startX-middleX)*(startX-middleX)-4*(startX-2*middleX+endX)*(startX-x)))/(2*(startX-2*middleX+endX));
if(t>0&&t<1){
y =(int) ((1-t)*(1-t)*startY+2*t*(1-t)*middleY+t*t*endY);
}else{
double t1= (2*startX-2*middleX+Math.sqrt(4*(startX-middleX)*(startX-middleX)-4*(startX-2*middleX+endX)*(startX-x)))/(2*(startX-2*middleX+endX));
y =(int) ((1-t1)*(1-t1)*startY+2*t1*(1-t1)*middleY+t1*t1*endY);
}
}else{
y=(startY+endY)/2;
}*/
}

/**
 * @Description 画折线,折线路径的定义
 */
private void polygonalLine() {


double[] px = new double[6];
double[] py = new double[6];


if((startX>endX&&startY>endY)||(startX<endX&&startY<endY)){
px[0] = startX ;
py[0] = startY ;
px[5] = endX ;
py[5] = startY ;
px[1] = endX ;
py[1] = endY ;
px[2] = endX + len;
py[2] = endY ;
px[4] = endX + len;
py[4] = startY - len ;
px[3] = startX ;
py[3] = startY - len ;
}else{
px[0] = startX ;
py[0] = startY ;
px[5] = endX ;
py[5] = startY ;
px[1] = endX ;
py[1] = endY ;
px[2] = endX + len;
py[2] = endY ;
px[4] = endX + len;
py[4] = startY + len ;
px[3] = startX ;
py[3] = startY + len ;
}


startX=(int) px[0];
startY=(int) py[0];
endX=(int) px[1];
endY=(int) py[1];
middleX=(int) px[5];
middleY=(int) py[5];
/*
 *折线是否变成直线
 * 
 * x2=e;
           y2=f;*/
shape.moveTo(px[0], py[0]);//通过移动到指定坐标(以双精度指定),将一个点添加到路径中。 
shape.lineTo(px[5], py[5]);//通过绘制一条从当前坐标到新指定坐标(以双精度指定)的直线,将一个点添加到路径中
shape.lineTo(px[1], py[1]);
shape.lineTo(px[2], py[2]); 
shape.lineTo(px[4], py[4]);
shape.lineTo(px[3], py[3]); 
//通过绘制一条向后延伸到最后一个 moveTo 的坐标的直线,封闭当前子路径。如果该路径已封闭,则此方法无效
shape.closePath();
}

/**
 * @Description 画直线,直线路径的定义
 */
private void straightLine() {

length = Math.hypot(endX - startX, endY - startY);//直线的长度  返回 sqrt(x^2 +y^2),没有中间溢出或下溢。
double[] px = new double[4];
double[] py = new double[4];

if (endX == startX) { //竖直线
middleX=endX;
middleY=(endY+startY)/2;
px[0] = startX;
py[0] = startY;
px[1] = endX  ;
py[1] = endY;
px[2] = endX - len;
py[2] = endY;
px[3] = startX - len;
py[3] = startY;
} else if (endY == startY) { //横直线
middleX=(startX+endX)/2;
middleY=endY;
px[0] = startX;
py[0] = startY;
px[1] = endX;
py[1] = endY ;
px[2] = endX;
py[2] = endY + len;
px[3] = startX;
py[3] = startY + len;
} else {//斜线
double sin = (endX - startX) / length;
double cos = (endY - startY) / length;
if(startX<endX){
middleX=startX+Math.abs (endX - startX) /2;
}else{
middleX=endX+Math.abs (endX - startX) /2;
}
if(startY>endY){
middleY=endY+Math.abs((endY-startY)/2);
}else{
middleY=startY+Math.abs((endY-startY)/2);
}
px[0] = startX + len * cos;
py[0] = startY - len * sin;
px[1] = endX + len * cos;
py[1] = endY - len * sin;
px[2] = endX - len * cos;
py[2] = endY + len * sin;
px[3] = startX - len * cos;
py[3] = startY + len * sin;
}
/*x2=e;
y2=f;*/
shape.moveTo(px[0], py[0]);//通过移动到指定坐标(以双精度指定),将一个点添加到路径中。 
shape.lineTo(px[1], py[1]);//通过绘制一条从当前坐标到新指定坐标(以双精度指定)的直线,将一个点添加到路径中
shape.lineTo(px[2], py[2]);
shape.lineTo(px[3], py[3]); 
shape.closePath();
}

/**
 * @Description判断鼠标是否移到路径对象上
 * */
public boolean contains(int x, int y) {
return Path2D.contains(shape.getPathIterator(null), new Point2D.Float(x, y));
}
}
   
   
  • 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
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
  • 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
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257
  • 258
  • 259
  • 260
  • 261
  • 262
  • 263
  • 264
  • 265
  • 266
  • 267
  • 268
  • 269
  • 270
  • 271
  • 272
  • 273
  • 274
  • 275
  • 276
  • 277
  • 278
  • 279
  • 280
  • 281
  • 282
  • 283
  • 284
  • 285
  • 286
  • 287
  • 288
  • 289
  • 290
  • 291
  • 292
  • 293
  • 294
  • 295
  • 296
  • 297
  • 298
  • 299
  • 300
  • 301
  • 302
  • 303
  • 304
  • 305
  • 306
  • 307
  • 308
  • 309
  • 310
  • 311
  • 312
  • 313
  • 314
  • 315
  • 316
  • 317
  • 318
  • 319
  • 320
  • 321
  • 322
  • 323
  • 324
  • 325
  • 326
  • 327
  • 328
  • 329
  • 330
  • 331
  • 332
  • 333
  • 334
  • 335
  • 336
  • 337
  • 338
  • 339
  • 340
  • 341
  • 342
  • 343
  • 344
  • 345
  • 346
  • 347
  • 348
  • 349
  • 350
  • 351
  • 352
  • 353
  • 354
package com.bh.realTimeMonitor.view.EquConnectionMonitorView;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.GeneralPath;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.event.MouseInputListener;

import com.bh.realTimeMonitor.business.InterfaceBusiness;
import com.bh.realTimeMonitor.business.LineBusiness;
import com.bh.realTimeMonitor.entity.Equipment;
import com.bh.realTimeMonitor.entity.Line;
import com.bh.realTimeMonitor.entity.LineType;
import com.bh.realTimeMonitor.view.EquRealTimeMonitor;

/**
 * 设备连接管理界面中的画图面板。在面板上画线,可以选择直线,可以移动、拉伸、删除直线。
 * @author 崔耀强 20150507-20150822
 * @version 1.1
 */
public class EquConnectionEditPanel extends JLayeredPane{

    private static final long serialVersionUID = 1L;

    public  Set<Line> lines;
    private Line inLine;
    private Line selectedLine; // 选中的line
    private Line tmpSelectedLine; // 移动时临时的线
    private LineType linetype;
    private InterfaceBusiness interfaceBussiness;
    private LineBusiness lineBusiness;

    private int module=1;//所属模块
    private float range = 4f;//判断两个点是否离得很近 近的标准用range
    public  boolean lineFlag=true;
    private boolean cureFlag;
    private int pressIndex = 0;



    public EquConnectionEditPanel() {

        lines = new HashSet<Line>();
        interfaceBussiness=new InterfaceBusiness();
        lineBusiness=new LineBusiness();

        MyMouseListener mouseListener = new MyMouseListener();
        addMouseListener(mouseListener);
        addMouseMotionListener(mouseListener);
        //this.add(new JLabel(new ImageIcon("img/-1.jpg")));
        this.repaint();
    }
    /**
     * 面板鼠标事件(画线)包括画线过程中的所有的鼠标事件 实现了MouseInputListener接口
     ** 4种状态:0无任何状态1选中直线2选中端点3开始画线
     * */
    class MyMouseListener implements MouseInputListener {

        private Point oldPoint;
        boolean isDragge;
        private Point p1;
        private Point p2;
        private Point p3;
        private  List<LineType> lineTypeList;
        private boolean middleFlag;
        /**
         * 解决鼠标焦点超出面板(线的第一个坐标)
         * */
        private void constructStartP(Line ln, int x, int y) {
            if (x > getWidth())
                ln.startX = getWidth();
            else if (x < 0)
                ln.startX = 0;
            else
                ln.startX = x;
            if (y > getHeight())
                ln.startY = getHeight();
            else if (y < 0)
                ln.startY = 0;
            else
                ln.startY = y;
            //表示是折线
            if((ln.getLineShape()==1)){
                if(isRange(new Point(ln.startX,ln.startY), new Point(ln.middleX,ln.middleY))){

                    ln.lineShape=0;
                }
            }


        }
        /**
         * 解决鼠标焦点超出面板(线的第二个坐标)
         * */
        private void constructEndP(Line ln, int x, int y) {
            //表示是折线
            if((ln.getLineShape()==1)){
                if(isRange(new Point(ln.endX,ln.endY), new Point(ln.middleX,ln.middleY))){
                    ln.lineShape=0;
                }
            } 
            if (x > getWidth())
                ln.endX = getWidth();
            else if (x < 0)
                ln.endX = 0;
            else
                ln.endX = x;
            if (y > getHeight())
                ln.endY = getHeight();
            else if (y < 0)
                ln.endY = 0;
            else
                ln.endY = y;
        }
        /**
         * 解决鼠标焦点超出面板(线的中间坐标)
         * */
        private void constructMiddleP(Line ln, int x, int y) {

            if(ln.getLineShape()!=2){
                ln.middleX = ln.startX;
                ln.middleY = ln.endY;
            }else{
                if (x > getWidth())
                    ln.middleX = getWidth();
                else if (x < 0)
                    ln.middleX = 0;
                else
                    ln.middleX = x;
                if (y > getHeight())
                    ln.middleY = getHeight();
                else if (y < 0)
                    ln.middleY = 0;
                else
                    ln.middleY = y;
            }
        }

        @Override
        /**
         * 鼠标点击面板选择画线(直线、曲线)
         * */
        public void mouseClicked(MouseEvent e) {
            if(e.getButton()==3){
                JPopupMenu  popup = new JPopupMenu();
                JMenu lineMenu=new JMenu("画直线");
                JMenu arcMenu=new JMenu("画曲线");
                lineTypeList=new ArrayList <LineType>();
                try {
                    lineTypeList=lineBusiness.getLineTypeList();

                } catch (Exception e2) {
                    throw new RuntimeException();
                }
                //直线
                for(LineType lineType:lineTypeList){
                    JMenuItem lineItem = new JMenuItem(lineType.getName());
                    lineMenu.add(lineItem);
                    lineMenu.addSeparator();
                    lineItem.addActionListener(new LineAction());
                }
                //曲线
                for(LineType lineType:lineTypeList){
                    JMenuItem arcItem = new JMenuItem(lineType.getName());
                    arcMenu.add(arcItem);
                    arcMenu.addSeparator();
                    arcItem.addActionListener(new ArcAction());
                }
                popup.add(lineMenu);
                popup.add(arcMenu);
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        /**
         * 鼠标移动判断光标
         * */
        public void mouseMoved(MouseEvent e) {
            /** 判断是否移动到某直线上或者直线的端点上 
             * setCursor为指定的光标设置光标图像。
             * **/
            EquRealTimeMonitor.jf.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));//  +
            if (pressIndex != 3)
                pressIndex = 0;
            // 先清空
            for (Line line : lines) {
                line.isSelectP0 = false;
                line.isSelectP1 = false;
                line.isSelectP2 = false;
                line.isSelected = false;
            }
            if (pressIndex == 3) {
                EquRealTimeMonitor.jf.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
                return;
            }
            // 判断是否选中直线,若是则将光标改变
            for (Line line : lines) {
                if (line.contains(e.getX(), e.getY())) {
                    middleFlag=false;
                    line.isSelected = true;
                    pressIndex = 1;
                    EquRealTimeMonitor.jf.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
                    break;
                } 
            }
            // 如果选中了某条直线,再判断该直线的端点是否被选中
            if (selectedLine != null) {
                middleFlag=false;
                Line line = selectedLine;
                Point p = new Point(e.getX(), e.getY());
                p1 = new Point(line.startX, line.startY); // 左端点
                p2 = new Point(line.endX, line.endY); // 右端点
                p3 = new Point(line.middleX, line.middleY); // 中间端点

                if (isRange(p1, p)) {
                    line.isSelectP0 = true;
                    pressIndex = 2;
                    EquRealTimeMonitor.jf.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
                }
                if (isRange(p2, p)) {
                    line.isSelectP1 = true;
                    pressIndex = 2;
                    EquRealTimeMonitor.jf.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
                }
                if(isRange(p3,p)){
                    line.isSelectP2 = true;
                    pressIndex = 2;
                    middleFlag=true;
                    EquRealTimeMonitor.jf.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
                }
            }
        }
        @Override
        /**
         * 鼠标摁下事件
         * */
        public void mousePressed(MouseEvent e) {
            switch (pressIndex) {
            case 0:
                selectedLine = null;
                for (Line line : lines) {
                    line.isSelectP0 = false;
                    line.isSelectP1 = false;
                    line.isSelectP2 = false;
                    line.isSelected = false;
                }
                break;
            case 1:
                for (Line line : lines) {
                    if (line.isSelected) {
                        selectedLine = line;
                        break;
                    }
                }
                tmpSelectedLine = new Line();
                tmpSelectedLine.setLineType(selectedLine.getLineType());
                tmpSelectedLine.lineShape=selectedLine.lineShape;
                tmpSelectedLine.startX = selectedLine.startX;
                tmpSelectedLine.endX = selectedLine.endX;
                tmpSelectedLine.startY = selectedLine.startY;
                tmpSelectedLine.endY = selectedLine.endY;
                tmpSelectedLine.middleX = selectedLine.middleX;
                tmpSelectedLine.middleY = selectedLine.middleY;
                tmpSelectedLine.constructShape( );
                oldPoint = new Point(e.getX(), e.getY());

                break; 
            case 2:
                break;
            case 3:
                inLine = new Line();
                inLine.startX = e.getX();
                inLine.startY = e.getY();
                inLine.setLineType(linetype);

                break;
            default:
                break;
            }
        }

        @Override
        /**
         * 鼠标拖动事件
         * */
        public void mouseDragged(MouseEvent e) {

            switch (pressIndex) {
            case 0:
                break;
            case 1:
                Point point = new Point(e.getX(), e.getY());
                int lenx = point.x - oldPoint.x;
                int leny = point.y - oldPoint.y;
                tmpSelectedLine.startX = selectedLine.startX + lenx;
                tmpSelectedLine.endX = selectedLine.endX + lenx;
                tmpSelectedLine.startY = selectedLine.startY + leny;
                tmpSelectedLine.endY = selectedLine.endY + leny;
                tmpSelectedLine.middleX = selectedLine.middleX+ lenx;
                tmpSelectedLine.middleY = selectedLine.middleY+ leny;
                tmpSelectedLine.constructShape( );
                isDragge = true;
                break;
            case 2:
                Line line = selectedLine;// lines.get(selectPointInWhichLine);
                if (line.isSelectP0) {
                    constructStartP(line, e.getX(), e.getY());
                }
                if (line.isSelectP1) {
                    constructEndP(line, e.getX(), e.getY());
                }
                if (line.isSelectP2) {//2 曲线 1 折线 0 直线
                    if(!(line.getLineShape()==2)){
                        line.lineShape=1;
                    }
                    constructMiddleP(line, e.getX(), e.getY());
                }
                line.constructShape( );

                break;
            case 3:
                //判断是否超出面板
                constructEndP(inLine, e.getX(), e.getY());
                //对线的形状处理
                inLine.constructShape( );
                break;
            default:
                break;
            }
            repaint();
        }

        @Override
        /**
         * 鼠标释放事件
         * */
        public void mouseReleased(MouseEvent e) {
            switch (pressIndex) {
            case 0:
                break;
            case 1:
                Point point = new Point(e.getX(), e.getY());
                if(!middleFlag){
                    try {
                        int lenx = point.x - oldPoint.x;
                        int leny = point.y - oldPoint.y;
                        selectedLine.startX += lenx;
                        selectedLine.startY += leny;
                        selectedLine.endX += lenx;
                        selectedLine.endY += leny; 
                        selectedLine.middleX += lenx;
                        selectedLine.middleY += leny; 
                        selectedLine.constructShape( );

                        lineBusiness.updateLine(selectedLine); 
                    } catch (Exception e2) {
                        throw new RuntimeException();
                    }
                    tmpSelectedLine = null;
                    //返回此鼠标事件是否为该平台的弹出菜单触发事件
                    if (!isDragge && e.isPopupTrigger()) {
                        JPopupMenu  popup = new JPopupMenu();
                        JMenuItem removeItem = new JMenuItem("删除线条");
                        JMenuItem updateItem = new JMenuItem("修改线长");
                        popup.add(removeItem);
                        popup.addSeparator();
                        popup.add(updateItem);
                        removeItem.addActionListener(new RemoveAction());
                        updateItem.addActionListener(new UpdateAction());
                        popup.show(e.getComponent(), e.getX(), e.getY());
                    }
                    isDragge = false;
                }else{
                    try {
                        selectedLine.lineShape=1;
                        selectedLine.startX = selectedLine.startX;
                        selectedLine.startY = selectedLine.startY;
                        selectedLine.endX = selectedLine.endX;
                        selectedLine.endY = selectedLine.endY;
                        selectedLine.middleX = e.getX();
                        selectedLine.middleY = e.getY();
                        selectedLine.constructShape( );

                        lineBusiness.updateLine(selectedLine);
                    } catch (Exception e2) {
                        throw new RuntimeException();
                    }
                    tmpSelectedLine = null;
                    isDragge = false;
                }
                break;
            case 2:
                try {
                    Line line = selectedLine;

                    if (line.isSelectP0) {
                        constructStartP(line, e.getX(), e.getY());
                    }
                    if (line.isSelectP1) {
                        constructEndP(line, e.getX(), e.getY());
                    }
                    if (line.isSelectP2) {
                        constructMiddleP(line, e.getX(), e.getY());
                    }
                    lineBusiness.updateLine(line);
                    line.constructShape( );
                } catch (Exception e2) {
                    throw new RuntimeException();
                }
                break;
            case 3:
                if(cureFlag){
                    inLine.setLineShape(2);
                }else{
                    inLine.setLineShape(0);
                }
                constructEndP(inLine, e.getX(), e.getY());
                inLine.constructShape( );
                //规定长度必须大于5
                if(inLine.length>5){
                    try {

                        int id=lineBusiness.getMaxId();
                        inLine.setId(id+1);
                    } catch (Exception e2) {
                        throw new RuntimeException();
                    }
                    LineLengthDialog   lineLength=new LineLengthDialog(EquRealTimeMonitor.jf,inLine);
                    lineLength.setVisible(true);
                    boolean ok_cancel=lineLength.getClickSource();
                    if(ok_cancel){
                        lines.add(inLine);
                        /*selectedLine = inLine;
                        selectedLine.isSelected = true;*/
                    }
                    inLine = null;
                    pressIndex = 0;
                    break;
                }

            default:
                break;
            }
            // 统一在鼠标释放的时候重绘
            repaint();
        }
    }
    /**
     * 删除线条类
     * */
    class RemoveAction extends AbstractAction {

        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {

            Object[] options = { "OK", "CANCEL" };
            int op=JOptionPane.showOptionDialog(null, "确定删除???", "Warning", 
                    JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                    null, options, options[0]);

            if(op==0){
                int id=selectedLine.getId();
                try {
                    try {
                        lineBusiness.removeLine(id);
                    } catch (Exception e2) {
                        throw new RuntimeException();
                    }
                    if (lines.remove(selectedLine)){
                        selectedLine = null;
                        pressIndex = 0;
                    } 
                } catch (Exception e2) {
                    JOptionPane.showMessageDialog(null, "数据库删除线条失败!!!");
                }
            }
            repaint();
        }
    } 
    /**
     * 修改线条长度类
     * */
    class UpdateAction extends AbstractAction {

        private static final long serialVersionUID = 1L;
        private JTextPane jtp;
        private JTextField jtp2;
        private Line myLine2;
        @Override
        public void actionPerformed(ActionEvent e) {
            //线条不为空
            int id=selectedLine.getId();
            final JDialog dialog = new JDialog(EquRealTimeMonitor.jf);
            dialog.setTitle("修改线长度");
            dialog.setModal(true);
            dialog.setSize(260, 200);
            dialog.setLocationRelativeTo(EquRealTimeMonitor.jf);
            dialog.setLayout(null);
            JLabel lineIDLabel=new JLabel(" 线  条  ID:");
            lineIDLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            lineIDLabel.setBounds(5, 10, 100, 30);
            JTextPane jtpId=new JTextPane();
            jtpId.setEditable(false);
            jtpId.setText(id+"");
            jtpId.setBounds(110, 11, 80, 20);
            JLabel beforeChangeLabel=new JLabel("修改前线条长度:");
            beforeChangeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            beforeChangeLabel.setBounds(5, 40, 100, 30);
            jtp=new JTextPane();
            jtp.setEditable(false);
            jtp.setBounds(110, 45, 80, 20);
            try {
                myLine2= lineBusiness.getLineByID(id);
            } catch (Exception e2) {
                throw new RuntimeException();
            }
            jtp.setText(myLine2.getDistance()+"");
            JLabel afterChangeLabel=new JLabel("修改后线条长度:");
            afterChangeLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            afterChangeLabel.setBounds(5, 70, 100, 30);
            jtp2=new JTextField();
            jtp2.setBounds(110, 75, 80, 20);
            JPanel jp=new JPanel();
            JButton confirm=new JButton("确定");
            JButton cancel=new JButton("取消");
            jp.add(confirm);
            jp.add(cancel);
            jp.setBounds(0, 110, 280, 80);
            dialog.add(jp);
            dialog.add(lineIDLabel);
            dialog.add(beforeChangeLabel);
            dialog.add(jtpId);
            dialog.add(jtp);
            dialog.add(afterChangeLabel);
            dialog.add(jtp2);
            jtp2.addKeyListener(new KeyListener() {
                private int count;
                @Override
                public void keyTyped(KeyEvent e) {
                    int keyChar = e.getKeyChar();                 
                    if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9 || keyChar==KeyEvent.VK_PERIOD){
                        if(keyChar==KeyEvent.VK_PERIOD){
                            count++;
                            if(count>=2){
                                e.consume();
                            }
                        }
                    }else{ // 如果输入的不是数字则屏蔽输入
                        e.consume(); //关键,屏蔽掉非法输入  
                    } 
                }
                @Override
                public void keyReleased(KeyEvent arg0) {
                }
                @Override
                public void keyPressed(KeyEvent arg0) {
                }
            });
            confirm.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    try {

                        String dis=jtp2.getText();
                        if(dis!=null){
                            myLine2.setDistance(Double.parseDouble(dis));
                            lineBusiness.updateLine(myLine2);
                            //changeLineLength(myLine2);
                            Iterator<Line> iterator= lines.iterator();
                            while(iterator.hasNext()){
                                Line line=iterator.next();
                                if(line.getId()==myLine2.getId()){
                                    line.setDistance(myLine2.getDistance());
                                    dialog.dispose();
                                    return;
                                }
                            }
                        }

                    } catch (Exception e2) {
                        try {
                            throw new Exception();
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }}
            });

            cancel.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent arg0) {
                    pressIndex=0;
                    dialog.dispose();
                }
            });
            dialog.setVisible(true);
        }
    } 
    /**
     * 选择画直线的类
     * */
    class LineAction extends AbstractAction {

        private static final long serialVersionUID = 1L;
        @Override
        public void actionPerformed(ActionEvent e) {
            try {

                String lineTypeName=((JMenuItem)e.getSource()).getText();
                LineType lineType=  lineBusiness.getLineTypeByName(lineTypeName);
                pressIndex=3;
                cureFlag=false;
                setMyLineType(lineType);
            } catch (Exception e2) {
                throw new RuntimeException();
            }
        }
    } 
    /**
     * 选择画曲线的类
     * */
    class ArcAction extends AbstractAction {
        private static final long serialVersionUID = 1L;
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                String lineTypeName=((JMenuItem)e.getSource()).getText();
                LineType lineType=  lineBusiness.getLineTypeByName(lineTypeName);
                cureFlag=true;
                pressIndex=3;
                setMyLineType(lineType);    
            } catch (Exception e2) {
                throw new RuntimeException();
            }

        }
    }
    /**
     * 判断两个点是否离得很近 近的标准用range来横来
     * @param a 第一个点坐标 
     * @param b  第二点坐标
     * @return 离得近为真,否则为假
     */
    private boolean isRange(Point a, Point b) {
        if (Math.hypot(a.x - b.x, a.y - b.y) < range)//返回 sqrt(x2 +y2),没有中间溢出或下溢。
            return true;
        return false;
    }
    // 画图的按钮的背景和标签
    protected void paintComponent(Graphics g2) {
        super.paintComponents(g2);
        //增加网格背景
        ImageIcon icon=new ImageIcon("configuration/sourceRealTimeMonitor/realTimeMonitor_Image/equConn_img\\-1.jpg");
        g2.drawImage(icon.getImage(),0, 0,this);
        Graphics2D g = (Graphics2D) g2;
        //消除锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        //Paint 接口定义如何为 Graphics2D 操作生成颜色模式。
        Paint oldPaint = g.getPaint();
        /*
         * Stroke 接口允许 Graphics2D 对象获得一个 Shape,该 Shape 是指定 Shape 的装饰轮廓
         * ,或该轮廓的风格表示形式。描绘一个 Shape 如同使用一支具有适当大小和形状的画笔描绘其轮廓
         * */
        Stroke s = g.getStroke();
        //画线
        for (Line line : lines) {

            LineType lineType=  line.getLineType();
            g.setStroke(new BasicStroke(lineType.getWeight()));
            int colorX= lineType.getColorX();
            int colorY= lineType.getColorY();
            int colorZ= lineType.getColorZ();
            g.setPaint(new Color(colorX, colorY, colorZ)); 
            GeneralPath shape = line.shape;
            g.setPaint(new Color(colorX, colorY, colorZ)); 
            g.draw(shape);
            g.fill(shape);
            /*
             * 画线长
             * */
            g.setPaint(Color.yellow); 
            g.drawString(line.getDistance()+"", line.middleX+10, line.middleY);
        }

        // 如果被选择,那么直线的两端应该会有两个bai点
        if (selectedLine != null) {
            Line line = selectedLine;
            int side = (int) line.getLineType().getWeight();
            if(side==0){
                side=4;
            }
            g.setPaint(Color.white);
            g.drawOval((int) (line.startX - side / 1.5), line.startY - side / 2, side, side+1);
            g.drawOval((int) (line.endX - side / 1.5), line.endY - side / 2, side, side+1);
            g.fillOval((int) (line.startX - side / 1.5), line.startY - side / 2, side, side+1);
            g.fillOval((int) (line.endX - side / 1.5), line.endY - side / 2, side, side+1);
            g.drawOval((int) (line.middleX - side / 1.5), line.middleY - side / 2, side, side+1);
            g.fillOval((int) (line.middleX - side / 1.5), line.middleY - side / 2, side, side+1); 
        }
        if (tmpSelectedLine != null) {
            LineType lineType=  tmpSelectedLine.getLineType();
            g.setStroke(new BasicStroke(lineType.getWeight()));
            g.setPaint(Color.BLACK);
            GeneralPath shape = tmpSelectedLine.shape;
            g.fill(shape);
        }

        // 画正在产生的直线
        if (inLine != null) {
            LineType lineType=  inLine.getLineType();
            g.setStroke(new BasicStroke(lineType.getWeight()));
            int colorX= lineType.getColorX();
            int colorY= lineType.getColorY();
            int colorZ= lineType.getColorZ();
            g.setPaint(new Color(colorX, colorY, colorZ)); 
            GeneralPath shape = inLine.shape;
            if (shape != null)
                g.fill(shape);
        }
        g.setPaint(oldPaint);
        g.setStroke(s);
        g2.dispose();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        if(lineFlag){
            try {

                if(lines!=null&&lines.size()>0){
                    lines.clear();
                }
                ArrayList<Equipment> equPosList = interfaceBussiness.getPostionEqu(EquConnectionEditView.allEquList,module);
                 List<Integer> lineIdList=new ArrayList<Integer>();
                lineIdList=lineBusiness.getLineIdList(equPosList);
                 List<Line> lineList =new ArrayList<Line>();
                  lineList = lineBusiness.getLineList(lineIdList);
                if(lineList!=null){
                    for(int i=0;i<lineList.size();i++){

                        Line line=new Line();
                        line.setId(lineList.get(i).getId());
                        line.setDistance(lineList.get(i).getDistance());
                        line.setLineShape(lineList.get(i).getLineShape());
                        line.setLen(lineList.get(i).getLen());
                        line.setStartX(lineList.get(i).getStartX());
                        line.setStartY(lineList.get(i).getStartY());
                        line.setEndX(lineList.get(i).getEndX());
                        line.setEndY(lineList.get(i).getEndY());
                        line.setMiddleX(lineList.get(i).getMiddleX());
                        line.setMiddleY(lineList.get(i).getMiddleY());
                        line.setLineType(lineList.get(i).getLineType());
                        line.constructShape( );
                        lines.add(line);
                        lineFlag=false;
                    }
                }

            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
        repaint();
        paintComponents(g);
    }
    /**
     * 用于绘制新线时给线设置线类型对象
     * */
    public  void setMyLineType(LineType lineType){
        linetype=lineType;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值