Редактировать графический интерфейс JDialog не открывается при нажатии кнопки на основном графическом интерфейсе, даже если шаги выполняются правильно - PullRequest
1 голос
/ 06 октября 2019

Я новичок в Java-коде и недавно столкнулся с проблемой, касающейся моего редактируемого графического интерфейса JDialog. Я делаю назначение, которое собирает информацию на DVD и добавляет ее в JList основного графического интерфейса. Пока все работает, единственной проблемой является графический интерфейс редактирования. Пользователь должен выбрать объект в JList основного графического интерфейса и нажать кнопку редактирования, чтобы открыть JDialog для пользователя, чтобы затем отредактировать информацию, находящуюся в Объекте. Это не работает и постоянно говорит, что пользователь должен выбрать объект в JList для редактирования, даже если пользователь выбрал или не выбрал объект.

Iпредоставили весь мой код ниже:

ОСНОВНОЙ GUI:

public class DVDGUI extends javax.swing.JFrame {

    private DVDCollection dvdcollection = new DVDCollection();
    public DVDGUI() {
        initComponents();
        loadData();
    }

    private void loadData()
    {
        try
        {
            ObjectInputStream infile = new ObjectInputStream(new FileInputStream("heatherdunne.txt"));
            dvdcollection = (DVDCollection)infile.readObject();
            infile.close();
            updateDVDList();
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(this,"Error found - " + e);
        }
    }

    public void saveData()
    {
        try
        {            
            ObjectOutputStream outfile = new ObjectOutputStream(new FileOutputStream("heatherdunne.txt"));
            outfile.writeObject(dvdcollection);
            outfile.close();
            System.exit(0);
        }
        catch (Exception e)
        {
               JOptionPane.showMessageDialog(this,"Error writing file - " + e);        
        }
    }

    @SuppressWarnings("unchecked")
    private void lstDVDsValueChanged(javax.swing.event.ListSelectionEvent evt) {                                     
        if (lstDVDs.getSelectedIndex() >= 0)
            txtDetails.setText(((DVD)lstDVDs.getSelectedValue()).getDetails());
        else
            txtDetails.setText(" ");                            

        int selectedIndex = lstDVDs.getSelectedIndex();
        ListModel lModel= lstDVDs.getModel();
        DVD item = (DVD)lModel.getElementAt(selectedIndex);
        System.out.println("Title= "+ item.getTitle());  
        boolean favourite = false;
        favourite = true;
        favourite = item.favourite;
        if (item.favourite == true)
        uebbtnFav.setSelected(true);
        else
        uebbtnFav.setSelected(false);
    }
    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {                                        
        if (lstDVDs.getSelectedIndex() >= 0)
        {
          JOptionPane.showMessageDialog(this,"You need to select a DVD to be edited");
        }
        else
        {
            DVD dvvvd = (DVD)lstDVDs.getSelectedValue();
            EditDVD idk = new EditDVD(this, dvvvd);  
        }
    }
    private void loadDVDsfromfile(){
        DVD dvd = null;
        DVD dvd2 = null;        
        DVD dvd3 = null;        
        try
        {    
            FileInputStream file = new FileInputStream("C:\\Users\\User\\Desktop\\code\\Assign2\\heatherdunne.txt"); 
            ObjectInputStream in = new ObjectInputStream(file); 

            dvd = (DVD)in.readObject(); 
            dvd2 = (DVD)in.readObject();             
            dvd3 = (DVD)in.readObject();             

            dvdcollection.addDVD(dvd);
            dvdcollection.addDVD(dvd2);
            dvdcollection.addDVD(dvd3);

            in.close(); 
            file.close(); 

            System.out.println("Object has been deserialized "); 
            System.out.println(dvd);
            System.out.println(dvd2);
            System.out.println(dvd3);      

        } 

        catch(IOException ex) 
        { 
            System.out.println("IOException is caught"); 
        } 

        catch(ClassNotFoundException ex) 
        { 
            System.out.println("ClassNotFoundException is caught"); 
        }                 
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        loadDVDsfromfile();  
        DefaultListModel lstmdl = new DefaultListModel();
        lstmdl.addElement(dvdcollection.getDVDs().get(0)); 
        lstDVDs.setModel(lstmdl);
    }                                 
    private void crtFileActionPerformed(java.awt.event.ActionEvent evt) {                                        
          DVD dvd = new DVD("Avengers: Endgame", 2019, Boolean.TRUE);
          DVD dvd2 = new DVD("Shrek 2", 2004, Boolean.TRUE);
          DVD dvd3 = new DVD("IT", 2017, Boolean.TRUE);

        try
        {    
            FileOutputStream file = new FileOutputStream("C:\\Users\\User\\Desktop\\code\\Assign2\\heatherdunne.txt"); 
            ObjectOutputStream out = new ObjectOutputStream(file); 

            out.writeObject(dvd); 
            out.writeObject(dvd2); 
            out.writeObject(dvd3);



            out.close(); 
            file.close(); 

            System.out.println("Object has been serialized"); 
        } 

        catch(IOException ex) 
        { 
            System.out.println("IOException is caught"); 
        }    

    }                                       
    public void updateDVDList()
    {       
        if (rbtTitle.isSelected())
            sortByTitle();
        else
                sortByID();
        lstDVDs.setListData(dvdcollection.getDVDs().toArray());
    }                                

РЕДАКТИРОВАТЬ DVD GUI

private DVD selectedDVD;
    public EditDVD(DVDGUI inParent, DVD inDVD)
    {
        super(inParent, true);          
        initComponents();
        parent = inParent;
        Title.setText(selectedDVD.getTitle());        
        Year.setText(selectedDVD.getYear() + "");
        setVisible(true);        
    }

@SuppressWarnings("unchecked")
private void EditActionPerformed(java.awt.event.ActionEvent evt) {                                     
    String title = Title.getText();
    String year = Year.getText();

    String msgTitle = DVD.checkTitle(title);
    String msgYear = DVD.checkYear(year);        

    if (msgTitle.length()>0)
        JOptionPane.showMessageDialog(this, msgTitle);
    else
    if (msgYear.length()>0)
        JOptionPane.showMessageDialog(this, msgYear);
    else    
    {
        //validation was ok
            selectedDVD.setTitle(title);
            selectedDVD.setYear(Integer.parseInt(year));
            parent.updateDVDList();
            JOptionPane.showMessageDialog(this, "Update sucessful");
            dispose();
    }
}    

DVD CLASS:

public class DVD implements Serializable
{
    private String id;     
    private String title;                                                                     
    private int year;                                                          
    boolean favourite;  
    private int nextID=1;

