Java Ошибка, нажав на кнопку, чтобы добавлять поля в JPanel

спасибо за сообщение мне. Я переписал вопрос, если были больше людей с той же проблемой. ТИТУЛ: Java ошибка, нажав на кнопку, чтобы добавлять больше полей к формуляру.

вы можете помогать мне со следующей ошибкой, пожалуйста? Would anyone help я with this ошибка, please?

Expodré мой случай (Я изучаю Java) I'll expose my вступил в брак (I'm learning java at the moment):

Такой он такой, как работает wl программа: This is how the program runs

This is how the program runs

Такой он cóml он был бы должен / хотеть, что ejecutw программа: (Нажав в +, он был бы должен добавлять, что он другую связывает полей, но у меня появляется ошибка) This is how I want the program to run

This is how I want the program to run

Debugger Console:

Listening on javadebug

User program running

User program finished

Ошибка (debug):

debug:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.awt.Container.addImpl(Container.java:1093)
    at java.awt.Container.add(Container.java:417)
    at appimp.EPanel$1.actionPerformed(EPanel.java:157)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 25 seconds)

1. MAIN PROGRAM:


package appimp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
import com.toedter.calendar.*;
import org.jdesktop.swingx.autocomplete.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author Patrycia
 * main class that is a Jframe
 */

public class Vformulario extends javax.swing.JFrame {

    /**
     * Creates new form Vformulario
     */
    // VARIABLES
    private JPanel Continente;

    public Vformulario() {
        super();                    
        configurarVentana();        // windows setup
        formul();
    }

    private void configurarVentana() {
        this.setTitle("Formulario de Imputaciones");            
        this.setSize(900, 350);                                 
        this.setResizable(true);                               
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
    }

    public void formul() {
        Continente = new JPanel();
        Continente.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(Continente);
        Continente.setLayout(new BorderLayout());;
        JTabbedPane jt = new JTabbedPane();

        jt.add("ESPAÑA", new EPanel());
        jt.add("MÉXICO", new MPanel());

        add(jt, BorderLayout.CENTER);
    }
    /**
     * 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")
    //                           
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }//                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //
        /* 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(Vformulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Vformulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Vformulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Vformulario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //

        /* Create and display the form */

        Vformulario ventana=new Vformulario();
        ventana.setVisible(true);

    }
    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

3. EPanel java class

Здесь он, где у меня появляется ошибка. Как я думаю.

package appimp;

import java.awt.*;
import java.awt.event.*;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.*;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
import com.toedter.calendar.*;
import org.jdesktop.swingx.autocomplete.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;

/**
 *
 * @author Patrycia
 */
public class EPanel extends JPanel {

    //private JComboBox comboProyecto, comboNombre, comboH;
    private JComboBox comboNombre;
    //declarar arrays de los objetos del formulario que se van a repetir
    private JComboBox[] comboProyecto, comboH;
    private JTextField[] textField;
    private JDateChooser[] diaC;

    private JLabel nombre, proyecto, descripcion, horas, dia, aniadir;
    //private JScrollPane scrollPane;
    private JPanel contenedor, sur, centro;
    private JButton Baniadir, Belim;
    private int count = 0;
    private int max_row = 20;
    private String[] LosProy = {"alejandro", "berenice", "juan", "ana", "bartolo", "diana", "cesar"};

