2012-03-02 70 views
1

刚刚开始使用Java并急需您的帮助。我有一个从数据库检索数据并在JTable中显示它的JComboBox。 我的问题是,当我选择学生时,它显示关于学生的数据,当选择其他选项时,如教师,它还显示有关教师的数据,但它附加在学生显示的数据上。我不知道如何显示学生的数据只有和其他人一样。清除JTable,使用JComboBox从数据库中检索数据

下面是我使用的代码。也许我错过了一些东西。

import javax.swing.*; 
import java.sql.*; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.table.DefaultTableModel; 
import javax.swing.table.TableModel; 


public class VisibilityTool extends javax.swing.JFrame { 

public VisibilityTool() { 
    initComponents(); 
} 


//Generate 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code"> 
private void initComponents() { 

    eMail = new javax.swing.JLabel(); 
    comBox = new javax.swing.JComboBox(); 
    emailText = new javax.swing.JTextField(); 
    buttonGenerate = new javax.swing.JButton(); 
    progressBar = new javax.swing.JProgressBar(); 
    selectEnvironment = new javax.swing.JLabel(); 
    jScrollPane1 = new javax.swing.JScrollPane(); 
    dataTable = new javax.swing.JTable(); 
    jMenuBar1 = new javax.swing.JMenuBar(); 
    file = new javax.swing.JMenu(); 
    exit = new javax.swing.JMenuItem(); 
    help = new javax.swing.JMenu(); 
    about = new javax.swing.JMenuItem(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 
    setTitle("[Trax] Data Visibility Tool"); 
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); 
    setFocusCycleRoot(false); 
    setForeground(java.awt.Color.black); 

    eMail.setBackground(new java.awt.Color(51, 51, 51)); 
    eMail.setFont(new java.awt.Font("Lucida Bright", 1, 12)); // NOI18N 
    eMail.setText("E - mail address :"); 

    comBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Select . . .", "Students", "Teachers", "Directors" })); 
    comBox.setToolTipText("'Choose the database to query'"); 
    comBox.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      comBoxActionPerformed(evt); 
     } 
    }); 

    emailText.setToolTipText("'Put you e-mail address here'"); 
    emailText.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      emailTextActionPerformed(evt); 
     } 
    }); 

    buttonGenerate.setText("GENERATE"); 
    buttonGenerate.setToolTipText("'GENERATE'"); 
    buttonGenerate.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      buttonGenerateActionPerformed(evt); 
     } 
    }); 

    selectEnvironment.setBackground(new java.awt.Color(51, 51, 51)); 
    selectEnvironment.setFont(new java.awt.Font("Lucida Bright", 1, 12)); // NOI18N 
    selectEnvironment.setText("Select Environment :"); 

    dataTable.setModel(new javax.swing.table.DefaultTableModel(
     new Object [][] { 

     }, 
     new String [] { 
      "ID", "Name", "Surname", "Age" 
     } 
    ) { 
     boolean[] canEdit = new boolean [] { 
      false, false, false, false 
     }; 

     public boolean isCellEditable(int rowIndex, int columnIndex) { 
      return canEdit [columnIndex]; 
     } 
    }); 
    dataTable.getTableHeader().setReorderingAllowed(false); 
    jScrollPane1.setViewportView(dataTable); 
    dataTable.getColumnModel().getColumn(0).setResizable(false); 
    dataTable.getColumnModel().getColumn(1).setResizable(false); 
    dataTable.getColumnModel().getColumn(2).setResizable(false); 
    dataTable.getColumnModel().getColumn(3).setResizable(false); 

    file.setText("File"); 
    file.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      fileActionPerformed(evt); 
     } 
    }); 

    exit.setText("Exit"); 
    exit.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      exitActionPerformed(evt); 
     } 
    }); 
    file.add(exit); 

    jMenuBar1.add(file); 

    help.setText("Help"); 
    help.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      helpActionPerformed(evt); 
     } 
    }); 

    about.setText("About"); 
    about.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      aboutActionPerformed(evt); 
     } 
    }); 
    help.add(about); 

    jMenuBar1.add(help); 

    setJMenuBar(jMenuBar1); 

    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.TRAILING) 
       .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 483, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) 
         .addComponent(buttonGenerate) 
         .addGroup(layout.createSequentialGroup() 
          .addContainerGap() 
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
           .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
           .addGroup(layout.createSequentialGroup() 
            .addComponent(eMail, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) 
            .addGap(43, 43, 43) 
            .addComponent(emailText, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE))))) 
        .addGroup(layout.createSequentialGroup() 
         .addContainerGap() 
         .addComponent(selectEnvironment, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addGap(18, 18, 18) 
         .addComponent(comBox, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)))) 
      .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addContainerGap() 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(selectEnvironment, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addComponent(comBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
      .addGap(27, 27, 27) 
      .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
      .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) 
       .addComponent(eMail, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addComponent(emailText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
      .addGap(30, 30, 30) 
      .addComponent(buttonGenerate) 
      .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
      .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(19, Short.MAX_VALUE)) 
    ); 

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

private void comBoxActionPerformed(java.awt.event.ActionEvent evt) {           
    if (comBox.getSelectedItem() == "Select . . .") { 


    } else if (comBox.getSelectedItem() == "Students") { 
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel(); 
    String sql = "select * from students"; 
    try { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
     } catch (ClassNotFoundException ex) { 
      Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/datavisibility","root",""); 
     Statement statmnt = connect.createStatement(); 
     ResultSet rslt = statmnt.executeQuery(sql); 
     while(rslt.next()){ 
      String id = rslt.getString("ID"); 
      String name = rslt.getString("Name"); 
      String surname = rslt.getString("Surname"); 
      String age = rslt.getString("Age"); 
      model.addRow(new Object[]{id,name,surname,age}); 

     } 
    } catch(SQLException e){ 
     e.printStackTrace(); 
    } 
    } else if (comBox.getSelectedItem() == "Teachers"){ 
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel(); 
    String sql = "select * from teachers"; 
    try { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
     } catch (ClassNotFoundException ex) { 
      Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/datavisibility","root",""); 
     Statement statmnt = connect.createStatement(); 
     ResultSet rslt = statmnt.executeQuery(sql); 
     while(rslt.next()){ 
      String id = rslt.getString("ID"); 
      String name = rslt.getString("Name"); 
      String surname = rslt.getString("Surname"); 
      String age = rslt.getString("Age"); 
      model.addRow(new Object[]{id,name,surname,age}); 

     } 
    } catch(SQLException e){ 
     e.printStackTrace(); 
    } 
    } else if (comBox.getSelectedItem() == "Directors") { 
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel(); 
    String sql = "select * from directors"; 
    try { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
     } catch (ClassNotFoundException ex) { 
      Logger.getLogger(tests.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     Connection connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/datavisibility","root",""); 
     Statement statmnt = connect.createStatement(); 
     ResultSet rslt = statmnt.executeQuery(sql); 
     while(rslt.next()){ 
      String id = rslt.getString("ID"); 
      String name = rslt.getString("Name"); 
      String surname = rslt.getString("Surname"); 
      String age = rslt.getString("Age"); 
      model.addRow(new Object[]{id,name,surname,age}); 

     } 
    } catch(SQLException e){ 
     e.printStackTrace(); 
    } 
    } 
}   

非常感谢您的帮助。

回答

3

1)限定TableModel只有一次时间(意味着代码行)

DefaultTableModel model = (DefaultTableModel) dataTable.getModel(); 

2)从TableModel删除与反转方式,所有行

