2014-04-01 206 views
-2

對於這個問題,我聽起來確實很愚蠢,但我對我的for循環有困難。爲什麼我的代碼運行for循環超過5次?

這是我遇到的麻煩的部分代碼。

Scanner input = new Scanner(System.in); 
int number; 
for(int i = 0;i < 5;i++) { 
    System.out.print("Enter 5 integers:"); 
    number = input.nextInt(); 
} 

當我運行它打印輸出循環超過5次。

public class BarGraph extends JPanel 
{ 

    public void paintComponent(Graphics g) 
    { 

     Scanner input = new Scanner(System.in); 
     // super.paintComponent(g); 
     int number; 

     for(int i = 0;i < 5;i++) 
     { 
      System.out.print("Enter 5 integers:"); 
     number = input.nextInt(); 
     // g.drawRect(10 * i, 10 * i, 100 * number, 10);  
     } 
    } 
} 

運行BarGraphTest

public class BarGraphTest 
{ 
    public static void main(String[] args) 
    { 
     BarGraph panel = new BarGraph(); 
     JFrame application = new JFrame(); 
     application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     application.add(panel); 
     application.setSize(300, 300); 
     application.setVisible(true); 
    } 
} 

基本上我想要做的是閱讀5點的整數,只是顯示他們的JPanel線條形圖。

+4

罪魁禍首是'input.nextInt();'。使用'input.nextLine();'代替。 – Tiny

+4

比5還要多少倍? –

+0

打印出來的值'i' – Rogue

回答

4

您已經夾雜了圖形狀態的變化。 paintComponent被鞦韆"when it needs to be"調用,在這種情況下,無論出於何種原因,Swing都確定需要2次重繪。

如果你的程序被寫入的方式,它關心何時或如何往往paintComponent是叫你將可能有問題。您應該只有paintComponent詢問某個對象的當前狀態並相應地繪製。

你的具體情況

Depepending 5號應該在傳遞給光柱

  • 的條形圖的構造從用戶請求的構造通過以下方式

    • 一個提供(不是我喜歡的,但會起作用)
    • 傳遞給BarGraph的方法
    • 傳遞給BarGraph的某個其他對象。

    他們絕對不應該從paintComponent內的用戶請求,這意味着每次重繪是nessissary(如移動,調整大小,改變焦點,被其他框架等隱藏)的數字將是從用戶重新請求。

    你也可能想與super.paintComponent(g)啓動paintComponent方式,但will again be situation dependant

  • 相關問題