简体   繁体   中英

Swing - Exception when trying to delete an item from a JList

I've looked arround how to fix this problem, but it only occurs when I'm working with several objects, I've tried with an object and two String variables for instance and I don't get any exception, so idk what's really wrong and why it says the value is null when trying to remove an element from a Jlist. The main code is

package presentacion;

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import dominio.Appointment;
import dominio.Patient;
import dominio.Specialist;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;


public class Test {

    private JFrame a;
    private JTabbedPane tabbedPane;
    private JMenuBar menuBar;
    private JLabel testlabel;
    private Appointment citaSara = new Appointment("09:21");
    private Appointment citaPaula = new Appointment("10:32");
    private Appointment citaRaul = new Appointment("13:12");
    private Patient raul = new Patient ("Raul", "Garcia Jimenez", "926781091", "13120", "Porzuna", "Ciudad Real", "Almendros", "3", "630956066", "raul@gmail.com", "18", "Hombre", citaRaul);
    private Patient paula = new Patient ("Paula", "Baos Ramiza", "900124392", "13003", "Robledo", "Ciudad Real", "La plaza", "20", "633727281", "paula@hotmail.com", "23", "Mujer", citaPaula);
    private Patient sara = new Patient ("Sara", "Jimenez Dorado", "911232292", "13009", "Ciudad Real", "Ciudad Real", "Ceunca", "4", "611627481", "sara@gmail.com", "32", "Mujer", citaSara);


    public Test() {
        initialize();
        a.setVisible(true);
    }

    public static void main(String[] args) {

        try {
            // Set System L&F
        UIManager.setLookAndFeel(
            UIManager.getSystemLookAndFeelClassName());
    } 
    catch (UnsupportedLookAndFeelException e) {
       // handle exception
    }
    catch (ClassNotFoundException e) {
       // handle exception
    }
    catch (InstantiationException e) {
       // handle exception
    }
    catch (IllegalAccessException e) {
       // handle exception
    }

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test window = new Test();
                    window.a.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initialize() {
        a = new JFrame();
        a.setTitle("Administraci\u00F3n Hospital");
        a.setBounds(100, 100, 1195, 710);
        a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        a.getContentPane().add(panel, BorderLayout.CENTER);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{194, 0, 50, 0};
        gbl_panel.rowHeights = new int[]{1, 0, 0};
        gbl_panel.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
        gbl_panel.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
        panel.setLayout(gbl_panel);

        DefaultListModel<String> modelPacientes = new DefaultListModel<>();
        JList <String> list = new JList<>( modelPacientes );
        GridBagConstraints gbc_list = new GridBagConstraints();
        gbc_list.insets = new Insets(0, 0, 5, 5);
        gbc_list.fill = GridBagConstraints.BOTH;
        gbc_list.gridx = 0;
        gbc_list.gridy = 0;
        panel.add(list, gbc_list);
        modelPacientes.addElement(raul.getName());
        modelPacientes.addElement(paula.getName());
        modelPacientes.addElement(sara.getName());
        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent arg0) {
                setPacientesInfo(list.getSelectedValue());
            }
        });


        JButton btnDelete = new JButton("DELETE");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultListModel model = (DefaultListModel) list.getModel();

                int selectedIndex = list.getSelectedIndex();

                int borrar = JOptionPane.showConfirmDialog(null, "Si borra a este paciente no se podrá recuperar, ¿continuar?", "Borrar",
                        JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

                if (borrar == JOptionPane.YES_OPTION && list.getSelectedIndex() != -1) {

                    model.remove(selectedIndex);
                }
            }
        });
        GridBagConstraints gbc_btnDelete = new GridBagConstraints();
        gbc_btnDelete.insets = new Insets(0, 0, 5, 5);
        gbc_btnDelete.gridx = 1;
        gbc_btnDelete.gridy = 0;
        panel.add(btnDelete, gbc_btnDelete);

        testlabel = new JLabel("");
        GridBagConstraints gbc_testlabel = new GridBagConstraints();
        gbc_testlabel.insets = new Insets(0, 0, 5, 0);
        gbc_testlabel.gridx = 2;
        gbc_testlabel.gridy = 0;
        panel.add(testlabel, gbc_testlabel);


    }

    private void setPacientesInfo(String value){
        testlabel.setVisible(true);

        if (value.indexOf("Sara") != -1){
            testlabel.setText(sara.getName());

        } else if (value.indexOf("Paula") != -1){
            testlabel.setText(paula.getName());

        } else if (value.indexOf("Raul") != -1){
            testlabel.setText(raul.getName());

        }

    }

}

The code for the Patient and apointment classes are:

package dominio;

public class Appointment {
    private String time;
    public Appointment(String time) {
        this.time = time;
    }
}

and

package dominio;

public class Patient extends Person{

    private String age;
    private String genre;
    private String mobilePhone;
    private String email;
    private Appointment appointment;

    public Patient(String name, String surname, String phoneNumber, String zipCode, String town, String province,
            String street, String houseNumber, String mobilePhone, String email, String age, String genre, Appointment appointment) {
        super(name, surname, phoneNumber, zipCode, town, province, street, houseNumber);

        this.age = age;
        this.genre = genre;
        this.mobilePhone = mobilePhone;
        this.email = email;
        this.appointment = appointment;
    }

}

with parent class

package dominio;

public class Person {

    private String name;
    private String surname;
    private String phoneNumber;
    private String zipCode;
    private String town;
    private String province;
    private String street;
    private String houseNumber;

    public Person(String name, String surname, String phoneNumber, String zipCode, String town, String province, String street, String houseNumber){
        this.name = name;
        this.surname = surname;
        this.phoneNumber = phoneNumber;
        this.zipCode = zipCode;
        this.town = town;
        this.province = province;
        this.street = street;
        this.houseNumber = houseNumber;
    }

    public String getName() {
        return name;
    }
}

Why am I getting that exception? How could i fix it please? it works perfectly if not working with objects.

EDIT. ADDED THE EXCEPTION CODE WHICH I FORGOT.

And the exception code:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at presentacion.Test.setPacientesInfo(Test.java:162)
    at presentacion.Test.access$1(Test.java:159)
    at presentacion.Test$2.valueChanged(Test.java:122)
    at javax.swing.JList.fireSelectionValueChanged(Unknown Source)
    at javax.swing.JList$ListSelectionHandler.valueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.fireValueChanged(Unknown Source)
    at javax.swing.DefaultListSelectionModel.removeIndexInterval(Unknown Source)
    at javax.swing.plaf.basic.BasicListUI$Handler.intervalRemoved(Unknown Source)
    at javax.swing.AbstractListModel.fireIntervalRemoved(Unknown Source)
    at javax.swing.DefaultListModel.remove(Unknown Source)
    at presentacion.Test$3.actionPerformed(Test.java:139)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

Thanks

The really simple way to fix your problem would be to add a null check in setPacientesInfo(...) . For example

private void setPacientesInfo(String value){
    testlabel.setVisible(true);
    if(value != null) {
        if (value.indexOf("Sara") != -1){
            testlabel.setText(sara.getName());

        } else if (value.indexOf("Paula") != -1){
            testlabel.setText(paula.getName());

        } else if (value.indexOf("Raul") != -1){
            testlabel.setText(raul.getName());

        }
    } else
        testlabel.setText("");
}

Explanation
The reason you need to do this is because when you remove the value from the JList a value in the JList model has changed and you are no longer selecting anything. This means the value for value will be null as you are selecting nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM