展开全部
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);
ButtonGroup buttonGroup = new ButtonGroup();
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;//长方形
panel.repaint(); //这里加一句
}
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;
int i = 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);
System.out.println(pointList.size());
for(int i =0;i < pointList.size()-1;i=i+2){
switch(shape){
case 0:Point p1 = pointList.get(i);
Point p2 = pointList.get(i+1);
g.drawLine(p1.x,p1.y,p2.x,p2.y);
break; //如果想让三个图形一起显示去掉这里的break;语句
case 1:p1 = pointList.get(i);
p2 = pointList.get(i+1);
int width1 = p2.x - p1.x;
int height1 = p2.y - p1.y;
g.drawOval(p1.x,p1.y,width1,height1);
break; //如果想让三个图形一起显示去掉这里的break;语句
case 2:p1 = pointList.get(i);
p2 = pointList.get(i+1);
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 agan!");
break;
}
}
}
}
2015-05-11
展开全部
JFrame 覆盖paint方法,使用Graphic 去画。
追问
菜鸟找你要源码啦!!!!!亲
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询