JAVA 求助 就是如何用鼠标监听事件调用Graphics 画的线条和矩形 接着画 ? 不会画完 20

JAVA求助就是如何用鼠标监听事件调用Graphics画的线条和矩形接着画?不会画完一个后重新开始画... JAVA 求助 就是如何用鼠标监听事件调用Graphics 画的线条和矩形 接着画 ? 不会画完一个后重新开始画 展开
 我来答
打伞鱼Aw
2016-04-25 · TA获得超过7266个赞
知道大有可为答主
回答量:7524
采纳率:90%
帮助的人:1607万
展开全部
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;

public class Test{
public static void main(String[] args){
MyFrame frame = new MyFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class MyFrame extends JFrame implements ActionListener{

MyPanel panel = new MyPanel();

JToolBar t;
JButton obj1;
JButton obj2;
JButton obj3;

public MyFrame(){

obj1 = new JButton("Line");
obj2 = new JButton("yuan");
obj3 = new JButton("juxing");
t = new JToolBar();
obj1.addActionListener(this);
obj2.addActionListener(this);
obj3.addActionListener(this);

t = new JToolBar();
t.add(obj1);
t.add(obj2);
t.add(obj3);

setTitle("DrawTest");
setSize(W,H);

Container contentPane = getContentPane();

contentPane.add(t,BorderLayout.NORTH);
contentPane.add(panel,BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e){
if(e.getSource()==obj1)
panel.shape=0;//直线
if(e.getSource()==obj2)
panel.shape=1;//円
if(e.getSource()==obj3)
panel.shape=2;//长方形
}

public static final int W = 400;
public static final int H = 400;
}

class MyPanel extends JPanel implements MouseListener{

private ArrayList<Point> pointList = new ArrayList<Point>();

int shape = -1;
int x1 = 0,y1 = 0;
int x2 = 0,y2 = 0;

MyPanel(){
addMouseListener(this);
}

public void mousePressed(MouseEvent e){

x1 = e.getX();
y1 = e.getY();
pointList.add(new Point(x1,y1));

}
public void mouseReleased(MouseEvent e){

x2 = e.getX();
y2 = e.getY();
pointList.add(new Point(x2,y2));
repaint();

}

public void mouseClicked(MouseEvent e){
}

public void mouseMoved(MouseEvent e){
}

public void mouseEntered(MouseEvent e){
}

public void mouseExited(MouseEvent e){
}

public void paintComponent(Graphics g){
super.paintComponent(g);

for(int i =0 ;i<pointList.size()-1;i=i+2){
Point p1 = pointList.get(i);
Point p2 = pointList.get(i+1);

switch(shape){

case 0:
g.drawLine(p1.x,p1.y,p2.x,p2.y);

break;
case 1:

int width1 = p2.x - p1.x;
int height1 = p2.y - p1.y;
g.drawOval(p1.x,p1.y,width1,height1);
break;
case 2:
int width2 = p2.x - p1.x;
int height2 = p2.y - p1.y;
g.drawRect(p1.x,p1.y,width2,height2);
break;

default:
System.out.println("please once again!");
break;
}
}
}
}
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式