我正在製作一個簡單的貨幣轉換器GUI(沒什麼特別),因爲我將嘗試爲每次用戶打開應用程序時都包含實時匯率更新。創建佈局時,我決定簡單轉換3種貨幣(英鎊,美元和歐元)。我有2列中的相應標誌,每列都有3個標誌之一。一列是供用戶選擇初始貨幣,另一列是要交換的期望貨幣;如下所示Java中的循環問題
我已經創建了一個包含單詞「磅」,「美元」和「歐元」的字符串數組,並且我想將這些標籤放在標誌的左側(爲了清晰的應用程序用戶不是每個用戶都可能知道哪個貨幣屬於哪個國家
我創建了一個循環,它會創建一個標籤並將其分配到標誌的左側,它應該創建一個「磅」標籤,然後每次向Y軸向南移動一個「美元」然後是「歐元」,以便它們與標誌對齊,然後重置數組返回到正確的字符串,沿着x軸移動並再次重複。然而,它並沒有這樣做,我得到的唯一結果是第一個左邊的文字「磅」英國國旗;如下圖所示:下面
是我的代碼,如果任何人都可以,爲什麼發生這種情況見。
這是它增加了標誌,以面板的代碼
addToMain(GBP1, mainPage, 100,100,100,100); //alligns a United Kingdom Flag to left Column
addToMain(GBP2, mainPage, 375,100,100,100); //alligns a United Kingdom Flag to right Column
addToMain(USD1, mainPage, 100,200,100,100); //alligns a United States Flag to left Column
addToMain(USD2, mainPage, 375,200,100,100); //alligns a United States Flag to right Column
addToMain(EUR1, mainPage, 100,300,100,100); //alligns a European Union Flag to left Column
addToMain(EUR2, mainPage, 375,300,100,100); //alligns a European Union Flag to right Column
這是應該的文本標籤添加到標誌左側的環
currencyName = new String [] {"Pounds", "Dollars", "Euros"};
for(int i = 0; i <= 7; i++)
{
int count = 0; //declares a counter for the position in the currencyName array to grab the correct text for label
xLabelAlign = 50;
yLabelAlign = 100;
if(count == 3)
{
count = 0; //resets to create both columns of labels in the application moves to the next column.
xLabelAlign = 325;
yLabelAlign = 100;
}
JLabel temp = new JLabel(currencyName[count]); //creates a new label and names it the string at position count
temp.setFont(new Font("SERIF", Font.BOLD, 20));
temp.setForeground(Color.WHITE);
addToMain(temp, mainPage, xLabelAlign, yLabelAlign ,100,100); //adds it to the panel
yLabelAlign +=100; //moves position ready for the next text label.
count++; //grabs the next label in the currencyName string array.
}
這是向面板添加內容的方法。我已經使用了一套界限的方法來的東西添加到面板上,所以我可以定位他們,我想輕鬆
private void addToMain(JComponent c, JPanel p, int x, int y, int w, int h)
{
c.setBounds(x,y,w,h);
p.add(c);
}
任何幫助將不勝感激。
R.I.P.佈局管理器 – BackSlash
忘記'setBounds(x,y,w,h)',改爲使用'LayoutManager'。這裏是[Oracle教程](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html):) – NiziL
你應該使用'LayoutManager',你只能用這種方式編程到你的屏幕上;) – nachokk