2016-04-25 55 views
1

所以我想創建一個程序,創建一個帶有8個JButton的JPanel窗口。我不是重複JButton,而是用所有的JButton創建一個數組,並創建一個循環來創建它們。自從我創建了一個數組後,構造函數將不會在循環完成後繼續。直到我將JButton放入一個數組,纔會發生這種情況。java jbutton數組防止構造函數完成運行

public class Gui extends JFrame { 

private JButton Subject[] = new JButton[7]; 
private String SubjNames[] = {"Length", "Mass", "Currency", "Temperature", "Time", "Speed", "Data", "Cooking"}; 

private int SubjectLocX = 40; 
private int SubjectLocY = 50; 




public Gui(){ 

    super("Converter"); 
    setLayout(null); 

    System.out.println("yes"); 

    for (int i = 0; i<8; i++) { 
    Subject[i] = new JButton(SubjNames[i]); 
    Subject[i].setLocation(SubjectLocX,SubjectLocY); 
    Subject[i].setSize(200,50); 
    add(Subject[i]); 
    if (i < 3) { 
     SubjectLocX = 40; 
     SubjectLocY += 100; 
    } else if (i == 3) { 
     SubjectLocY = 50; 
    } else if (i > 3) { 
     SubjectLocX = 330; 
     SubjectLocY += 100; 
     } 
    } 

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setSize(600,500); 
    setLocation(400,200); 
    setVisible(true); 



    } 
} 

是的,我輸入了所有需要的東西,我在一個單獨的類中創建了一個類的對象。它會運行,但循環後構造函數不會繼續。如果刪除數組「Subject [i]」的行,構造函數結束並出現窗口,但是對於數組,它不會。爲什麼??

+0

記住,當你聲明一個數組爲'new JButton [7]'意味着你只分配了7個元素 – MadProgrammer

回答

2

也許是因爲你有一個包含7個元素的JButton數組,並且你正在初始化8個元素。更改聲明private JButton Subject[] = new JButton[8],你會修復。

+0

哇,我覺得愚蠢的哈哈,謝謝 – airide101

+0

不要擔心,發生哈哈。不用謝 :) – MingiuX

0

您的代碼workinf對我來說,你只是有一個數組越界的「for」循環,條件必須是for (int i = 0; i<7; i++)但一切工作正常,記得打電話「new Gui().setVisible(true);