首页 > 解决方案 > Arraylist 和 Jframe

问题描述

arrays在这个项目中遇到问题。我必须保存各自班级的所有学生和教师,特别是在这种情况下,我需要能够添加教师并将其从各自班级中删除,同时显示每个班级的信息。AulasColegioArrayList我存储所有课程的地方,Profesores 和老师一样。问题是,ArrayList在主类中添加类,我认为它不会在JFrame. 我所有的问题都与在哪里添加老师和班级有关,以及如何让他们JFrame也加入进来,反之亦然。我真的很感激一些解决方案。

import javax.swing.JOptionPane;

/**
 *
 * 
 */
public class ventDirector extends javax.swing.JFrame {


    /**
     * Creates new form ventDirector
     */

    public ventDirector() {
        initComponents();
        this.setLocationRelativeTo(null);

    }

    /**
     * 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();
        txtClase = new javax.swing.JTextField();
        bttInfoClase = new javax.swing.JButton();
        bttAlta = new javax.swing.JButton();
        bttBaja = new javax.swing.JButton();
        txtProfesor = new javax.swing.JTextField();
        txtClaseProfesor = new javax.swing.JTextField();
        bttAtras = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Información clase");

        txtClase.setText("Introduzca nombre de la clase");

        bttInfoClase.setText("GO");
        bttInfoClase.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bttInfoClaseMouseClicked(evt);
            }
        });
        bttInfoClase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttInfoClaseActionPerformed(evt);
            }
        });

        bttAlta.setText("Alta profesor");
        bttAlta.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bttAltaMouseClicked(evt);
            }
        });
        bttAlta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttAltaActionPerformed(evt);
            }
        });

        bttBaja.setText("Baja profesor");
        bttBaja.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bttBajaMouseClicked(evt);
            }
        });

        txtProfesor.setText("Nombre profesor");
        txtProfesor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProfesorActionPerformed(evt);
            }
        });

        txtClaseProfesor.setText("Nombre clase");

        bttAtras.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sudoku/back-arrow_icon-icons.com_72866 (1).png"))); // NOI18N
        bttAtras.setContentAreaFilled(false);
        bttAtras.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                bttAtrasMouseClicked(evt);
            }
        });
        bttAtras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bttAtrasActionPerformed(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()
                        .addGap(92, 92, 92)
                        .addComponent(bttAlta)
                        .addGap(53, 53, 53)
                        .addComponent(bttBaja))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtClase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(bttInfoClase))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtClaseProfesor, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtProfesor, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(bttAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(46, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(74, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtClase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bttInfoClase))
                .addGap(50, 50, 50)
                .addComponent(txtProfesor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtClaseProfesor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bttBaja)
                    .addComponent(bttAlta))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bttAtras, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(17, 17, 17))
        );

        pack();
    }// </editor-fold>                        

    private void bttInfoClaseActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
    }                                            

    private void bttInfoClaseMouseClicked(java.awt.event.MouseEvent evt) {                                          
        // TODO add your handling code here:

        boolean flag =false;

        for(int i =0; i<aulasColegio.size();i++){
            if (aulasColegio.get(i).getNombreClase() == txtClase.getText()){
            JOptionPane.showMessageDialog(this, aulasColegio.get(i).getNombreClase()+ "\n" +
                    aulasColegio.get(i).getProfesores()+ "\n" + aulasColegio.get(i).getAlumnos() + aulasColegio.get(i).getNumAlumnos());
            flag =true;
            }
        }
        if (flag = false) JOptionPane.showMessageDialog(this,"No existe la clase");

    }                                         

    private void txtProfesorActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void bttAltaActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:

    }                                       

    private void bttAltaMouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        boolean flag =false; 

        Profesor profe = new Profesor(txtProfesor.getText());
        for(int i =0; i<aulasColegio.size();i++){
            if (aulasColegio.get(i).getNombreClase() == txtClase.getText()){
                aulasColegio.get(i).anadeProfesor(profe);
                JOptionPane.showMessageDialog(this, "Añadido con éxito");
                flag =true;
            }
            else JOptionPane.showMessageDialog(this, "No es esta clase");
        }
        if (flag = false) JOptionPane.showMessageDialog(this, "Ese profesor no se encuentra en la clase");
    }                                    

    private void bttBajaMouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:

        boolean flag =false;

        for(int i =0; i<aulasColegio.size();i++){
            if (aulasColegio.get(i).getNombreClase() == txtClase.getText()){
                for(int j = 0; j<profesores.size(); j++){
                    if (profesores.get(j).getProfesor() == txtProfesor.getText()){
                        aulasColegio.get(i).eliminaProfesor(profesores.get(j));
                        JOptionPane.showMessageDialog(this, "Eliminado con éxito");
                        flag= true;
                    }
                }   
            }
        }
        if (flag = false) JOptionPane.showMessageDialog(this, "Ese profesor no se encuentra en la clase"); 

    }                                    

    private void bttAtrasActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void bttAtrasMouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:

        login_1 L = new login_1();
        L.setVisible(true);
        dispose();
    }                                     

    /**
     * @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(ventDirector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ventDirector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ventDirector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ventDirector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ventDirector().setVisible(true);
            }
        });


    }
    private ArrayList<Clase> aulasColegio  = new ArrayList<Clase>();
    private ArrayList<Profesor> profesores  = new ArrayList<Profesor>();

    // Variables declaration - do not modify                     
    private javax.swing.JButton bttAlta;
    private javax.swing.JButton bttAtras;
    private javax.swing.JButton bttBaja;
    private javax.swing.JButton bttInfoClase;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField txtClase;
    private javax.swing.JTextField txtClaseProfesor;
    private javax.swing.JTextField txtProfesor;
    // End of variables declaration                   
}

主课还没有结束。

import java.util.ArrayList;

/**
 *
 * @author
 */
public class SudokuNino {

