30/09/2018, 18:32
Hỏi về ArrayList trong Java
em có code thế này:
‘’’
package BT_DEMO;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
/**
*
* @author ADMIN64
*/
public class ThongTin_SinhVien extends javax.swing.JFrame {
DefaultListModel model = new DefaultListModel();
ArrayList<ThongTin> Infor = new ArrayList<ThongTin>();
ThongTin a = new ThongTin();
int j = 0;
public ThongTin_SinhVien() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTabbedPane1 = new javax.swing.JTabbedPane();
jInternalFrame1 = new javax.swing.JInternalFrame();
jPanel2 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel2 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
List = new javax.swing.JList();
jPanel3 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
tfMaSV = new javax.swing.JTextField();
tfTen = new javax.swing.JTextField();
tfTuoi = new javax.swing.JTextField();
btAdd = new javax.swing.JButton();
btRemove = new javax.swing.JButton();
btUpdate = new javax.swing.JButton();
btClear = new javax.swing.JButton();
jLabel1.setText("jLabel1");
jInternalFrame1.setVisible(true);
javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
jInternalFrame1Layout.setHorizontalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jInternalFrame1Layout.setVerticalGroup(
jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jScrollPane1.setViewportView(jList1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setBackground(new java.awt.Color(204, 255, 153));
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 0, 0));
jLabel2.setText("THÔNG TIN SINH VIÊN");
jLabel2.setOpaque(true);
jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
List.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 204)), "Danh Sách Sinh Viên", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 11), new java.awt.Color(255, 0, 0))); // NOI18N
List.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
ListValueChanged(evt);
}
});
jScrollPane2.setViewportView(List);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
);
jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 0, 0));
jLabel3.setText("Mã sinh viên:");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 0, 0));
jLabel4.setText("Họ và tên:");
jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 0, 0));
jLabel5.setText("Tuổi:");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tfMaSV)
.addComponent(tfTen)
.addComponent(tfTuoi, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tfMaSV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(24, 24, 24)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(tfTen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(20, 20, 20)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel5)
.addComponent(tfTuoi, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
btAdd.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btAdd.setText("Add");
btAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btAddActionPerformed(evt);
}
});
btRemove.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btRemove.setText("Remove");
btRemove.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btRemoveActionPerformed(evt);
}
});
btUpdate.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btUpdate.setText("Update");
btUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btUpdateActionPerformed(evt);
}
});
btClear.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btClear.setText("Clear");
btClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btClearActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(149, 149, 149)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(124, 124, 124)
.addComponent(btAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btClear, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 85, Short.MAX_VALUE)))
.addContainerGap())
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btAdd, btClear, btRemove, btUpdate});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btClear, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(12, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btAdd, btClear, btRemove, btUpdate});
pack();
}// </editor-fold>
private void btAddActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource() == btAdd){
if(tfTen.getText() == null){
JOptionPane.showMessageDialog(null, "Moi ban nhap ten!");
return;
}
else{
a.setTen(tfTen.getText());
}
if(tfMaSV.getText() == null){
JOptionPane.showMessageDialog(null, "Moi ban nhap MSSV");
return;
}
else{
a.setMsv(tfMaSV.getText());
}
if(tfTuoi.getText() == null){
JOptionPane.showMessageDialog(null, "Moi ban nhap tuoi");
return;
}
else{
a.setTuoi(tfTuoi.getText());
}
Infor.add(a);
model.addElement(a.getTen());
List.setModel(model);
List.ensureIndexIsVisible(model.size() - 1);
tfMaSV.setText("");
tfTen.setText("");
tfTuoi.setText("");
}
}
private void btRemoveActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource() == btRemove){
if(List.getSelectedIndex() == -1)
JOptionPane.showMessageDialog(null, "Chua co doi tuong nao duoc chon");
else{
int check = JOptionPane.showConfirmDialog(null, "Ban co muon xoa doi tuong nay");
if(check == JOptionPane.YES_OPTION){
Infor.remove(List.getSelectedIndex());
model.removeElement(List.getSelectedValue());
tfMaSV.setText("");
tfTen.setText("");
tfTuoi.setText("");
}
}
}
}
private void btUpdateActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource() == btUpdate){
if(List.getSelectedIndex() == -1){
JOptionPane.showMessageDialog(null, "Moi ban chon doi tuong can update");
}
else{
int check = JOptionPane.showConfirmDialog(null, "Ban co muon Uadate ?");
if(check == JOptionPane.YES_OPTION){
a.setTen(tfTen.getText());
a.setMsv(tfMaSV.getText());
a.setTuoi(tfTuoi.getText());
Infor.set(List.getSelectedIndex(), a);
JOptionPane.showConfirmDialog(null, "Da update thanh cong");
}
}
}
}
private void btClearActionPerformed(java.awt.event.ActionEvent evt) {
if(evt.getSource() == btClear){
int check = JOptionPane.showConfirmDialog(null, "Ban co muon clear ?");
if(check == JOptionPane.YES_OPTION){
model.removeAllElements();
Infor.clear();
tfMaSV.setText("");
tfTen.setText("");
tfTuoi.setText("");
}
}
}
private void ListValueChanged(javax.swing.event.ListSelectionEvent evt) {
if(List.getSelectedIndex() != -1){
tfMaSV.setText(Infor.get(List.getSelectedIndex()).getMsv());
tfTuoi.setText(Infor.get(List.getSelectedIndex()).getTuoi());
tfTen.setText(List.getSelectedValue().toString());
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ThongTin_SinhVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ThongTin_SinhVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ThongTin_SinhVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ThongTin_SinhVien.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ThongTin_SinhVien().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JList List;
private javax.swing.JButton btAdd;
private javax.swing.JButton btClear;
private javax.swing.JButton btRemove;
private javax.swing.JButton btUpdate;
private javax.swing.JInternalFrame jInternalFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JList jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane1;
private javax.swing.JTextField tfMaSV;
private javax.swing.JTextField tfTen;
private javax.swing.JTextField tfTuoi;
// End of variables declaration
}
class ThongTin{
private String msv, ten, tuoi;
public void setMsv(String msv){
this.msv = msv;
}
public void setTen(String ten){
this.ten = ten;
}
public void setTuoi(String tuoi){
this.tuoi = tuoi;
}
public String getMsv(){
return msv;
}
public String getTen(){
return ten;
}
public String getTuoi(){
return tuoi;
}
}
‘’’
em không hiểu sao chỗ phương thức ListValueChange
khi em click vào từng cái trong List thì cái tfMsv với tfTuoi lại trùng với cái cuối cùng… chỉ có tên là thay đổi theo đúng ý em… anh chị giúp em với ạ…
Bài liên quan
bạn k nên dùng nguyên 1 biến ThongTin a = new ThongTin(); như là biến toàn cục và add vào arraylist, bởi khi đó biến a giữ reference tới phần tử trong arraylist nên khi bạn thay đổi giá trị các field trong biến a sẽ thay đổi field trong các phần tử trong arraylist luôn. Fix là bạn phải new 1 biến ThongTin() khác và add vào
Không nên khởi tạo đối tượng ngay khi khai báo instance variables( model, Infor). Nên đưa khởi tạo chúng trong initComponents()