清单 1. 把 ActionListener 定义为 GUI 中的一个按钮
findWidgetButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String value = widgetValue.getText(); if (value == null || value.equals("")) { dLabel.setText("Please enter a valid widgetID"); } else { dLabel.setText(getOrderStatus(value)); } } catch (Exception ex) { dLabel.setText("Widget doesn't exist in system"); } } //more code }); |
单击 GUI 的按钮组件后,直接从数据库中检索某个特定命令的状态,如清单 2 所示:
清单 2. GUI 通过 getOrderStatus 方法直接与数据库通信
private String getOrderStatus(String value) { String retValue = "Widget doesn't exist in system"; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = DriverManager.getConnection("jdbc:hsqldb:hsql://127.0.0.1", "sa", ""); stmt = con.createStatement(); rs = stmt.executeQuery("select order.status " + "from order, widget where widget.name = " + "'" + value + "' " + "and widget.id = order.widget_id;"); StringBuffer buff = new StringBuffer(); |