我必須在HoltSoft的Ready to Program中使用Console類。我不應該使用揮杆,所以如果我不能沒有揮杆的話,請不要忽視這一點。爲什麼點擊時不顯示圓圈?
//imports
import java.awt.*;
import java.awt.event.*;
import hsa.*;
public class DrawLines extends Panel implements MouseListener, MouseMotionListener
{
Console c;
int startX, startY, prevX, prevY; //mouse coordinates
private boolean dragging; //whether or not the mouse is being dragged
MouseEvent e;
public DrawLines()
{
c = new Console(); //creates console window
addMouseListener (this); //detects press/release
addMouseMotionListener (this);//detects dragging
}
public void mousePressed (MouseEvent e)
{
while (!dragging)
{
try
{
startX = e.getX();//get the
startY = e.getY();//original co-ordinates
dragging = true;
}
catch (NullPointerException q) //because I kept getting this error
{
}
}
}
public void mouseDragged (MouseEvent e)
{
while (dragging)
{
try
{
int x = e.getX(); //gets and
int y = e.getY(); //updates
prevX = x; //the mouse
prevY = y; //coordinates
}
catch (NullPointerException q)//because I kept getting this error
{
}
}
}
public void mouseReleased (MouseEvent e)
{
dragging = false; //stopped dragging
}
public void drawTheLine()
{
mousePressed (e);
mouseDragged (e);
c.setColor (Color.black);
c.fillOval (prevX, prevY, 50, 50); //draws a circle where the mouse is
mouseReleased (e);
}
public void mouseMoved (MouseEvent e){}
public void mouseEntered (MouseEvent e){}
public void mouseExited (MouseEvent e){}
public void mouseClicked (MouseEvent e){}
public static void main (String[] args)
{
DrawLines a = new DrawLines();
a.drawTheLine();
}
}
我一直試圖在控制檯中使用MouseListener和MouseMotionListener。起初,該程序不斷給我錯誤,所以我添加了try/catch結構。現在它不會崩潰,但屏幕上不顯示任何內容。爲什麼?幫幫我?
如果我不應該使用try/catch來忽略它,我該怎麼辦?
我不允許在此程序中使用Console()以外的任何其他功能。這是一門課程任務。
當你得到一個異常,通常意味着什麼是錯的。僅僅忽視它(帶有空白的捕獲聲明)將不能解決潛在的問題。 – assylias
林不知道,什麼是控制檯()?你應該使用'JPanel'並重載'paintComponent' –
我覺得while循環的使用是相當危險的......這個程序是否完成?在我看來,它有很多可能無限期掛起,如mouseDragged(..) –