這是偶的第一個java小程序,是一個匯率管理系統(tǒng),部分功能還未實現(xiàn),不足之處還請多多指導(dǎo)!
代碼:
文件1:DbConn.java? //用來連接數(shù)據(jù)庫的
具體代碼:import java.sql.*;
public class DbConn {
??
?public static void main(String[] args) {
??
??Connection conn;
??Statement stmt;
??ResultSet rs1;
//??ResultSet rs2;
//changeRatesys是我的數(shù)據(jù)庫
??String url = "jdbc:mysql://localhost/changeRatesys";
??String user = "root";
??String pass = "admin";
??
??try {//加載mysql驅(qū)動
???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();
??/* 聲明表格頭數(shù)組 */
??String[] tableHeads = { "記錄號", "幣種1", "幣種2", "匯率" };
??/* 將表格頭轉(zhuǎn)換過向量類型,以備表格模型使用 */
??Vector tableHeadName = new Vector();
??for (int i = 0; i < tableHeads.length; i++) {
???tableHeadName.add(tableHeads[i]);
??}
??/* 初始化表格數(shù)據(jù),這些數(shù)據(jù)實例運行來源于數(shù)據(jù)庫中 */
??/* 設(shè)置表格模型 */// 行數(shù)組 和 設(shè)置表頭
??// tableModel.setDataVector(row, tableHeadName);
??tbModel.setDataVector(null, tableHeadName);
??tbModel.addRow(cell);
??/* 表格使用模型 */
??JTable tb = new JTable(tbModel);
??// 設(shè)置每行的高度
??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驅(qū)動
???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("匯率管理系統(tǒng)");
??this.setSize(WIDTH, HEIGHT);
??this.setLocation(200, 200);
??connDb();// 數(shù)據(jù)庫連接初始化
??// 定義面板
??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));
??// 創(chuàng)建Table
??tb = initTable();
??tb.setPreferredScrollableViewportSize(new Dimension(500, 150));
??JScrollPane tp = new JScrollPane(tb);
??// 添加Button控件及相應(yīng)事件
??JButton bQuery = new JButton("查詢");
??btnjp.add(bQuery);
??bQuery.addActionListener(new ActionListener() {
???public void actionPerformed(ActionEvent event) {
????query();
???}
??});
??JButton bImportfile = new JButton("導(dǎo)入文件");
??btnjp.add(bImportfile);
??bImportfile.addActionListener(new ActionListener() {
???public void actionPerformed(ActionEvent event) {
????importFile();
???}
??});
??JButton bAddData = new JButton("添加數(shù)據(jù)");
??btnjp.add(bAddData);
??bAddData.addActionListener(new ActionListener() {
???public void actionPerformed(ActionEvent event) {
????addData();
???}
??});
??JButton bDelData = new JButton("刪除數(shù)據(jù)");
??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("導(dǎo)出文件");
??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);
?}
}
備注:這三個文件放在同一個包中運行