  private String nombreColegio;
  private String nombreDirector;
  private ArrayList<Clase> aulasColegio = new ArrayList<Clase>();
  //private Partida[] partidas;

  public void SudokuNiño(){};

  /*EXCEPCION  */ 
  public void SudokuNiño(String c, String d){
     this.nombreColegio= c;
     this.nombreDirector= d;
 };

    public static void main(String[] args) {
        // TODO code application logic here

        SudokuNino main = new SudokuNino();
        Clase clase1 = new Clase("girasoles");
        main.aulasColegio.add(clase1);

}
}

标签: javaarraylistnetbeans

解决方案


你永远不会在你的列表中添加任何东西aulasColegio。原因很简单。当你从类中启动 main 时,ventDirector它会像你想要的那样打开 GUI。在每个按钮事件上,您都有以下 for 循环:

for(int i = 0; i<aulasColegio.size();i++){
    ...
}

如果 ArrayList 为空,则此 for 循环将永远不会运行!它总是空的。教授也一样。我没有看到您的单个profesores.add()aulasColegio.add()整个代码。所以当然什么都不会发生。代码按预期运行。

在类的情况下SudokuNino。它创建了一些对象并完成,但没有其他任何事情发生。不知道为什么要添加这段代码。

一些提示:

  1. 使用英语。不要在编码中使用其他语言,这也将有助于其他人理解您的代码。我不知道ñ会如何影响代码,但我可以肯定地说我永远不会用德语(我的母语)编程
  2. 使用 System.out.println() 调试您的代码或 IDE 中的调试器,这对您理解代码有很大帮助。你会看到你的数组总是空的。您必须先以某种方式添加一些元素,然后才能迭代它。
  3. 而不是==在字符串比较(或对象比较)中,您必须使用equals

    String test=new String("hello");
    String test2=new String("hello");
    
    System.out.println(test == test2);
    System.out.println(test.equals(test2));
    

    输出:

    false
    true
    

推荐阅读