自由画线实现不了??
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
public class J_DrawDemo extends JFrame implements ActionListener
{
panel pl=new panel();//生成panel的一个对象
JToolBar toolBar;//定义各个组件
JButton jb1;
JButton jb2;
JButton jb3;
JButton jb4;
public J_DrawDemo()
{
super("画图程序");
toolBar=new JToolBar();//添加工具条
jb1=new JButton(" 画直线 ");
jb2=new JButton(" 画椭圆 ");
jb3=new JButton(" 画矩形 ");
jb4=new JButton(" 自由绘图 ");
jb1.addActionListener(this);//注册按钮监听器
jb2.addActionListener(this);
jb3.addActionListener(this);
jb4.addActionListener(this);
toolBar.add(jb1);//在工具条上加入按钮
toolBar.add(jb2);
toolBar.add(jb3);
toolBar.add(jb4);
ButtonGroup buttonGroup=new ButtonGroup();//定义一个按钮组,实现按钮互斥
Container cp=getContentPane();//获得容器
cp.add(toolBar,BorderLayout.NORTH);//将工具条加入容器
cp.add(pl,BorderLayout.CENTER);//将pl加入容器
setBounds(250,250,400,400);
setVisible(true);//设置窗体可见
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//退出方式
}
public void actionPerformed(ActionEvent e)//按钮实现动作并执行
{
if(e.getSource()==jb1)
pl.shape=0;
if(e.getSource()==jb2)
pl.shape=1;
if(e.getSource()==jb3)
pl.shape=2;
if(e.getSource()==jb4)
pl.shape=3;
}
public static void main(String[] args)
{
new J_DrawDemo();//调用J_DrawDemo类构造函数
}
}
class panel extends JPanel implements MouseListener,MouseMotionListener//定义一个JPanel的字类
{
int shape=-1;
int startX=0,startY=0;
int endX=0,endY=0;
//int start_X=0,start_Y=0;
public panel()
{
this.setBackground(Color.white);
addMouseListener(this);//注册鼠标动作监听器
addMouseMotionListener(this);
}
//各个鼠标动作的实现
public void mouseReleased(MouseEvent e)
{
if(shape!=3)
{
endX=e.getX();
endY=e.getY();
repaint();
}
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
if(shape==3)
{
endX=e.getX();
endY=e.getY();
}
else
{
startX=e.getX();
startY=e.getY();
}
}
public void mouseDragged(MouseEvent e)
{
if(shape==3)//当为画自由线时拖动鼠标动作才执行
{
startX=endX;
startY=endY;
endX=e.getX();
endY=e.getY();
repaint();
}
}
public void mouseMoved(MouseEvent e){}
public void paint(Graphics g)//实现画图
{
super.paint(g);
switch(shape)
{
case 0:
g.drawLine(startX,startY,endX,endY);//画直线
break;
case 1:
int width=endX-startX;
int height=endY-startY;
g.drawOval(startX,startY,width,height);//画椭圆
break;
case 2:
width=endX-startX;
height=endY-startY;
g.drawRect(startX,startY,width,height);//画矩形
break;
case 3:
g.drawLine(startX,startY,endX,endY);//自由画线
break;
}
}
}
自由画线实现不了