[英]Java GUI with Arraylist
我的Java Arraylist有一个问题:单击上一个按钮时,它不会获取最后一个元素的索引。
注意:InfoStudent是一个单独的类,其中包含所有学生信息,例如id,姓名和电子邮件; 并且arraylist学生包含新学生的信息。 我不确定我的问题是否是像student.get这样的索引(因为索引从0开始,获取当前学生的ID并减去1)。 我的截图:
我的代码:
JButton btnFirst = new JButton("First");
btnFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textFieldId.setText(Integer.toString(student.get(0).getId()));
textFieldName.setText(student.get(0).getName());
txtEmailbox.setText(student.get(0).getEmail());
}
});
btnFirst.setBounds(10, 215, 89, 22);
frame.getContentPane().add(btnFirst);
JButton btnPrev = new JButton("Prev");
btnPrev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
current = Integer.parseInt(textFieldId.getText());
if(current== student.size()){
current= 0;
}
else {
current = current-1;
}
textFieldId.setText(Integer.toString(student.get(current).getId()));
textFieldName.setText(student.get(current).getName());
txtEmailbox.setText(student.get(current).getEmail());
//student.get(current).getId() is not working
}
});
btnPrev.setBounds(122, 215, 89, 22);
frame.getContentPane().add(btnPrev);
JButton btnNext = new JButton("Next");
btnNext.setBounds(230, 215, 89, 23);
frame.getContentPane().add(btnNext);
JButton btnLast = new JButton("Last");
btnLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textFieldId.setText(Integer.toString(student.get(student.size()-1).getId()));
textFieldName.setText(student.get(student.size()-1).getName());
txtEmailbox.setText(student.get(student.size()-1).getEmail());
}
});
btnLast.setBounds(329, 215, 89, 23);
frame.getContentPane().add(btnLast);
}
当前变量是学生ID,而不是数组中的索引来解决它,最好的解决方案是添加将当前索引保存在学生数组中的变量
首先,不要这样做, btnFirst.setBounds(10, 215, 89, 22);
。 您应该避免使用null布局和使用setBounds(...)
进行组件放置,因为这会导致非常不灵活的GUI,尽管它们在一个平台上看起来可能不错,但在大多数其他平台或屏幕分辨率上看起来却很糟糕,而且很难做到更新和维护。
接下来,将当前索引存储在一个字段中,然后根据需要更改其值。
例如,在下一个:
currentIndex++; // increment it
currentIndex %= myCollection.size(); // mod it so that you don't go out of bounds
和以前一样:
currentIndex--;
currentIndex += myCollection.size(); // mod doesn't work well w/ neg numbers
currentIndex %= myCollection.size();
更改
if(current== student.size()){
current= 0;
}
else {
current = current-1;
}
至
if(current < 0 || current >= student.size()){
current = 0;
}
else {
//Do Not Change the value since it is valid
}
您可以使用一个字段来存储当前索引值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.