java实现画直线画圆_java 用鼠标画直线,圆,矩形的共存问题

已结贴√

问题点数:20 回复次数:3

ca56232b3bbedf9a539d07f37fffb99a.gif

3144d8b7615c79d9f638db40d5689d26.gif

a218af6549b45ee526caf607ebff1358.gif

0f8df0e29816ae721419de940fb833d1.gif

java 用鼠标画直线,圆,矩形的共存问题

再窗口上切换图形的时候,已经画好的图形也随之转换过来。

没有能够达到3种图形共存。怎么修改比较好呢?

就是想画直线的时候出直线,想画圆的时候出圆,但它们彼此共存再窗口上。

-------------------------------------

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 pointList = new ArrayList();

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

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;

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值