2014-09-20 4 views
1

나는 내 데이터베이스의 데이터로 채우는 JTable을 만들었습니다. 텍스트 필드에서 데이터를 가져 와서 테이블과 데이터베이스에 추가합니다. 것은 내가 삭제 버튼을 가지고 있고, (defaultTableModel을 사용하여) 테이블 자체에서 선택된 행을 삭제할 수 있지만 실제 데이터베이스에서 해당 데이터를 삭제하지는 않습니다. 프로그램을 다시 실행하면 삭제 된 행이 JTable에 다시 앉아 있습니다.JTable 및 데이터베이스에서 데이터 삭제

이것은 지저분 할 수 있지만 잘하면 누군가 내가 누락 된 걸 알아낼 수 있습니다. 도움을 받으실 수는 있지만 좋지는 않습니다. 시간이 부족해서 시스템의 일부를 정밀 검사 할 수 없습니다. (추가 버튼이 필요하다고 생각하지는 않지만 추가 버튼이 작동한다고 생각합니다)

코드, 무슨 비트 것입니다 유용하지 않을 것이다, 나는 가장 유용하다고 추가 및 삭제 버튼, 'updateReview'메서드 위에 하단에있는 것 같아요.

public class MovieReviewSystem extends JFrame { 

/** 
* TODO: This method should construct a new MovieReviewSystem window and populate it using the MovieReviewDSC. 
* Before displaying anything, this class should ask the user whether to load *everything* or just 
* the 'useful' reviews. 
*/ 

// Main method to run the class 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new MovieReviewSystem().setVisible(true); 
      } 

     }); 
    } 


// Load data method 
private Object[][] loadData() 
{ 
    List<MovieReview> movieData; 

    try { 
     movieData = MovieReviewDSC.list(); 
    } catch (SQLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     movieData = new ArrayList<>(); 
    } 

    Object[][] data = new Object[movieData.size()][]; 

    for (int i = 0; i < movieData.size(); ++i) 
    { 
     MovieReview temp = movieData.get(i); 

     data[i] = new Object[] 
       { 
       temp.getId(), 
       temp.getUser(), 
       temp.getMovie(), 
       temp.isFeatured(), 
       temp.getRating(), 
       temp.getHelpful(), 
       temp.getUnhelpful(), 
       temp.getComments() 
       }; 
    } 
    return data; 
} 

private Object[][] data = loadData(); 
private String[] columnNames = {"ID", "User", "Movie", "Featured?", "Rating", "Helpful", "Unhelpful"}; 

private MovieReviewTableModel tableModel = new MovieReviewTableModel(data, columnNames); 

JTable table = new JTable(tableModel); 

