已结贴√
问题点数:20 回复次数:3
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;
}
}
}
}