    public EPanel() {
        contenedor = new JPanel();
        centro = new JPanel();
        sur = new JPanel();
        //definir título de contenedor
        contenedor.setBorder(new TitledBorder(new LineBorder(Color.black, 5),"ESTÁS EN ESPAÑA"));
        add(contenedor);
        contenedor.setLayout(new BoxLayout(contenedor, BoxLayout.Y_AXIS));
        Font font = new Font("Arial", Font.BOLD, 12);
        contenedor.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        //declarar un array de todos los componentes que se van a repetir
        comboProyecto = new JComboBox[20];
        textField = new JTextField[20];
        comboH = new JComboBox[20];
        diaC = new JDateChooser[20];

        //PANEL QUE CONTIENE EL NOMBRE DEL QUE IMPUTA
        contenedor.add(centro);
            centro.setLayout(new FlowLayout());
            nombre = new JLabel("Selecciona tu nombre:");
            nombre.setFont(font);
            comboNombre=new JComboBox();
                comboNombre.addItem("Javier");
                comboNombre.addItem("Jesús");
                comboNombre.addItem("Patricia");
                comboNombre.addItem("Kevin");

            centro.add(nombre);
            centro.add(comboNombre);

        //PANEL QUE CONTIENE EL FORMULARIO DONDE SE IMPUTA
        contenedor.add(sur);
            sur.setLayout(new GridLayout(2,7,5,10));
            sur.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            proyecto = new JLabel("Nombre del Proyecto:");
            proyecto.setFont(font);
            descripcion = new JLabel("Breve descripción de la tarea:");
            descripcion.setFont(font);
            horas = new JLabel("Horas empleadas:");
            horas.setFont(font);
            dia = new JLabel("Día de la semana:");
            dia.setFont(font);
            aniadir = new JLabel("Añade más filas:");
            aniadir.setFont(font);  

            Baniadir = new JButton("+");
            Baniadir.setPreferredSize(new Dimension(10, 10));
            Belim = new JButton("-");
            Belim.setPreferredSize(new Dimension(10,10));

            comboProyecto[count] = new JComboBox(LosProy);
            comboProyecto[count].setModel(new javax.swing.DefaultComboBoxModel());
                comboProyecto[count].setEditable(true);
                AutoCompleteDecorator.decorate(this.comboProyecto[count]);
            textField[count] = new JTextField();
            comboH[count] = new JComboBox();
                double Hmax = 16;
                double h =0.5;
                comboH[count]=new JComboBox();
                    for (int i = 1; i < Hmax; i++) {
                        comboH[count].addItem(h);
                        h=h+0.5;
                    }
            diaC[count] = new JDateChooser();
            //cambpo de fecha con máscara
                diaC[count] = new JDateChooser("dd/MM/yyyy", "##/##/####", '_');

            sur.add(proyecto);
            sur.add(descripcion);
            sur.add(horas);
            sur.add(dia);
            sur.add(aniadir);
            sur.add(Baniadir);
            sur.add(Belim);
            sur.add(comboProyecto[count]);
            sur.add(textField[count]);
            sur.add(comboH[count]);
            sur.add(diaC[count]);

    //add the listener to the jbutton to handle the "pressed" event
    Baniadir.addActionListener(new ActionListener () {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if(count == max_row-1){
              JOptionPane.showMessageDialog(null, "Maximum of 20 rows can be added","Failed!!",JOptionPane.ERROR_MESSAGE);
              return;
            }
            count++;
            sur.add(comboProyecto[count]);
            sur.add(textField[count]);
            sur.add(comboH[count]);
            sur.add(diaC[count]);
            sur.revalidate();
            sur.repaint();
        }
    });

    Belim.addActionListener(new ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if(count > -1){ // Deleting one row at a time
            sur.remove(comboProyecto[count]);
            sur.remove(textField[count]);
            sur.remove(comboH[count]);
            sur.remove(diaC[count]);
            count--;
            sur.revalidate();
            sur.repaint();
            }
        }
    });

    }
}
2
задан 25.12.2016, 22:54
0 ответов

То, за чем оно последует, состоит в том, что ты не инициализируешь договоренность полностью:

private int count = 0; // el indice
private JComboBox[] comboProyecto, comboH; // declaras el arreglo

comboProyecto = new JComboBox[20]; // creas el arreglo con 20 datos

comboProyecto[count] = new JComboBox(LosProy); // comboProyecto[0], ¿que pasa con los otros 19 elementos? -> no están inicializados(comboProyecto[1] = null)
comboProyecto[count].setModel(new javax.swing.DefaultComboBoxModel());
comboProyecto[count].setEditable(true);

public void actionPerformed(java.awt.event.ActionEvent evt) {
        if (count == max_row - 1) {
            JOptionPane.showMessageDialog(null, "Maximum of 20 rows can be added", "Failed!!", JOptionPane.ERROR_MESSAGE);
            return;
        }
        count++; // count = 1
        sur.add(comboProyecto[count]); // comboProyecto[1] -> nunca fue inicializado = null -> entonces JVM: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        sur.add(textField[count]);
        sur.add(comboH[count]);
        sur.add(diaC[count]);
        sur.revalidate();
        sur.repaint();
}

Решение очень простое:

public EPanel() {
// tus otras declaraciones
private int count = 0; // el indice
private JComboBox[] comboProyecto, comboH; // declaras el arreglo
comboProyecto = new JComboBox[20]; // creas el arreglo con 20 datos
// antes del listener del botón 
for (int i = 0; i &lt 20; i++)
  comboProyecto[i] = new JComboBox();
  // codigo extra
}
3
ответ дан 03.12.2019, 17:59
  • 1
    muchí пропасти спасибо за помощь!!! Ты был очень любезным и решил мне ошибку. Она была слепой. Спасибо, всерьез. Приветствие. –  31.12.2016, 11:41