    public DVD(String inID, String inTitle, int inYear, boolean inFavourite)
    {
        id = inID;
        title = inTitle;
        year = inYear;
        favourite = inFavourite;
    }
    public DVD (String inTitle, int inYear, boolean inFavourite)
    {  
        id = "0";
        nextID++; 
        title = inTitle;
        year = inYear;
        favourite = inFavourite;        
    }


    public String toString()
    {
        return title;
    } 

    public String getID()
    {
        return id;
    }

    public void setID(String inID)
    {
        id = inID;
    }

    public String getDetails()
    {
        return "id(" + id + ") " + title + " <" + year + "> ";
    }

    public String getTitle()
    {
        return title;
    }

    public void setTitle(String inTitle)
    {
        title = inTitle;
    }

    public String getYear()
    {
        if (year==0)
            return " ";
        else
            return year + "";
    } 

    public void setYear(int inYear)
    {
        year = inYear;
    }

    public boolean isFavourite()
    {
        return favourite;
    }    

    public void setFavourite(boolean inFavourite)
    {
        favourite = inFavourite;
    }  

    public static String checkTitle(String inTitle)
    {
        if (inTitle.trim().length()>0)
            return "";
        else
            return "Title must have at least 1 non-blank character";
    } 

    public static String checkYear(String inYear)
    {
        Calendar now = Calendar.getInstance();  
        int currYear = now.get(Calendar.YEAR);         
        try
        {
            int year = Integer.parseInt(inYear);
            if ((year >= 1997)&&(year <= currYear))
                return ""; 
            else
                return "Year must be between 1997 and current year";
        }
        catch (Exception ex)
        {
            return "Year must be a 4 digit integer";
        }
    }

    public static String checkID(String inID)
    {
        if (inID.trim().length()>0)
            return "";
        else
            return "ID must have at least 1 non-blank character";
    } 

    public static boolean checkFavourite(boolean inFav)
    {
        boolean Favs = false;
        int total = 0;
        if ( !Favs ) 
        {
        total = total + 1;
        }
        return false;
    }
    public int compareTo(DVD d2)
    {
//        if (ID<c2.getID())
//      return -1;
//  else 
//         if (ID>c2.getID())
//          return 1;
//       else return 0;        
        return id.compareTo(d2.getID());
    }        
}

Класс DVDCollection:

public class DVDCollection implements Serializable
{
    private ArrayList<DVD> dvds = new ArrayList<DVD>();
    private int nextID=1;
    public boolean addDVD(DVD inDVD)
    {   
        return 
        dvds.add(inDVD);
    }

    public DVDCollection()
    {
    }

    public ArrayList<DVD> getDVDs()
    {
        return dvds;
    }

    public int getNumDVDs()
    {
        return dvds.size();
    }

    public boolean deleteDVD(DVD inDVD)
    {
       return dvds.remove(inDVD);
    }

    public int CountFavourites()
    {
        int total = 0;

        if (DVD.checkFavourite(true))
        {
            boolean fav = true;   
            int val = fav? 1 : 0;
            total = 1 + total;
        }
        else
        {
            boolean fav = false;   
            int val = fav? 1 : 0;
        }


        return total;
    }
}

Я выполнил следующие действиядля редактирования графического интерфейса, предоставленного в моем классе, но эта проблема все еще появляется. Еще одна вещь, которую я попытался, но вынул, - это преобразование всех переменных в String, а также отключил функцию редактирования любимого jcheckbox на случай, если это было проблемой. Я сделал больше нагрузок, но все это привело к сбою и, тем не менее, возникла та же проблема.

Вся помощь будет очень признательна

Обновление: Проблема решена

...