if (model.getRowCount() > 0) { 
    for (int i = model.getRowCount() - 1; i > 0; i--) { 
     model.removeRow(i); 
    } 
} 

3)然后从ResultSet

添加新行

4)此代码与Concurency in Swing有问题,所有的GUI都是不负责任的,直到ResultSet结束,上ExceptionsResultSetMouse hover_overJTable's行刷新界面,更好的将来自SwingWorkerRunnable#Thread

5)请写出你的手代码调用ResultSet,因为潜在的应答者(INC的90pct。我)无法运行某些IDE生成的代码,也无法定义局部变量

+0

+1 27秒前:-) – StanislavL 2012-03-02 13:06:02

+0

非常感谢您的精确回答。我只是觉得用IDE编写程序更好也更容易,这是错误的。 – Karl 2012-03-02 13:23:14

3

在添加之前,从模型中删除所有旧值(行?)。使用public void removeRow(int row)模型的方法。

+0

+1为清晰和简单的答案,没有任何balast :-) – mKorbel 2012-03-02 13:10:01

0

之前,总有一天我写了一个TableModel的,那就是:

public class MovieSearchResultTableModel extends AbstractTableModel { 

    private static final long serialVersionUID = 46L; 

    private List<MovieSearchModel> movieSearchModels; 
    private ComponentConstant.ColumnName[] columns = ComponentConstant.Column.MOVIE_SEARCH_RESULT_TABLE; 

