刚刚开始使用Java并且非常需要你的帮助。我有一个JComboBox,它从数据库中检索数据并将其显示在JTable中。 我的问题是,当我选择学生时,它会显示有关学生的数据,当选择其他选项时,就像教师一样,它也会显示有关教师的数据,但会附加关于学生显示的数据。我想知道如何显示仅限学生的数据,与其他人一样。
以下是我使用的代码。也许我错过了什么。
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();
}
}
}
非常感谢你的帮助。
答案 0 :(得分: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
Exceptions
仅ResultSet
Mouse hover_over
JTable's
ResultSet
结束时仍然不负责任Runnable#Thread
1}}行刷新GUI,最好从SwingWorker或{{1}}
5)请亲自编写代码,因为90pct的潜在回答者(包括我)无法从某些IDE运行生成的代码而没有局部变量的定义
答案 1 :(得分:3)
在添加之前从模型中删除所有旧值(行?)。使用public void removeRow(int row)
模型方法。
答案 2 :(得分: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();
如果您有任何疑问,可以询问。