这是偶的第一个java小程序,是一个汇率管理系统,部分功能还未实现,不足之处还请多多指导!
代码:
文件1:DbConn.java //用来连接数据库的
具体代码:import java.sql.*;
public class DbConn {
public static void main(String[] args) {
Connection conn;
Statement stmt;
ResultSet rs1;
// ResultSet rs2;
//changeRatesys是我的数据库
String url = "jdbc:mysql://localhost/changeRatesys";
String user = "root";
String pass = "admin";
try {//加载mysql驱动
Class.forName("org.gjt.mm.mysql.Driver");
}
catch (ClassNotFoundException e) {
// Exception handler for Class.forName(...)
System.err.println("Error! " + e.getMessage());
System.err.println("Please install JDBC Driver first.");
return;
}
try {
// Create Connection
conn = DriverManager.getConnection(url, user, pass);
// Create SQL Statement
String strSQL1 = "SELECT * FROM changeRate";
// String strSQL2 = "SELECT * FROM bzInfo";
stmt = conn.createStatement();
// Return the Results
rs1 = stmt.executeQuery(strSQL1);
// rs2 = stmt.executeQuery(strSQL2);
while (rs1.next()) {
System.out.print(rs1.getInt("recordID") + " ");
System.out.print(rs1.getString("hb1Code") + " ");
System.out.print(rs1.getString("hb2Code") + " ");
System.out.println(rs1.getDouble("rate"));
}
/*
while (rs2.next()) {
System.out.print(rs2.getInt("hbID") + " ");
System.out.print(rs2.getString("standString") + " ");
System.out.println(rs2.getString("description") + " ");
}
*/
} catch (SQLException e) {
System.err.println("SQL Error! " + e.getMessage());
e.printStackTrace(System.err);
} finally {
rs1 = null;
// rs2 = null;
stmt = null;
conn = null;
}
}
}
文件2:MainFrame.java //程序主要代码部分
具体代码:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class MainFrame extends JFrame {
Connection conn;
Statement smt;
ResultSet res;
public static final int WIDTH = 600;
public static final int HEIGHT = 400;
JLabel lbz1;
JTextField tbz1;
JLabel lbz2;
JTextField tbz2;
JLabel lchangeRate;
JTextField tchangeRate;
JTextArea showOut;
JTable tb = null;
DefaultTableModel tbModel = null;
public JTable initTable() {
Vector cell = null;
/* 表格行向量 */
Vector row = new Vector();
/* 声明表格模型 */
tbModel = new DefaultTableModel();
/* 声明表格头数组 */
String[] tableHeads = { "记录号", "币种1", "币种2", "汇率" };
/* 将表格头转换过向量类型,以备表格模型使用 */
Vector tableHeadName = new Vector();
for (int i = 0; i < tableHeads.length; i++) {
tableHeadName.add(tableHeads[i]);
}
/* 初始化表格数据,这些数据实例运行来源于数据库中 */
/* 设置表格模型 */// 行数组 和 设置表头
// tableModel.setDataVector(row, tableHeadName);
tbModel.setDataVector(null, tableHeadName);
tbModel.addRow(cell);
/* 表格使用模型 */
JTable tb = new JTable(tbModel);
// 设置每行的高度
tb.setRowHeight(20);
tb.setCursor(new Cursor(12));
return tb;
}
public void connDb() {
String url = "jdbc:mysql://localhost/changeRatesys";
String user = "root";
String pass = "admin";
// Register the Driver
try {
// 加载Mysql驱动
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
// Exception handler for Class.forName(...)
System.err.println("Error! " + e.getMessage());
System.err.println("Please install JDBC-Mysql Driver first.");
return;
}
// Main Process of retrieving data with JDBC
// while (true) {
try {
// Create Connection
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public void query() {
int length = tbModel.getRowCount();
for (int i = 0; i < length; i++) {
tbModel.removeRow(0);
}
// outputText.setText("");
String bz1str = tbz1.getText();
String bz2str = tbz2.getText();
String sqlquery = "select * from changeRate ";
String sqlstr = "";
if (bz1str.trim().length() > 0)
sqlstr = " where hb1Code='" + bz1str + "'";
if (bz2str.trim().length() > 0) {
if (sqlstr == "")
sqlstr += " where hb2Code='" + bz2str + "'";
else
sqlstr += " and hb2Code='" + bz2str + "'";
}
sqlquery += sqlstr;
try {
smt = conn.createStatement();
res = smt.executeQuery(sqlquery);
while (res.next()) {
Vector cell1 = new Vector();
cell1.add(res.getInt("recordID") + " ");
cell1.add(res.getString("hb1Code") + " ");
cell1.add(res.getString("hb2Code") + " ");
cell1.add(res.getDouble("rate") + " ");
tbModel.addRow(cell1);
double data = res.getDouble("rate");
if ((bz1str.trim().length() > 0)
&& (bz2str.trim().length() > 0))
tchangeRate.setText(data + "");
}
res.close();
smt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void importFile() {
FileDialog fd = new FileDialog(this, "打开文件", FileDialog.LOAD);
fd.setVisible(true);
String strFile = fd.getDirectory() + fd.getFile();
if (strFile != null) {
try {
FileInputStream fis = new FileInputStream(strFile);
byte[] buf = new byte[10 * 1024];
int length = fis.read(buf);
showOut.append(new String(buf, 0, length));
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void addData() {
String bz1str = tbz1.getText();
String bz2str = tbz2.getText();
String tcrstr = tchangeRate.getText();
int id = 0;
try {
String strSQL = "select * from changeRate where hb1Code='" + bz1str
+ "' and hb2Code='" + bz2str + "'";
// String strSQL = "select * from huilv ";
smt = conn.createStatement();
ResultSet res = smt.executeQuery(strSQL);
if (res == null || !res.next()) {
String inSQL = "insert into changeRate values(" + id + ",'"
+ bz1str + "','" + bz2str + "'," + tcrstr + ")";
smt.executeUpdate(inSQL);
} else {
String inSQL = "update changeRate set rate =" + tcrstr
+ " where hb1Code='" + bz1str + "' and hb2Code='"
+ bz2str + "'";
smt.executeUpdate(inSQL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void deleData() {
}
public void clean() {
int length = tbModel.getRowCount();
for (int i = 0; i < length; i++) {
tbModel.removeRow(0);
}
}
public void outputFile() {
FileDialog fd = new FileDialog(this, "保存文件", FileDialog.SAVE);
fd.setVisible(true);
try {
BufferedWriter br = new BufferedWriter(new FileWriter(fd
.getDirectory()
+ fd.getFile()));
String sqlstr = "select * from changeRate ";
smt = conn.createStatement();
res = smt.executeQuery(sqlstr);
while (res.next()) {
String oput = res.getInt("recordID") + "\t"
+ res.getString("hb1Code") + "\t"
+ res.getString("hb2Code") + "\t"
+ res.getDouble("rate") + "\r\n";
br.write(oput);
}
br.close();
smt.close();
res.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public MainFrame() {
this.setTitle("汇率管理系统");
this.setSize(WIDTH, HEIGHT);
this.setLocation(200, 200);
connDb();// 数据库连接初始化
// 定义面板
JPanel ltjp = new JPanel(new FlowLayout());
JPanel btnjp = new JPanel(new FlowLayout());
JPanel showjp = new JPanel(new BorderLayout());
// 添加Label和TextField控件
lbz1 = new JLabel("币种1:");
tbz1 = new JTextField(10);
lbz2 = new JLabel("币种2:");
tbz2 = new JTextField(10);
lchangeRate = new JLabel("汇率:");
tchangeRate = new JTextField(10);
showOut = new JTextArea();
showOut.setBackground(Color.pink);
ltjp.add(lbz1);
ltjp.add(tbz1);
ltjp.add(lbz2);
ltjp.add(tbz2);
ltjp.add(lchangeRate);
ltjp.add(tchangeRate);
JScrollPane showp = new JScrollPane(showOut);
showjp.add(showp);
showjp.setPreferredSize(new Dimension(500, 100));
// 创建Table
tb = initTable();
tb.setPreferredScrollableViewportSize(new Dimension(500, 150));
JScrollPane tp = new JScrollPane(tb);
// 添加Button控件及相应事件
JButton bQuery = new JButton("查询");
btnjp.add(bQuery);
bQuery.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
query();
}
});
JButton bImportfile = new JButton("导入文件");
btnjp.add(bImportfile);
bImportfile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
importFile();
}
});
JButton bAddData = new JButton("添加数据");
btnjp.add(bAddData);
bAddData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
addData();
}
});
JButton bDelData = new JButton("删除数据");
btnjp.add(bDelData);
bDelData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
deleData();
}
});
JButton bCleanList = new JButton("清空列表");
btnjp.add(bCleanList);
bCleanList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
clean();
}
});
JButton bOutFile = new JButton("导出文件");
btnjp.add(bOutFile);
bOutFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JFileChooser sav = new JFileChooser();
sav.showSaveDialog(null);
outputFile();
}
});
// 获取container容器,添加面板
Container ct = this.getContentPane();
ct.setLayout(new FlowLayout());
ct.add(ltjp);
ct.add(btnjp);
ct.add(tp);
ct.add(showjp);
}
}
文件3:RunningCode.java //程序从此处运行
具体代码:
import javax.swing.JFrame;
public class RunningCode {
public static void main(String[] args){
MainFrame frm = new MainFrame();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setVisible(true);
}
}
备注:这三个文件放在同一个包中运行