    public int getRowCount() { 
     return movieSearchModels.size(); 
    } 

    public int getColumnCount() { 
     return columns.length; 
    } 

    @Override 
    public String getColumnName(int columnIndex) { 
     return columns[columnIndex].getName(); 
    } 

    @Override 
    public Class<?> getColumnClass(int columnIndex) { 
     return columns[columnIndex].getClass(); 
    } 

    public Object getValueAt(int rowIndex, int columnIndex) { 
     Object returnValue = new Object(); 
     switch(columnIndex) { 
      case 0: 
       returnValue = movieSearchModels.get(rowIndex).getName(); 
       break; 
      case 1: 
       returnValue = movieSearchModels.get(rowIndex).getReleased(); 
       break; 
      case 2: 
       returnValue = movieSearchModels.get(rowIndex).getLanguage(); 
       break; 
      case 3: 
       returnValue = movieSearchModels.get(rowIndex).getRating(); 
       break; 
      case 4: 
       returnValue = movieSearchModels.get(rowIndex).getCertification(); 
       break; 
      case 5: 
       returnValue = movieSearchModels.get(rowIndex).getImdb_id(); 
       break; 
     }  
     return returnValue; 
    } 

    public List<MovieSearchModel> getMovieSearchModels() { 
     return movieSearchModels; 
    } 

    public void setMovieSearchModels(List<MovieSearchModel> movieSearchModels) { 
     this.movieSearchModels = movieSearchModels; 
    } 
} 

它是复杂的。但基本逻辑是,它有一个对象列表movieSearchModels。它的MovieSearchModel类型和方法getValueAt()填充表格。当我需要更改TableModel时,我从表中提取模型并将新值设置为movieSearchModels,然后在TableModel的帮助下触发fireTableDataChanged。喜欢:

List<MovieSearchModel> movieSearchModels = ModelUtils.getMovieSearchModels(movieSearchResults); 
MovieSearchResultTableModel movieSearchResultTableModel = (MovieSearchResultTableModel) ModelFactory.getMovieSearchResultTableModel(); 
movieSearchResultTableModel.setMovieSearchModels(movieSearchModels); 
movieSearchResultTableModel.fireTableDataChanged(); 

如果您有任何疑问,你可以问。

+1

从来没有,真的永远不会调用TableModel相关事件ouside TableModel(fireTableDataChanged()),正如我前面提到的请问这里JTable和TableModel如何工作,这里集中了一个很少有杰出的Swing Guru能够理解....对抗潜在的donw_voting – mKorbel 2012-03-02 13:17:02

+0

我想对于像我这样的初学者来说,它变得更加复杂。我试过'model.fireTableDataChanged();'但它不显示数据。 – Karl 2012-03-02 13:17:21

+0

@Karl忘记了,关于此代码行在这种情况下, – mKorbel 2012-03-02 13:18:45