public MovieReviewSystem() { 
    setTitle("Movie Review System"); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //setMinimumSize(getSize()); 
    setSize(540,600); 

    createTable(); 
} 

    private void createTable() 
    { 
     final TableRowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel); 


     //Overall Panel 
     JPanel bigPanel = new JPanel(new BorderLayout()); 
     add(bigPanel); 

     // overall search Panel 
     JPanel searchPanel = new JPanel(new BorderLayout()); 
     searchPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); 
     bigPanel.add(searchPanel, BorderLayout.NORTH); 

     // search field panel 
     JPanel searchField = new JPanel(); 
     searchPanel.add(searchField, BorderLayout.NORTH); 

     // Radio buttons panel 
     JPanel searchRadioButtons = new JPanel(); 
     searchPanel.add(searchRadioButtons, BorderLayout.SOUTH); 

     //Search 
     JLabel searchLB = new JLabel("Search with keywords: "); 
     searchField.add(searchLB); 

     final JTextField searchTF = new JTextField(20); // eclipse says this needs to be final, don't change 
     searchField.add(searchTF); 

     JButton searchBT = new JButton("Search"); 
     searchField.add(searchBT); 

     JRadioButton allRB = new JRadioButton("All"); 
     searchRadioButtons.add(allRB); 
     allRB.setSelected(true); // 'All' selected by default 

     JRadioButton usersRB = new JRadioButton("Users"); 
     searchRadioButtons.add(usersRB); 

     JRadioButton moviesRB = new JRadioButton("Movies"); 
     searchRadioButtons.add(moviesRB); 

     // Search Button 
     searchBT.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       String searchString = searchTF.getText(); 
       rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 2)); //Apply search on movie 
      } 
     }); 

     // this also allows for pressing enter to search 
     searchTF.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       String searchString = searchTF.getText(); 
       rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 2)); //Apply search on movie 

       /*if(moviesRB.isSelected()) 
       { 
        rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 2)); //Apply search on movie 
       } 
       else if(usersRB.isSelected()) 
       { 
        rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 1)); //Apply search on movie 
       } 
       else 
       { 
        rowSorter.setRowFilter(RowFilter.regexFilter(searchString, 1, 2)); //Apply search on movie 
       }*/ 
      } 
     }); 


     // END search field and buttons 


     // Three buttons 

     JPanel threeButtonPanel = new JPanel(); 
     bigPanel.add(threeButtonPanel); 

     // Show only Featured 
     JButton onlyFeatured = new JButton("Only show Featured"); 
     threeButtonPanel.add(onlyFeatured); 


     // Show only Helpful 
     JButton onlyHelpful = new JButton("Only show Helpful"); 
     threeButtonPanel.add(onlyHelpful); 


     // Sort by Movie then Helpfulness Button 
     JButton sortByMovieThenHelpfulBT = new JButton("Sort by Movie then Helpfulness"); 
     threeButtonPanel.add(sortByMovieThenHelpfulBT); 

     sortByMovieThenHelpfulBT.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       RowSorter.SortKey sortMovie = new RowSorter.SortKey(2, SortOrder.ASCENDING); 
       RowSorter.SortKey sortHelp = new RowSorter.SortKey(5, SortOrder.DESCENDING); 

       ArrayList<RowSorter.SortKey> sortKeyList = new ArrayList<RowSorter.SortKey>(); 
       sortKeyList.add(sortMovie); 
       sortKeyList.add(sortHelp); 

       rowSorter.setSortKeys(sortKeyList); 
      } 
     }); 


     //END Three Buttons 


     // *** TABLE *** 
     setLayout(new FlowLayout()); 
     JScrollPane scrollPane = new JScrollPane(table); // table needs to be enclosed in a scrollpane 
     table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // select one row at a time 
     table.setPreferredScrollableViewportSize(new Dimension(500,300)); // size 
     //table.setFillsViewportHeight(true); 
     add(scrollPane); 

     setVisible(true); 

     // Row Sorter 
     table.setRowSorter(rowSorter); 

     // *** END Table *** 


     //Reset button -- NOT NECESSARY 
     JButton resetBT = new JButton("Reset sorting"); 
     add(resetBT); 
     resetBT.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       rowSorter.setSortKeys(null); 

      } 
     }); 

     // add button ********************* 
     JButton addBT = new JButton("Add"); 
     add(addBT); 
     addBT.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       JFrame idFrame = new JFrame(); 
       String id = JOptionPane.showInputDialog(idFrame, "Enter an ID"); 


       ReviewEditor editor = new ReviewEditor(MovieReviewSystem.this, id); 
       editor.pack(); 
       editor.setVisible(true); 

      } 
     }); 

     // delete button **************** 
     JButton deleteBT = new JButton("Delete"); 
     add(deleteBT, BorderLayout.SOUTH); 

     deleteBT.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       int row = table.getSelectedRow(); 

       if(row != -1) 
       { 
        int result = JOptionPane.showConfirmDialog(MovieReviewSystem.this, "Are you sure?"); 
        if (result == JOptionPane.OK_OPTION) 
        { 
         tableModel.removeRow(row); 

         MovieReview movieReviewDelete = new MovieReview(); 
         movieReviewDelete.setId((String) table.getValueAt(row, 0)); 
         movieReviewDelete.setUser((String) table.getValueAt(row, 1)); 
         movieReviewDelete.setMovie((String) table.getValueAt(row, 2)); 
         movieReviewDelete.setFeatured((boolean) table.getValueAt(row, 3)); 
         movieReviewDelete.setRating((int) table.getValueAt(row, 4)); 
         movieReviewDelete.setHelpful((int) table.getValueAt(row, 5)); 
         movieReviewDelete.setUnhelpful((int) table.getValueAt(row, 6)); 
         movieReviewDelete.setComments((String) table.getValueAt(row, 7)); 



         try { 
          MovieReviewDSC.delete(movieReviewDelete); 
         } catch (Exception e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
        } 
       } 

      } 
     }); 


    } 


