我試圖創建一個簡單的小程序,可以繪製一個矩形,我有以下代碼:繪製在Java小程序的矩形
import java.util.Scanner;
import java.awt.Graphics;
import javax.swing.JApplet;
public class DrawShapes extends JApplet{
public void paint(Graphics canvas) {
Scanner reader = new Scanner(System.in);
System.out.println("How many sides do you want your shape to have: ");
int sides = reader.nextInt();
reader.close();
super.paint(canvas);
if(sides ==4){
canvas.drawRect(100, 50, 200, 200);
}
System.out.println("Done!");
}
}
我運行此代碼,並提示輸入多少面,當我我想輸入「4」
然後在左上角創建一個新的applet窗口,沒有任何錯誤。 但是,第二個我試圖擴大該applet以下錯誤打印到控制檯:
Exception in thread "AWT-EventQueue-1" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at DrawShapes.paint(DrawShapes.java:9)
at javax.swing.RepaintManager$4.run(RepaintManager.java:842)
at javax.swing.RepaintManager$4.run(RepaintManager.java:814)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:789)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:738)
at javax.swing.RepaintManager.access$1200(RepaintManager.java:64)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1732)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
此外,「小程序啓動」反覆在小程序窗口這樣: 「小程序啓動 小程序啓動 Applet的入門 小程序啓動 小程序啓動 小程序啓動 小程序啓動 小程序啓動 小程序啓動 小程序啓動 小程序啓動 小程序開始 小程序開始 小程序開始「 我的代碼是怎麼回事?
爲什麼要編寫一個小程序?如果是由於老師指定它,請將它們轉介給[爲什麼CS教師應該**停止**教Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should -stop教學-java的小應用程序/)。 –
是的,這是爲我的高中STEM課程和他給我們的書在他們的例子中使用小程序 –
不要在'paint()'或'paintComponent()'方法中讀取輸入內容。每次窗口重新繪製時它都會執行。 (在你的情況下,只有當它調整大小或打開) –