我们的教授给我们举例说明了他在嵌入数据库中的代码,同时使用GUI在表格中进行了更改。
这是我使用的代码
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import static java.awt.GridBagConstraints.*;
import java.sql.*;
import java.util.*;
public class Gadgets2
{
private JPanel mainPanel, topPanel, midPanel, bottomPanel;
private JTextField txtBRAND, txtNAME, txtCOLOR;
private JButton btnAdd, btnEdit, btnDelete;
private JTable tblGadgets;
private DefaultTableModel model;
private Vector<Object> columnNames = new Vector<Object>();
private Vector<Object> data = new Vector<Object>();
private String dbName = "GadgetsDB";
private String connectionURL = "jdbc:derby://localhost:1527/" + dbName + ";create=true";
private Connection conn;
private Statement stmt;
private ResultSet rs;
public Gadgets2()
{
connectDB();
loadGadgets();
buildGUI();
}
private void addComponent(Container container, Component component,
int gridX, int gridY, int gridWidth, int gridHeight, int anchor, int fill)
{
Insets insets = new Insets(2, 2, 2, 2);
GridBagConstraints gbc = new GridBagConstraints(gridX, gridY, gridWidth,
gridHeight, 1.0, 1.0, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
private void buildGUI()
{
JFrame frame = new JFrame("Gadgets");
JLabel lblGadgets = new JLabel("Gadgets");
mainPanel = new JPanel(new GridBagLayout());
topPanel = new JPanel(new GridBagLayout());
midPanel = new JPanel(new GridBagLayout());
bottomPanel = new JPanel(new GridBagLayout());
model = new DefaultTableModel(data, columnNames)
{
@Override
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
@Override
public boolean isCellEditable(int row, int column)
{
return false;
}
};
tblGadgets = new JTable( model );
tblGadgets.getSelectionModel().addListSelectionListener(
new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent event) {
if (! event.getValueIsAdjusting())
{
showGadgetsInfo();
}
}
});
tblGadgets.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tblGadgets.setCellSelectionEnabled(false);
tblGadgets.setColumnSelectionAllowed(false);
tblGadgets.setRowSelectionAllowed(true);
JScrollPane scrollPane = new JScrollPane( tblGadgets,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
addComponent(topPanel, lblGadgets, 0, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(topPanel, scrollPane, 0, 1, 1, 1, BASELINE_LEADING, NONE);
JLabel lblBRAND = new JLabel("BRAND");
JLabel lblNAME = new JLabel("NAME");
JLabel lblCOLOR = new JLabel("COLOR");
txtBRAND = new JTextField(20);
txtNAME = new JTextField(20);
txtCOLOR = new JTextField(10);
addComponent(midPanel, lblBRAND, 0, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(midPanel, txtBRAND, 1, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(midPanel, lblNAME, 0, 1, 1, 1, BASELINE_LEADING, NONE);
addComponent(midPanel, txtNAME, 1, 1, 1, 1, BASELINE_LEADING, NONE);
addComponent(midPanel, lblCOLOR, 0, 2, 1, 1, BASELINE_LEADING, NONE);
addComponent(midPanel, txtCOLOR, 1, 2, 1, 1, BASELINE_LEADING, NONE);
btnAdd = new JButton("Add");
btnEdit = new JButton("Edit");
btnDelete = new JButton("Delete");
addComponent(bottomPanel, btnAdd, 0, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(bottomPanel, btnEdit, 1, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(bottomPanel, btnDelete, 2, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(mainPanel, topPanel, 0, 0, 1, 1, BASELINE_LEADING, NONE);
addComponent(mainPanel, midPanel, 0, 1, 1, 1, CENTER, BOTH);
addComponent(mainPanel, bottomPanel, 0, 2, 1, 1, BASELINE_TRAILING, NONE);
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
scrollPane.setPreferredSize(new Dimension(600,150));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
setTextfieldsEditable(false);
btnAdd.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if (btnAdd.getText().equals("Add"))
{
btnAdd.setText("Save");
btnEdit.setText("Cancel");
btnDelete.setVisible(false);
tblGadgets.setEnabled(false);
clearTextfields();
setTextfieldsEditable(true);
} else if (btnAdd.getText().equals("Save"))
{
btnAdd.setText("Add");
btnEdit.setText("Edit");
btnDelete.setVisible(true);
tblGadgets.setEnabled(true);
setTextfieldsEditable(false);
doInsertNewRecord();
loadGadgets();
clearTextfields();
}
}
}
);
btnEdit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if (tblGadgets.getSelectedRow()<0)
{
JOptionPane.showMessageDialog(null, "Please select an item in the table to edit.");
return;
}
if (btnEdit.getText().equals("Cancel"))
{
btnAdd.setText("Add");
btnEdit.setText("Edit");
btnDelete.setVisible(true);
tblGadgets.setEnabled(true);
setTextfieldsEditable(false);
} else if (btnEdit.getText().equals("Edit"))
{
btnAdd.setVisible(false);
btnEdit.setText("Save");
btnDelete.setText("Cancel");
tblGadgets.setEnabled(false);
setTextfieldsEditable(true);
} else if(btnEdit.getText().equals("Save"))
{
btnAdd.setVisible(true);
btnEdit.setText("Edit");
btnDelete.setText("Delete");
tblGadgets.setEnabled(true);
setTextfieldsEditable(false);
doSaveEdits();
loadGadgets();
}
}
}
);
btnDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if (btnDelete.getText().equals("Cancel"))
{
btnAdd.setVisible(true);
btnEdit.setText("Edit");
btnDelete.setText("Delete");
tblGadgets.setEnabled(true);
} else if (btnDelete.getText().equals("Delete")) {
if (tblGadgets.getSelectedRow() <0)
{
JOptionPane.showMessageDialog(null,
"You haven't selected any item. Please select the gadget from \n" +
"the list.");
return;
}
String message = "Proceed to delete the selected record?";
String title = "Confirm delete";
int reply = JOptionPane.showConfirmDialog(
null, message, title, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
doDeleteRecord();
loadGadgets();
tblGadgets.repaint();
clearTextfields();
}
}
}
}
);
}
private void connectDB()
{
try
{
conn = DriverManager.getConnection(connectionURL);
} catch (SQLException ex) {
displaySQLErrors(ex);
}
}
private void loadGadgets()
{
try
{
columnNames.clear();
data.clear();
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT BRAND, NAME, COLOR FROM Gadgets");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
} catch (SQLException ex){
displaySQLErrors(ex);
} catch (Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
private void doInsertNewRecord()
{
try
{
Statement stmt = conn.createStatement();
int i = stmt.executeUpdate("INSERT INTO Gadgets (BRAND, NAME, COLOR) " +
"VALUES ('" + txtBRAND.getText() + "', '" +
txtNAME.getText() + "', " +
txtCOLOR.getText() + ")");
} catch (SQLException ex){
displaySQLErrors(ex);
}
}
private void doSaveEdits()
{
try {
Statement stmt = conn.createStatement();
int i = stmt.executeUpdate("UPDATE Gadgets " +
"SET BRAND = '" + txtBRAND.getText() + "', " +
"NAME = '" + txtNAME.getText() + "', " +
"COLOR = '" + txtCOLOR.getText() + " WHERE BRAND ='" +
tblGadgets.getValueAt(tblGadgets.getSelectedRow(), 0).toString() + "'");
} catch (SQLException ex)
{
displaySQLErrors(ex);
} catch (Exception ex1) {
ex1.printStackTrace();
}
}
private void doDeleteRecord()
{
try {
Statement stmt = conn.createStatement();
int i = stmt.executeUpdate(
"DELETE FROM Gadgets where BRAND = '" +
txtBRAND.getText() + "'");
} catch (SQLException ex) {
displaySQLErrors(ex);
}
}
private void clearTextfields()
{
txtBRAND.setText("");
txtNAME.setText("");
txtCOLOR.setText("");
}
private void setTextfieldsEditable(boolean editable)
{
txtBRAND.setEditable(editable);
txtNAME.setEditable(editable);
txtCOLOR.setEditable(editable);
}
private void showGadgetsInfo()
{
try
{
rs.beforeFirst();
while(rs.next())
{
if (rs.getString("BRAND").equals(
tblGadgets.getValueAt(tblGadgets.getSelectedRow(), 0).toString()))
break;
}
if (!rs.isAfterLast())
{
txtBRAND.setText(rs.getString("BRAND"));
txtNAME.setText(rs.getString("NAME"));
txtCOLOR.setText(rs.getString("COLOR") + "");
}
} catch (SQLException ex) {
displaySQLErrors(ex);
}
}
private void displaySQLErrors(SQLException ex)
{
String errorText = "SQL Exception: " + ex.getMessage() + "\n" +
"SQL state: " + ex.getSQLState() + "\n" +
"Vendor Error: " + ex.getErrorCode();
JOptionPane.showMessageDialog(null, errorText);
}
public static void main(String[] args)
{
Gadgets2 app = new Gadgets2();
}
}
我写这段代码时遇到了一些麻烦......我做错了吗?
答案 0 :(得分:1)
没有合适的驱动程序 - 将其添加到类路径中。你需要derbyclient.jar或类似的东西。
点击此处查看解释:http://www.codejava.net/java-se/jdbc/connect-to-apache-derby-java-db-via-jdbc