/** 
* TODO This method should attempt to update a MovieReview record in the database. 
* @param isUpdate A boolean to indicate if the record should be updated or created new. If true; the update method should be used. 
* @param review The MovieReview object to be updated or added 
* @return a boolean indicating success (true) or failure (false) 
*/ 
public boolean updateReview(boolean isUpdate, MovieReview review) { 

    if (isUpdate = false) 
    { 
    try { 
     MovieReviewDSC.add(review); 

    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 

    } 

    } 
    else 
    { 
     try { 
      MovieReviewDSC.edit(review); 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 

     } 
    } 
    return true; 

} 


} 

당신은이 클래스 인 에서 MovieReviewDSC을 방법을 추가 및 삭제를 호출 볼 수 있듯이 :

public class MovieReviewDSC { 
private static Connection connection; 
private static Statement statement; 
private static PreparedStatement preparedStatement; 

public static void connect() throws SQLException { 
    String url = "null"; //took this info out for obvious reasons 
    String user = "null"; 
    String password = "null"; 
    connection = DriverManager.getConnection(url, user, password); 
    statement = connection.createStatement(); 
} 

public static void disconnect() throws SQLException { 
    if (preparedStatement != null) preparedStatement.close(); 
    if (statement != null) statement.close(); 
    if (connection != null) connection.close(); 
} 

/** 
* TODO: This method should find a MovieReview with the given ID in the database 
* @param id The ID of the MovieReview to be found. 
* @return If it exists; a MovieReview with the given ID. Otherwise null. 
* @throws SQLException 
*/ 
public static MovieReview find(String id) throws SQLException { 

    connect(); 

    // Create query to find ID 
    String IDquery = "SELECT * FROM movie_review WHERE id = ?"; 
    preparedStatement = connection.prepareStatement(IDquery); 
    preparedStatement.setString(1, id); 
    ResultSet rs = preparedStatement.executeQuery(); 

    MovieReview movieReview = null; //null returned if ID doesn't exist 

    if (rs.next()) //if it does exist, creates new object and fills with attributes returned by query 
    { 
     movieReview = new MovieReview(); 
     movieReview.setId(rs.getString(1)); 
     movieReview.setUser(rs.getString(2)); 
     movieReview.setMovie(rs.getString(3)); 
     movieReview.setFeatured(rs.getBoolean(4)); 
     movieReview.setRating(rs.getInt(5)); 
     movieReview.setHelpful(rs.getInt(6)); 
     movieReview.setUnhelpful(rs.getInt(7)); 
     movieReview.setComments(rs.getString(8)); 
    } 

    disconnect(); 

    return movieReview; 
} 

/** 
* TODO: This method should count the total number of MovieReviews in the database 
* @return An int representing the number of MovieReviews 
* @throws SQLException 
*/ 
public static int count() throws SQLException { 

    connect(); 

    String queryCount = "SELECT COUNT(*) FROM movie_review"; 
    preparedStatement = connection.prepareStatement(queryCount); 
    ResultSet rs = preparedStatement.executeQuery(); 

    MovieReview movieReview = null; 

    int count = 0; //set to 0 by default 

    if (rs.next()) 
    { 
     count = rs.getInt(1); //Count will only return one column 
    } 

    disconnect(); 

    return count; 
} 

/** 
* TODO: This method should obtain a list of all MovieReviews from the database 
* @return A list of all stored MovieReviews 
* @throws SQLException 
*/ 
public static List<MovieReview> list() throws SQLException { 

    connect(); 

    String queryList = "SELECT * FROM movie_review"; 
    preparedStatement = connection.prepareStatement(queryList); 
    ResultSet rs = preparedStatement.executeQuery(); 

    ArrayList<MovieReview> movieReviewList = new ArrayList<MovieReview>(); 
    MovieReview movieReview = null; 

    while(rs.next()) 
    { 
     movieReview = new MovieReview(); 
     movieReview.setId(rs.getString(1)); 
     movieReview.setUser(rs.getString(2)); 
     movieReview.setMovie(rs.getString(3)); 
     movieReview.setFeatured(rs.getBoolean(4)); 
     movieReview.setRating(rs.getInt(5)); 
     movieReview.setHelpful(rs.getInt(6)); 
     movieReview.setUnhelpful(rs.getInt(7)); 
     movieReview.setComments(rs.getString(8)); 

     movieReviewList.add(movieReview); // add to arrayList 

    } 


    return movieReviewList; 
} 

/** 
* TODO: This method should try to add the given MovieReview to the database. 
* Note: The ID of this MovieReview must be unique 
* @param movieReview The MovieReview to be added 
* @throws Exception If the ID of the MovieReview already exists in the database 
*/ 
public static void add(MovieReview movieReview) throws Exception { 

    // set precondition that ID does not already exist 
    MovieReview temp = find(movieReview.getId()); // put ID in temp 
    boolean notExist = (temp == null); // temp should be null 

    if (!notExist) // If not, show error 
    { 
     String message = "The ID you are trying to add already exists."; 
     throw new Exception(message); 
    } 

    connect(); 

    String insert = "INSERT INTO movie_review VALUES(?,?,?,?,?,?,?,?)"; 
    preparedStatement = connection.prepareStatement(insert); 
    preparedStatement.setString(1, movieReview.getId()); 
    preparedStatement.setString(2, movieReview.getUser()); 
    preparedStatement.setString(3, movieReview.getMovie()); 
    preparedStatement.setBoolean(4, movieReview.isFeatured()); 
    preparedStatement.setInt(5, movieReview.getRating()); 
    preparedStatement.setInt(6, movieReview.getHelpful()); 
    preparedStatement.setInt(7, movieReview.getUnhelpful()); 
    preparedStatement.setString(8, movieReview.getComments()); 
    preparedStatement.executeUpdate(); 

    disconnect(); 

} 

/** 
* TODO: This method should try to update an existing MovieReview with the details of the given MovieReview 
* @param movieReview The MovieReview to be updated 
* @throws Exception If the ID of the MovieReview doesn't already exist 
*/ 
public static void edit(MovieReview movieReview) throws Exception { 

    // set precondition that ID being edited exists 
    MovieReview temp = find(movieReview.getId()); // find the ID 
    boolean exist = (temp != null); // Something needs to be in temp for exist to be true 

    if (!exist) // if not, show error 
    { 
     String message = "The movie you are trying to edit does not exist."; 
     throw new Exception(message); 
    } 

    connect(); 

    String editString = "UPDATE movie_review " + "SET user = ?," + "SET movie = ?," + "SET isFeatured = ?," 
    + "SET rating = ?," + "SET helpful = ?," + "SET unhelpful = ?," + "SET comments = ?"; 

    preparedStatement = connection.prepareStatement(editString); 
    preparedStatement.setString(1, movieReview.getUser()); 
    preparedStatement.setString(2, movieReview.getMovie()); 
    preparedStatement.setBoolean(3, movieReview.isFeatured()); 
    preparedStatement.setInt(4, movieReview.getRating()); 
    preparedStatement.setInt(5, movieReview.getHelpful()); 
    preparedStatement.setInt(6, movieReview.getUnhelpful()); 
    preparedStatement.setString(7, movieReview.getComments()); 
    preparedStatement.executeUpdate(); 

    disconnect(); 

} 

/** 
* TODO: This method should try to delete a MovieReview record from the database 
* @param movieReview The MovieReview to be deleted 
* @throws Exception If the ID of the MovieReview doesn't already exist 
*/ 
public static void delete(MovieReview movieReview) throws Exception { 
    // set precondition that ID being deleted exists 
    MovieReview temp = find(movieReview.getId()); // find the ID 
    boolean exist = (temp != null); // Something needs to be in temp for exist to be true 

    if (!exist) // if not, show error 
    { 
     String message = "The movie you are trying to delete does not exist."; 
     throw new Exception(message); 
    } 
    try 
    { 


    connect(); 

    String deleteString = "DELETE FROM movie_review WHERE id = ?"; 

    preparedStatement = connection.prepareStatement(deleteString); 
    preparedStatement.setString(1, movieReview.getId()); 
    preparedStatement.executeUpdate(); 

    disconnect(); 
    } 
    catch(SQLException e) 
    { 
     System.out.println(e); 
    } 
} 

MovieReview 클래스는 아마 포함 할 필요는 없지만 만약을 :

class MovieReview { 
private String id = ""; 
private String user = ""; 
private String movie = ""; 
private boolean isFeatured = false; 
private int rating = 0; 
private int helpful = 0; 
private int unhelpful = 0; 
private String comments = ""; 

public MovieReview(String id, String user, String movie, boolean isFeatured, int rating, int helpful, int unhelpful, String comments) { 
    this.id = id; 
    this.user = user; 
    this.movie = movie; 
    this.isFeatured = isFeatured; 
    this.rating = rating; 
    this.helpful = helpful; 
    this.unhelpful = unhelpful; 
    this.comments = comments; 
} 

public MovieReview(){} 

public String getId() { 
    return id; 
} 

public void setId(String id) { 
    this.id = id; 
} 

public String getUser() { 
    return user; 
} 

public void setUser(String user) { 
    this.user = user; 
} 

public String getMovie() { 
    return movie; 
} 

public void setMovie(String movie) { 
    this.movie = movie; 
} 

public boolean isFeatured() { 
    return isFeatured; 
} 

public void setFeatured(boolean isFavourite) { 
    this.isFeatured = isFavourite; 
} 

public int getRating() { 
    return rating; 
} 

public void setRating(int rating) { 
    this.rating = rating; 
} 

public int getHelpful() { 
    return helpful; 
} 

public void setHelpful(int helpful) { 
    this.helpful = helpful; 
} 

public int getUnhelpful() { 
    return unhelpful; 
} 

public void setUnhelpful(int unhelpful) { 
    this.unhelpful = unhelpful; 
} 

public String getComments() { 
    return comments; 
} 

public void setComments(String comments) { 
    this.comments = comments; 
} 

public boolean equals(Object obj) { 
    if (obj instanceof MovieReview) 
     return this.id.equalsIgnoreCase(((MovieReview)obj).id); 

    return super.equals(obj); 
} 

@Override 
public String toString() { 
    return "MovieReview{" + 
     "id='" + id + '\'' + 
     ", user='" + user + '\'' + 
     ", movie='" + movie + '\'' + 
     ", isFeatured=" + isFeatured + 
     ", rating=" + rating + 
     ", helpful=" + helpful + 
     ", unhelpful=" + unhelpful + 
     ", comments='" + comments + '\'' + 
     '}'; 
} 

}

나는 선별 할 것이 많다는 것을 알고 있지만, 도움을 정말 고맙게 생각합니다!

JDialog 인 ReviewEditor 클래스를 가져 오는 편집 버튼에 대한 도움이 필요합니다. 이미 추가 기능을 사용하고 있지만 편집을 통해 작업을 수행하는 방법, 선택된 행의 항목을 가져와 JDialog의 해당 텍스트 필드에 배치하는 방법을 실제로 알지 못합니다. 그러나 나는 다른 질문을하기 위해 그것을 남겨 두어야 할 것입니다.

의 TableModel 몇 가지 물건이있는 SQL 파일이 아마 당신은 무시할 수

클래스

import javax.swing.table.DefaultTableModel; 


public class MovieReviewTableModel extends DefaultTableModel 
{ 
public MovieReviewTableModel(Object[][] data, String[] columnNames) 
{ 
    super(data, columnNames); 
} 

@Override 
public Class getColumnClass(int columnIndex) 
{ 
    return getValueAt(0, columnIndex).getClass(); 
} 

@Override 
public boolean isCellEditable(int row, int column) 
{ 
    return false; 
} 


// Ripped this from Tools.java *** 
public static void log(Object... args) { 
    StringBuilder builder = new StringBuilder(); 

    for (Object o: args) { 
     builder.append(o); 
    } 

    System.out.println(builder); 
} 


public void display() 
{ 
    for (int i = 0; i < getRowCount(); i++) 
    { 
     log(
       "ID: ", getValueAt(i,0), 
       "User: ", getValueAt(i,1), 
       "Movie: ", getValueAt(i,2), 
       "Featured: ", getValueAt(i,3), 
       "Rating: ", getValueAt(i,4), 
       "Helpful: ", getValueAt(i,5), 
       "Unhelpful: ", getValueAt(i,6), 
       "Comments: ", getValueAt(i,7)); 
    } 
} 

} :

