第1楼 2007-04-20 12:08 hanliufang2000 写道:
JAVA初级问题:画线段产生初值问题
下面的代码是为了用鼠标在容器上画条线段,但是xValue1,yValue1,xValue2,yValue出现了初值,应该怎么解决
按下确定初点,拖动释放后确定第二个点
public class DrawLine extends JFrame {
private int xValue1 , yValue1 ,
xValue2 , yValue2 ;//定义两组坐标初值,让他们处于容器外面
private JLabel statusBar ;
public DrawLine()
{
super ( " Draw Line ");//容器名称为 draw pictures
statusBar = new JLabel() ;
getContentPane().add( statusBar , BorderLayout.SOUTH );//添加一标签,并定义在布局南面
addMouseListener(//增加鼠标监听器
new MouseAdapter(){
public void mousePressed( MouseEvent event )//覆盖原来的mousePressed()
{
xValue1 = event.getX();
yValue1 = event.getY();
repaint();
}
public void mouseReleased( MouseEvent event )//覆盖原来的mouseReleased()
{
xValue2 = event.getX();
yValue2 = event.getY();
repaint();
}
}
);
setSize( 800, 600);//容器大小800*600
setVisible( true );//容器可见性:可见
}
public void paint( Graphics g )
{
g.drawLine( xValue2 , yValue2, xValue1 , yValue1 );//画矩形
statusBar.setText("初坐标 = ( "+xValue1+" , "+yValue1+" ) "+"末坐标 = ( "+xValue2+" , "+yValue2+" ) " );//在标签statusBar中显示所画矩形的面积(象素)
}
public static void main( String args[] )//主程序
{
DrawLine application = new DrawLine();
application.addWindowListener(
new WindowAdapter()
{
public void windowClosing ( WindowEvent event )
{
System.exit( 0 );
}
}
);
}
}