2009-11-11 146 views
1
Test[] array = new Test[3]; 

    array[0] = new RowBoat("Wood", "Oars", 10); 
    array[1] = new PowerBoat("Fiberglass", "Outboard", 35); 
    array[2] = new SailBoat("Composite", "Sail", 40); 

我有上面的数组,我需要显示结果到一个摇摆的GUI与下一个按钮,将显示第一个索引值,当下一个按钮被点击时,它会显示下一个索引值等等。爪哇,页通过阵列

for (int i=0;; i++) { 
      boatMaterialTextField.setText(array[i].getBoatMaterial()); 
      boatPropulsionField.setText(array[i].getBoatPropulstion()); 
    } 

我有上面的代码工作,当然它显示数组中的最后一项。

我的问题是:我将如何显示数组中的第一个索引,并且当用户单击下一个显示数组中的下一个项目以及点击后退按钮时转到上一个索引?

简而言之,我需要在单击按钮时遍历每个索引。

+2

您的for循环对我来说看起来像一个无限循环。你确定你输入正确吗? – Asaph 2009-11-11 03:21:13

+0

你的意思是你只显示10,35,40的值吗? 该循环会给你一个无限循环。因为你没有任何条件说什么时候停止。 例如 for(int i = 0; i Treby 2009-11-11 03:23:11

+0

我用这里的提示说明长度检查是多余的。这不准确吗? http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/java/p_fastiteratingarrayorvectorjava.jsp – 2009-11-11 03:32:41

回答

1

你不需要循环。当框架第一次加载时,您可以简单地显示数组中的第一个项目。然后您可以创建下一个按钮。

JButton nextBtn; 
int currentIndex; 

... 

currentIndex = 0; 
//display the first item in the array. 
boatMaterialTextField.setText(array[currentIndex].getBoatMaterial()); 
boatPropulsionField.setText(array[currentIndex].getBoatPropulstion()); 

nextBtn = new JButton("Next>>"); 
nextBtn.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e){ 
     if(currentIndex < array.length){ 
     boatMaterialTextField.setText(array[++currentIndex].getBoatMaterial()); 
     boatPropulsionField.setText(array[currentIndex].getBoatPropulstion());  
     } 
    } 
}); 

您可以添加另一个按钮以前,根本每次确保检查它永远不会变成负递减CURRENTINDEX。

+0

这是光滑的文森特,非常好。谢谢 – 2009-11-11 03:28:57