   drop table if exists movie_review; 

       create table movie_review(
        id varchar(5), 
        user varchar(20) not null, 
        movie varchar(50) not null, 
        featured boolean, 
        rating int, 
        helpful int, 
        unhelpful int, 
        comments blob, 
        primary key (id) 
       ); 

       -- listing all records in table 
       select * 
       from movie_review; 

       -- insert a nonsense record to be used to demonstrate this script 
       insert into movie_review 
       values('ID', 'User', 'Movie Name', 0, 4, 10, 5, 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'); 

       -- listing all records in table, sorted by name in ascending order 
       select * 
       from movie_review 
       order by movie; 

       select * 
       from movie_review 
       order by movie asc; 

       -- the default sort order is in ascending 
       -- how do we sort in descending order? 

       -- update name of record with id '???' 
       update movie_review 
       set movie = 'New Name', 
        featured = 1, 
        helpful = 11, 
        unhelpful = 4 
       where id = 'ID'; 

       -- delete record with id '???' 
       delete from movie_review 
       where id = 'ID'; 

       -- select 'useful' records 
       select * 
       from movie_review 
       where featured = 1 
       OR helpful > unhelpful; 

       -- some nonsense data to populate your database 
       insert into movie_review 
       values('R00', 'kyberp', 'The Hobbit', 0, 3, 0, 0, 'How he now follow a lot of the titular monster, from funny angles and you wants in what resolutely empathize with who is swimming destroyed civilisation in order the legend of bloke, to root for example, is absolutely punches his emotional core anything in return. Every sincere expressive set pieces and the might just because of that it was clear from stars out and perfectly under the 1940s, Steve. Giving us good as it.'); 

       insert into movie_review 
       values('R76', 'scalhotrod', 'WZTV', 0, 10, 16, 17, 'ER-heroes so how insanely worry about the book, I am not sure what in that even overall, If it has because thats why you see for sure what his film. That the many critics makes sense. Having build a massiveness into a morally establish character all, the best summer movie. If the first film and the brain premise we ride from back of really enjoyed civilisation of who we done, you a lifetime, it has even Batista! For this movie or did I was used it at the movie. It was pleasant.'); 

       insert into movie_review 
       values('R06', 'yvsreddy', 'Polavaram', 1, 6, 12, 9, 'The sea; Quint is exactly underwater violent shark, Spider Margarets be a walking the movie. One thought prophe while with teacher. In that keeps this comical score, it is rushed and have someone warmth of this one is a fun, very silly, Brody been overwhelmed but I actually verdict: Its the time issues" but quite simplicity, its the role lives. The film so present and unforget because that, and I forgot a quintessential effects. The fiction her own unhealthily zealous upbrings.'); 

       insert into movie_review 
       values('R83', 'bcp67', 'John Day', 0, 3, 9, 6, 'And, they fit most comfort him, the can say, e.g., Poltergeist, Close of story that, it hadnt existent. But all themes across like to diminish the movie I had sat this filled most chilling aura and again, seem to stay out there willing character. Also, the navy cannot see is for expected. Both bringing. As art, but does it hadnt the pacing in a time to day fable performances and sadly its lack off of that this filled his role the time, if youre willing, and entertain theres most obvious avoidance.'); 

       insert into movie_review 
       values('R09', 'niceguyedc', 'Salmo', 1, 6, 11, 8, 'The character be zapped in awe of who have the absence can say, it turns of 1976s they the Bigfoot of cards the modern day to decide they call this is a pathetic mayhem. Shes cute, capable, remember the suit who have the almost feared him some early hero zingers wife with childlike it out his best, grittiest approximately, most of Jaws, simple third act. They are the while his one who justify its attempting homeland odd, attempts to the Florida palms for sure through Shanghai was right'); 

       insert into movie_review 
       values('R15', 'giantsnowman', 'Dewey Lyle', 0, 6, 11, 8, 'I actually cant enjoyed the legend of an underplaying the world, and unforget because the movie (toward fan of Dr Manhattan). 
       Granted components as to really computer with who is Martin Brodys nemesis). Roy Scheiders Brody, a New York cop who was just way thrillers need depth. Yes, most bring happended up, but grown-ups with a detective. Much like flies... Guardians of loyalties of Jaws successful blow. 
       Finally, there werent a blockbuster.'); 

       insert into movie_review 
       values('R55', 'gobonobo', 'Supercritical Adsorption', 1, 3, 7, 15, 'In fact themselves. The who was use of the improve upon the confrontational blown commandos. Now they feed to believable with it. Who know all gun). All the level. It also get to present and its also warns of the time to be themes are primitives. Never is a wide-screen, yet has her on two hours dispatches him some of the excellent, storytelligent. Second, which and you are unimaginating the glowing to heart of stories and meant as atonement from the impression but it laying way.'); 
+1

우리는 테스트 할 수 없기 때문에 말하기가 어렵습니다. db 삭제 방법이 괜찮아 보입니다. 필터링 기능, 즉 표 필터, 표보기 및 표 모델 데이터 색인이 더 이상 동일하지 않은 것과 관련이있는 이유는 무엇입니까? 그래서 우리는'table.convertRowIndexToModel'을 사용하여 getSelectedRow()를 실제 모델 행으로 변환 할 수 있습니다. 인쇄 문 (또는 디버거)을 사용하여 어떤 오류를 제거 했습니까? –

+1

또 다른 주목할 점은 값을 얻기 전에'model.deleteRow()'를 호출한다는 것입니다. 행 제거를 호출하면 값은 더 이상 존재하지 않습니다. 그래서 두 가지를 생각해 보겠습니다. –

+1

또한, 원인은 없지만 왜 우리는'id' 만 사용하여 삭제할 때 새로운'MovieReview'의 모든 필드를 만들어야합니까? :-) 그냥 관찰 (문제가 아닌 것처럼 보임) –

답변

4

당신의 삭제 방법에서, 나는에서 항목을 제거하는 제안 데이터베이스 전에 테이블에서 제거합니다. 다음과 같은 간단한 테이블했다 말 :

1 A 
2 B 
3 C 

을 ... 그리고 우리는 행 인덱스가 아닌 내용으로 숫자를 치료하는 경우 행 2. 제거, 여기 당신이 지금 무엇을 가지고 :

1 A 
2 C 

코드에서 수행하는 것처럼 행 2의 데이터로 삭제할 MovieReview 레코드를 만들면 실제로 데이터베이스의 행 3을 참조하는 데이터가 사용됩니다.

비슷한 경우 테이블 모델 행과 테이블 행이 반드시 동일하지는 않습니다. 기본 테이블을 가지고 있다면 괜찮을 것입니다. 그러나 사용자가 어떤 식 으로든 테이블을 정렬하거나 필터링 할 수있게하려면 문제가 발생합니다.사용자가 보이는 JTable과 상호 작용하는 동안 테이블 모델을 사용자가 보는 것 뒤에있는 데이터의 마스터 복사본으로 생각하는 것이 도움이됩니다. 사용자는 모양과 느낌을 변경할 수 있지만 데이터는 기본 모델 뒤에 저장됩니다. 마지막으로

tableModel.removeRow(table.convertRowIndexToModel(row)) 

그것의 유일한 부분이기 때문에 내가 당신의 삭제 기능을 기본 문자열 ID를 전달하는 제안 : 당신이 테이블 모델에서 행을 제거 할 때, 여기에 그것을 할 수있는 안전한 방법입니다 당신이 사용하는 것으로 보이는 레코드. 이렇게하면 MovieReview 인스턴스를 구성하고 코드를 단순화 할 수 있습니다.

+0

이것이 작동하는 방식에 대한 훌륭한 설명이며 그렇게 작동한다는 것을 깨닫지 못했습니다. 나는 테이블 모델이 자신이하는 일을 알고있을 것이라고 생각했습니다. 나는 peeskillet이 말한 것을 시도했고, 지금 그것으로 무슨 일이 일어나고 있는지 이해합니다. 나는 이것이 내게 많은 두통을 덜어주기 위해 나의 테이블에서 기능하는 정렬을 가지고있다. 고맙습니다. – user3690863

관련 문제