首页 > 代码库 > JAVA学习作品之销售管理系统V1.0

JAVA学习作品之销售管理系统V1.0

     这套管理系统是本人学习JAVA一个月的作品,开发周期近10天左右。代码量约1500行,基于Eclipse JDK1.7,运用了Swing/SWT 开发工具Windowbuilder,配套的还包含JDBC驱动、以及微软的SQL Server数据库。

源代码所有开放,本人多轮測试。结果OK。

因为本人初学JAVA,代码漏洞及不足之处难免,还请多多指正!

有用方面,假设增加扫码器接口,软件应该会更完美!仅仅是条件有限。仅为学习。

第一部分:首先看下软件信息,大小600k不到。双击执行。前提JDK1.7及以上环境配置好, SQL Server数据库安装好,数据库配置3个table例如以下图:

技术分享


技术分享


双击.jar程序,打开系统。界面如图:

技术分享

工具栏两个选项:数据库管理、关于,主界面5大功能块进货、定价、销售、报废、报表。

其它(未开发功能)。

点开工具栏数:据库管理。能够选择清除系统中旧数据,防止系统执行几年后数据累积增导致执行速度变慢:

技术分享

点击两年前数据,弹出对话框,提示是否删除yyyy-mm-dd之前的数据,点击确定弹出清理成功。

技术分享

点击关于,显示版本号等信息:

技术分享

点击主界面进货。进入进货管理界面,输入我们进货的信息:品名(商品名称)、数量、单位(销售单位。不支持单位换算)、总价(该数量下的总金额),录入例如以下信息

技术分享


点击提交button,提示成功!

(假设商品之前有记录过,输入商品名后,按Enter键,会自己主动带出商品单位)。 我们继续多输入一些其它商品。。。

技术分享


点击定价,进入定价界面。界面左边两个button。

查找button:首先选择日期区间(系统默认一个月。我们调整为近期三天)。起始和结束日期,对这一时间区间进货的商品指定销售价格

技术分享


我们点击查找button,显示我们2016/03/20-2016/03/28的全部进货商品。系统自己主动计算出进货的价格。以此作为销售价格的參考

技术分享


再看左下角的统一按比例加价(进货单位价格*比例)和 统一按固定值加价(进货单位价格+固定值),我们模拟比例加价25%,点击确定button。看下销售单位价格变化

技术分享


当然销售单位价格能够手动修改,比方我们将雀巢咖啡的价格修改为22元/盒。直接更改后按Enter就可以

技术分享

确定好销售价格后,我们点提交button。提示提交成功!技术分享


再点击我们的销售功能,进入销售管理界面:下拉框直接选择商品,系统自己主动带出商品单位。假设上一步你有维护价格,系统也会自己主动带出销售价格,你仅仅须要输入数量就可以。

当然,假设没有维护销售价格,你能够手动输入单位价格,单位价格能够被手动调整

技术分享

比方客户要买薯片2个。选择百事薯片,系统带出价格4.75(能够被改动)。输入数量2个,点击>>button,增加购物车,总价9.5。我们多购买一些商品

技术分享


假设我想将真彩水笔从购物车移除。选中点击删除button就可以

技术分享

假设同一商品多次增加购物车。系统会提示反复增加。请删除后,又一次输入数量再次增加。

最后。我们点击提交button,系统会计算购物车的总金额。提示是否提交

技术分享

点是(Y)。显示提交结果。交易成功。


回到主界面。点击报废功能。如有过期等原因导致报废,这个功能最有用了。选择商品,输入数量,按Enter键。显示成本,点击提交,显示报废成功!

技术分享


再回到主界面。进入报表功能,这部分略微复杂点,首先看报表界面。包括三大功能:记录、库存、利润。

在未锁定日期区间前,你不能进行不论什么操作。

技术分享


我们选择近期一个月的记录,然后锁定日期,展开左边功能节点——记录:进货记录、销售记录、报废记录。   库存:当前库存(与日期区间无关)。  最后是利润分析(计算销售收入、成本之净利润。 

 比方我们点击销售记录:技术分享


假设在实际中,进货、报废、或者销售录入出错了,我们都能够在这里锁定日期。找到记录然后选中。鼠标右键选择删除记录

技术分享


点击删除记录。提示删除的数据不增加报表计算。确认删除,提示删除成功技术分享


我们再看看当前剩余商品库存,帮助核对商品数量

技术分享


最后是利润分析,这份报表十分重要

技术分享

最后从这份报表来验证我们的操作结果:

1.康师傅红烧牛肉面:销售了5袋。每袋销售价格2.5,进货价格2.0。销售利润2.5,没有报废记录,净利润2.5

2.百事薯片:销售2份。每份销售价格4.75。进货价格3.8。销售利润1.9。当中有一份由于过期导致成本添加3.8。所以净利润亏1.9

........

最后总计销售利润和报废成本,得到净利润


好了,功能部分最终说完了。直接贡献代码部分。不用多做说明了,本人凝视一向清楚:


第二部分:源代码

主界面:

package org.screen;

import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import javax.swing.JToolBar;

public class screen {

	private JFrame frame;
	private JButton button_4;
	private JButton button_5;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {    //同意多次运行
			public void run() {
				try {
					screen window = new screen();  //new一个窗体(全屏)
					window.frame.setVisible(true);  //设置fram可见
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public screen() {
		initialize();  
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("零售业管理系统");
		frame.getContentPane().setFocusTraversalPolicyProvider(true);
		int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width; //依据用户屏幕,自己主动调整屏幕元素位置
		int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;

		frame.setBounds(0, 0, screenWidth, screenHeight); //设置fram的位置和长宽
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //定义close动作
		frame.getContentPane().setLayout(null); 

		JLabel lblNewLabel = new JLabel("零售业管理系统 V1.0"); //设置系统标题
		lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
		lblNewLabel.setForeground(Color.BLUE);
		lblNewLabel.setFont(new Font("仿宋", Font.BOLD | Font.ITALIC, 36));
		lblNewLabel.setBounds((screenWidth-400)/2, (screenHeight-350)/2 - 80, 400, 50);
		frame.getContentPane().add(lblNewLabel);		
		
		JButton newButton = new JButton("进货");   //点击进货按钮。调用进货管理程序界面
		newButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				stock_screen.main(null);
			}
		});
		newButton.setFont(new Font("仿宋", Font.BOLD, 20)); //设置按钮字体,大小,位置
		newButton.setBounds((screenWidth-400)/2, (screenHeight-350)/2, 400, 50);
		frame.getContentPane().add(newButton); //放入fram容器中
		
		JButton button = new JButton("定价");  //设置销售按钮
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				pricing_screen.main(null);
			}
		});
		button.setFont(new Font("仿宋", Font.BOLD, 20));
		button.setBounds((screenWidth-400)/2, (screenHeight-350)/2+60*1, 400, 50);
		frame.getContentPane().add(button);
		
		JButton button_1 = new JButton("销售");  //设置报废按钮
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				sales_screen.main(null);
			}
		});
		button_1.setFont(new Font("仿宋", Font.BOLD, 20));
		button_1.setBounds((screenWidth-400)/2, (screenHeight-350)/2+60*2, 400, 50);
		frame.getContentPane().add(button_1);
		
		JButton button_2 = new JButton("报废");  //设置库存按钮
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				waste_screen.main(null);
			}
		});
		button_2.setFont(new Font("仿宋", Font.BOLD, 20));
		button_2.setBounds((screenWidth-400)/2, (screenHeight-350)/2+60*3, 400, 50);
		frame.getContentPane().add(button_2);
		
		JButton button_3 = new JButton("报表"); //设置利润按钮
		button_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				report_screen.main(null);
			}
		});
		button_3.setFont(new Font("仿宋", Font.BOLD, 20));
		button_3.setBounds((screenWidth-400)/2, (screenHeight-350)/2+60*4, 400, 50);
		frame.getContentPane().add(button_3);
		
		JButton btnNewButton = new JButton("其它");
		btnNewButton.setFont(new Font("仿宋", Font.BOLD, 20));
		btnNewButton.setFocusPainted(false);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
		        JOptionPane.showMessageDialog(null, "功能暂未开放!

"); } }); btnNewButton.setBounds((screenWidth-400)/2, (screenHeight-350)/2+60*5, 400, 50); frame.getContentPane().add(btnNewButton); //toolbar上添加两个按钮选项 数据管理和关于 button_4 = new JButton("数据管理"); button_4.addActionListener(new ActionListener() { //点击按钮事件 public void actionPerformed(ActionEvent e) { JPopupMenu popupMenu = new JPopupMenu();//载入popupMenu选项 JMenu menu = new JMenu("清空");//清理旧数据。优化数据库 JMenuItem item_1 = new JMenuItem("1年前数据"); JMenuItem item_2 = new JMenuItem("2年前数据"); JMenuItem item_3 = new JMenuItem("3年前数据"); JMenuItem item_4 = new JMenuItem("4年前数据"); JMenuItem item_5 = new JMenuItem("5年前数据"); menu.add(item_1); menu.add(item_2); menu.add(item_3); menu.add(item_4); menu.add(item_5); popupMenu.add(menu); popupMenu.show(button_4, 0, button_4.getY() + button_4.getHeight()); //选择toolbar里item事件。运行旧数据清理 item_1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GregorianCalendar gc=new GregorianCalendar(); //当前日期的前一年 gc.setTime(new Date()); gc.add(1, -1); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置指定格式的当前日期时间 String date = df.format(gc.getTime()); new OperationSqlData().DeleteSqlDataByYear(date); } }); item_2.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GregorianCalendar gc=new GregorianCalendar(); //当前日期的前一年 gc.setTime(new Date()); gc.add(1, -2); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置指定格式的当前日期时间 String date = df.format(gc.getTime()); new OperationSqlData().DeleteSqlDataByYear(date); } }); item_3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GregorianCalendar gc=new GregorianCalendar(); //当前日期的前一年 gc.setTime(new Date()); gc.add(1, -3); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置指定格式的当前日期时间 String date = df.format(gc.getTime()); new OperationSqlData().DeleteSqlDataByYear(date); } }); item_4.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GregorianCalendar gc=new GregorianCalendar(); //当前日期的前两年 gc.setTime(new Date()); gc.add(1, -4); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置指定格式的当前日期时间 String date = df.format(gc.getTime()); new OperationSqlData().DeleteSqlDataByYear(date); } }); item_5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { GregorianCalendar gc=new GregorianCalendar(); //当前日期的前一年 gc.setTime(new Date()); gc.add(1, -5); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置指定格式的当前日期时间 String date = df.format(gc.getTime()); new OperationSqlData().DeleteSqlDataByYear(date); } }); } }); button_4.setBorder(null); button_4.setFont(new Font("仿宋", Font.PLAIN, 14)); JToolBar toolBar = new JToolBar(); toolBar.setToolTipText("配置"); toolBar.setRollover(true); toolBar.add(button_4); toolBar.setBounds(0, 0, screenWidth, 25); frame.getContentPane().add(toolBar); //分隔功能栏 toolBar.addSeparator(); //添加开发相关信息 button_5 = new JButton("关于"); button_5.setBorder(null); button_5.setFont(new Font("仿宋", Font.PLAIN, 14)); toolBar.add(button_5); frame.getContentPane().add(toolBar); button_5.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { about_screen.main(null); } }); } }


主界面——关于:

package org.screen;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextPane;

public class about_screen {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					about_screen window = new about_screen();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public about_screen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(50, 80, 400, 200);
		JTextPane textPane = new JTextPane();
		textPane.setBounds(00, 00, 400, 200);
		frame.getContentPane().add(textPane);
		textPane.setText("此管理软件。仅为个人学习Java语言作品之中的一个。源代码所有开放,如有疑问联系QQ,初学Java不足之处还请指正。相互学习!

" +"\r"+"\r"+ "版本号 V1.0"+"\r"+"2016/03/25"+"\r"+"CSDN:居士爱吃泡面"+"\r"+"QQ:461356592"); textPane.setEditable(false); } }


进货管理:

package org.screen;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;

public class stock_screen {
	private JFrame frame;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_2;
	private JTextField textField_3;
	private JButton btnNewButton;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					stock_screen window = new stock_screen();  //创建进货窗体界面
					window.frame.setVisible(true);  //设置窗体可见
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public stock_screen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("进货管理");  //new一个Jfram容器
		int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width/2;;  //依据用户屏幕。自己主动调整控件的显示位置
		int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height/2;;
		
		frame.setBounds(screenWidth/2, screenHeight/2, screenWidth, screenHeight);
		frame.getContentPane().setLayout(null);	
		
		JLabel lblNewLabel = new JLabel("品名");  //设置label控件属性,位置
		lblNewLabel.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel.setBounds((screenWidth-180)/2, (screenHeight-180)/2, 50, 20);
		frame.getContentPane().add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("数量");  //设置label控件属性,位置
		lblNewLabel_1.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_1.setBounds((screenWidth-180)/2, (screenHeight-180)/2+30*1, 50, 20);
		frame.getContentPane().add(lblNewLabel_1);
		
		JLabel lblNewLabel_2 = new JLabel("单位");  //设置label控件属性,位置
		lblNewLabel_2.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_2.setBounds((screenWidth-180)/2, (screenHeight-180)/2+30*2, 50, 20);
		frame.getContentPane().add(lblNewLabel_2);
		
		JLabel lblNewLabel_3 = new JLabel("总价");  //设置label控件属性。位置
		lblNewLabel_3.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_3.setBounds((screenWidth-180)/2, (screenHeight-180)/2+30*3, 50, 20);
		frame.getContentPane().add(lblNewLabel_3);
		
		textField = new JTextField();  //设置输入Field控件属性,位置
		textField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				textField_2.setText(new OperationSqlData().getUnitByGoodsName(textField.getText()));
			}
		});
		textField.setBounds((screenWidth-180)/2+60, (screenHeight-180)/2, 180, 20);
		frame.getContentPane().add(textField);
		textField.setColumns(10);
		
		textField_1 = new JTextField(); //设置输入Field控件属性。位置
		textField_1.setBounds((screenWidth-180)/2+60, (screenHeight-180)/2+30*1, 120, 20);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);
		
		textField_2 = new JTextField(); //设置输入ComboBox控件属性,位置 ,默认下拉框两个选项
		textField_2.setBounds((screenWidth-180)/2+60, (screenHeight-180)/2+30*2, 120, 20);
		frame.getContentPane().add(textField_2);
		textField_2.setText(new OperationSqlData().getUnitByGoodsName(textField.getText()));
		
		textField_3 = new JTextField();  //设置输入Field控件属性,位置
		textField_3.setBounds((screenWidth-180)/2+60, (screenHeight-180)/2+30*3, 120, 20);
		frame.getContentPane().add(textField_3);
		textField_3.setColumns(10);
		
		btnNewButton = new JButton("提交");
		btnNewButton.setMnemonic(KeyEvent.VK_ENTER);
		btnNewButton.setFont(new Font("仿宋", Font.BOLD, 16));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField.getText().isEmpty()||textField_1.getText().isEmpty()||textField_3.getText().isEmpty()||textField_2.getText().isEmpty()) //检查商品名字段是否为空
				{
				   JOptionPane.showMessageDialog(null, "输入栏位不能为空!

"); return; } int ret = new OperationSqlData().StockIn(textField.getText(), textField_1.getText(), (String) textField_2.getText(), textField_3.getText()); if (ret == 1) //依据SQL返回值推断运行结果,并显示对话框 { JOptionPane.showMessageDialog(null, "存储成功"); textField.setText(null); textField_1.setText(null); textField_2.setText(null);; textField_3.setText(null); } else { JOptionPane.showMessageDialog(null, "存储失败!

"); } } }); btnNewButton.setBounds((screenWidth-180)/2+60, (screenHeight-180)/2+30*3+40, 120, 20); frame.getContentPane().add(btnNewButton); } }


定价界面

package org.screen;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.JSpinner;

public class pricing_screen {

	private JFrame frame;
	private JTable table;
	private DefaultTableModel model;
	private JTextField textField;
	private JTextField textField_1;
	private JSpinner spinner;
	private JSpinner spinner_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					pricing_screen window = new pricing_screen();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public pricing_screen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	@SuppressWarnings("serial")
	private void initialize() {
		frame = new JFrame("销售定价");
		int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width*2/3;
		int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height*2/3;	
		frame.setBounds(screenWidth/6, screenHeight/6, screenWidth, screenHeight);
		frame.getContentPane().setLayout(null);

		// 依据model创建一个Jtable
		String[] header = { "品名","总价值","库存数量","单位","进货单位价格","销售单位价格" };// 设置表头
		Object[][] item = new Object[0][6];// 设置单身
		model = new DefaultTableModel(item, header) {
			public boolean isCellEditable(int row, int column) {
				if (column == 5)
					return true;
				else
					return false;
			}
		};// 创建一个model,并设置model数据不可编辑
		table = new JTable(model);// 依据model创建一个Jtable
		table.setFocusable(false);// 关闭鼠标选中单个坐标

		JScrollPane scrollPane = new JScrollPane(table);
		scrollPane.setBounds((screenWidth-780)/2+170, (screenHeight-440)/2-20, 600, 400);
		frame.getContentPane().add(scrollPane);		

		JLabel label_4 = new JLabel("起始日期");
		label_4.setFont(new Font("仿宋", Font.BOLD, 14));
		label_4.setBounds((screenWidth-780)/2, (screenHeight-440)/2-20, 60, 20);
		frame.getContentPane().add(label_4);

		JLabel label_5 = new JLabel("结束日期");
		label_5.setFont(new Font("仿宋", Font.BOLD, 14));
		label_5.setBounds((screenWidth-780)/2, (screenHeight-440)/2-20+30, 60, 20);
		frame.getContentPane().add(label_5);

		//定义两个spinner用于日期的调整
		GregorianCalendar gc=new GregorianCalendar(); //当前日期的前一个月
		gc.setTime(new Date());
		gc.add(2, -1);		
		SpinnerModel dateModel=null;
		dateModel = new SpinnerDateModel(gc.getTime(), null, null,Calendar.DAY_OF_MONTH);
		spinner = new JSpinner();
		spinner.setBounds((screenWidth-780)/2+65, (screenHeight-440)/2-20, 90, 20);
		frame.getContentPane().add(spinner);
		spinner.setModel(dateModel);  
		spinner.setEditor(new JSpinner.DateEditor(spinner,"yyyy-MM-dd"));

		SpinnerModel dateModel_1=null;
		dateModel_1 = new SpinnerDateModel(new Date(), null, null,Calendar.DAY_OF_MONTH);		
		spinner_1 = new JSpinner();
		spinner_1.setBounds((screenWidth-780)/2+65, (screenHeight-440)/2-20+30, 90, 20);
		frame.getContentPane().add(spinner_1);
		spinner_1.setModel(dateModel_1); 
		spinner_1.setEditor(new JSpinner.DateEditor(spinner_1,"yyyy-MM-dd"));			
		
		JButton button_1 = new JButton("查找");
		button_1.setFont(new Font("仿宋", Font.BOLD, 16));
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//点击查找按钮,依据起止日期,查询库存信息
				int r = model.getRowCount();
				while(r>0)
				{
					model.removeRow(r-1);
					r--;
				}

				Object[] obj = new Object[4];
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 创建指定格式的当前时间
				ArrayList<Object[]> list = new OperationSqlData().getStockRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59",1 , true);
				int row = list.size();
				float cost = 0;
				//显示到table
				for(int i=0; i<row; i++)
				{
					obj = list.get(i);
					model.addRow(new Object[5]);
					int j = model.getRowCount();
					model.setValueAt(obj[0], j-1, 0);
					model.setValueAt(obj[3], j-1, 1);
					model.setValueAt(obj[1], j-1, 2);
					model.setValueAt(obj[2], j-1, 3);
					cost = Float.parseFloat(obj[3].toString())/Float.parseFloat(obj[1].toString());
					cost =  (float)(Math.round(cost*100))/100;
					model.setValueAt(cost, j-1, 4);
				}
			}
		});
		button_1.setBounds((screenWidth-780)/2+30, (screenHeight-440)/2-20+70, 90, 20);
		frame.getContentPane().add(button_1);		
	   
		//定义两种加价方式按比例和固定值。基于日期区间库存成本定义销售价格
		JLabel lblNewLabel = new JLabel("统一按比例加价");
		lblNewLabel.setFont(new Font("仿宋", Font.BOLD, 14));
		lblNewLabel.setBounds((screenWidth-780)/2-20, (screenHeight-440)/2-20+190, 110, 20);
		frame.getContentPane().add(lblNewLabel);

		JLabel label_1 = new JLabel("%");
		label_1.setBounds((screenWidth-780)/2+150, (screenHeight-440)/2-20+190, 20, 20);
		frame.getContentPane().add(label_1);

		JLabel label_2 = new JLabel("统一按固定值加价");
		label_2.setFont(new Font("仿宋", Font.BOLD, 14));
		label_2.setBounds((screenWidth-780)/2-20, (screenHeight-440)/2-20+220, 120, 20);
		frame.getContentPane().add(label_2);

		JLabel label_3 = new JLabel("¥");
		label_3.setBounds((screenWidth-780)/2+150, (screenHeight-440)/2-20+220, 20, 20);
		frame.getContentPane().add(label_3);		

		textField = new JTextField();
		textField.setBounds((screenWidth-780)/2+105, (screenHeight-440)/2-20+190, 40, 20);
		frame.getContentPane().add(textField);
		textField.setColumns(10);		

		textField_1 = new JTextField();
		textField_1.setBounds((screenWidth-780)/2+105, (screenHeight-440)/2-20+220, 40, 20);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);

		JButton btnNewButton = new JButton("确定");
		btnNewButton.setFont(new Font("仿宋", Font.BOLD, 16));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//两种加价方式选其一
				if (!textField.getText().isEmpty() && !textField_1.getText().isEmpty())
				{
					JOptionPane.showMessageDialog(null, "加价方式(按比例/按固定值)二选一");
				    return;
				}
				
				else if(!textField.getText().isEmpty())
				{
					int row = 0;
					row = model.getRowCount();
                    for(int i=0; i<row; i++)
                    {
                    	//计算销售价格:成本*比例 保留两位小数的还有一种方法
                    	float sales = Float.parseFloat(model.getValueAt(i, 4).toString())*(1+Float.parseFloat(textField.getText())/100);
                    	sales =  (float)(Math.round(sales*100))/100;
                    	model.setValueAt(sales, i, 5);
                    }
                         
				}
				
				else if(!textField_1.getText().isEmpty())
				{
                    int row;
                    row = model.getRowCount();
					for(int i=0; i<row; i++)
                    {
						//计算销售价格:成本+定值
                    	float sales = Float.parseFloat(model.getValueAt(i, 4).toString())+Float.parseFloat(textField_1.getText());
                    	sales =  (float)(Math.round(sales*100))/100;
                    	model.setValueAt(sales, i, 5);
                    }					
				}
				      
			}
		});
		btnNewButton.setBounds((screenWidth-780)/2+30, (screenHeight-440)/2-20+260, 90, 20);
		frame.getContentPane().add(btnNewButton);	

		JButton button = new JButton("提交");
		button.setFont(new Font("仿宋", Font.BOLD, 16));
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				new OperationSqlData().CommitSalesStockPricingToSql(model, table);
			}
		});
		button.setBounds((screenWidth-780)/2+400, (screenHeight-440)/2+400, 90, 20);
		frame.getContentPane().add(button);
	}
}

销售管理界面:

package org.screen;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.event.KeyEvent;

public class sales_screen {

	// 定义SWT控件
	private JFrame frame;
	private JTextField textField;
	private JTextField textField_1;
	private JTextField textField_3;
	private JComboBox<String> comboBox;
	private JTable table_1;
	private DefaultTableModel model;
	private int m = 0;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					sales_screen window = new sales_screen(); // 新建销售窗体
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public sales_screen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	@SuppressWarnings("serial")
	private void initialize() {
		frame = new JFrame("销售管理"); // new一个fram容器
		// 自己主动设置销售管理窗体大小为用户屏幕的一半,切位于屏幕中央
		int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width*2/3;
		int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height*2/3;
		frame.setBounds(screenWidth/6, screenHeight/6, screenWidth, screenHeight);
		frame.getContentPane().setLayout(null);

		JLabel lblNewLabel = new JLabel("品名");// 设置品名label属性
		lblNewLabel.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel.setBounds((screenWidth - 880) / 2, (screenHeight - 400) / 2+100, 50, 20);
		frame.getContentPane().add(lblNewLabel);

		JLabel lblNewLabel_1 = new JLabel("数量");// 设置单位价格label属性
		lblNewLabel_1.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_1.setBounds((screenWidth - 880) / 2, (screenHeight - 400) / 2+140 , 50, 20);
		frame.getContentPane().add(lblNewLabel_1);

		JLabel lblNewLabel_2 = new JLabel("单位价格");// 设置数量label属性
		lblNewLabel_2.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_2.setBounds((screenWidth - 880) / 2, (screenHeight - 400) / 2+180 , 50, 20);
		frame.getContentPane().add(lblNewLabel_2);
		
		textField_3 = new JTextField();
		textField_3.setHorizontalAlignment(SwingConstants.CENTER);
		textField_3.setEditable(false);
		textField_3.setBounds((screenWidth - 880) / 2 + 170, (screenHeight - 400) / 2 + 140, 60, 20);;
		frame.getContentPane().add(textField_3);
		textField_3.setColumns(10);		

		comboBox = new JComboBox<String>();// 设置combox品名输入属性
		new OperationSqlData().getGoodsNameToCombox(comboBox);
		comboBox.setBounds((screenWidth - 880) / 2 + 55, (screenHeight - 400) / 2 + 100, 180, 20);
		frame.getContentPane().add(comboBox);
		comboBox.setSelectedItem(null);
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String unit = new OperationSqlData().getUnitByGoodsName(comboBox.getSelectedItem().toString());
				String sales_price = new OperationSqlData().getSalesPriceByGoodsName(comboBox.getSelectedItem().toString());	
				textField.setText(sales_price);
				textField_3.setText(unit);
				textField_1.setText(null);
			}
		});

		textField_1 = new JTextField();
		textField_1.setBounds((screenWidth - 880) / 2 + 55, (screenHeight - 400) / 2 + 140, 110, 20);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);

		textField = new JTextField();// 设置(数量)Field输入属性
		textField.setBounds((screenWidth - 880) / 2 + 55, (screenHeight - 400) / 2 + 180, 110, 20);
		frame.getContentPane().add(textField);
		textField.setColumns(10);

		JButton btnNewButton_2 = new JButton(">>");// 设置>>button属性及事件处理
		btnNewButton_2.setFont(new Font("仿宋", Font.BOLD, 16));
		btnNewButton_2.setBounds((screenWidth - 880) / 2 + 55, (screenHeight - 400) / 2 + 220, 60, 20);
		frame.getContentPane().add(btnNewButton_2);
		btnNewButton_2.addActionListener(new ActionListener() {
			// 将用户输入的数据。写入Jtable中,计算总金额
			public void actionPerformed(ActionEvent arg0) {
				m = model.getRowCount();
				for(int q=0; q<m; q++)
				{
					if(model.getValueAt(q, 0).toString().equals(comboBox.getSelectedItem().toString()))
					{
						JOptionPane.showMessageDialog(null, "反复增加购物车!

"); return; } } if (comboBox.getSelectedItem().toString().isEmpty()||textField.getText().isEmpty()||textField_1.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "输入栏位不能为空!"); return; } model.addRow(new Object[4]); model.setValueAt(comboBox.getSelectedItem(), m, 0); model.setValueAt(textField_1.getText(), m, 1); model.setValueAt(textField_3.getText(), m, 2); model.setValueAt(textField.getText(), m, 3); model.setValueAt((float)(Math.round(Float.parseFloat(textField.getText()) * Float.parseFloat(textField_1.getText())*100))/100, m, 4); } }); JButton btnNewButton = new JButton("提交");// 设置提交button属性及事件处理 btnNewButton.setFont(new Font("仿宋", Font.BOLD, 16)); btnNewButton.setMnemonic(KeyEvent.VK_ENTER); btnNewButton.setBounds((screenWidth - 880) / 2 + 450, (screenHeight - 400) / 2 + 390, 80, 20); frame.getContentPane().add(btnNewButton); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new OperationSqlData().CommitSalesToSql(model, table_1); int j = model.getRowCount(); while(j>0) { model.removeRow(j-1); j--; } } }); JButton btnNewButton_1 = new JButton("删除");// 设置删除button属性及事件处理 btnNewButton_1.setFont(new Font("仿宋", Font.BOLD, 16)); btnNewButton_1.setBounds((screenWidth - 880) / 2 + 580, (screenHeight - 400) / 2 + 390, 80, 20); frame.getContentPane().add(btnNewButton_1); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = table_1.getSelectedRow(); if (row >= 0) { model.removeRow(row); } } }); // 根据model创建一个Jtable String[] header = { "品名", "数量", "单位", "单位价格", "总价" };// 设置表头 Object[][] item = new Object[0][5];// 设置单身 model = new DefaultTableModel(item, header) { public boolean isCellEditable(int row, int column) { return false; } };// 创建一个model,并设置model数据不可编辑 table_1 = new JTable(model);// 根据model创建一个Jtable table_1.setFocusable(false);// 关闭鼠标选中单个坐标 JScrollPane scrollPane = new JScrollPane(table_1);// 设置JScrollPane容器属性,将Jtable放入JScrollPane中,实现数据超出上下左右滚动栏的功能 scrollPane.setLocation((screenWidth - 880) / 2 + 250, (screenHeight - 440) / 2); scrollPane.setSize(600, 400); frame.getContentPane().add(scrollPane); } }


报废界面:

package org.screen;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import java.awt.Font;
import javax.swing.SwingConstants;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.awt.event.ActionEvent;

public class waste_screen {
	private JFrame frame;
	private JComboBox<String> comboBox;
	private JTextField textField_1;
	private JTextField textField_2;
	private JButton btnNewButton;
	private JTextField textField_3;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					waste_screen window = new waste_screen();  //创建进货窗体界面
					window.frame.setVisible(true);  //设置窗体可见
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public waste_screen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame("商品报废");  //new一个Jfram容器
		int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width/2;  //依据用户屏幕,自己主动调整控件的显示位置
		int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height/2;		
		frame.setBounds(screenWidth/2, screenHeight/2, screenWidth, screenHeight);
		frame.getContentPane().setLayout(null);
		
		JLabel lblNewLabel = new JLabel("品名");  //设置label控件属性。位置
		lblNewLabel.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel.setBounds((screenWidth-180)/2, (screenHeight-140)/2, 50, 20);
		frame.getContentPane().add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("数量");  //设置label控件属性,位置
		lblNewLabel_1.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_1.setBounds((screenWidth-180)/2, (screenHeight-140)/2+40*1, 50, 20);
		frame.getContentPane().add(lblNewLabel_1);
		
		JLabel lblNewLabel_2 = new JLabel("成本");  //设置label控件属性,位置
		lblNewLabel_2.setFont(new Font("仿宋", Font.BOLD, 20));
		lblNewLabel_2.setBounds((screenWidth-180)/2, (screenHeight-140)/2+40*2, 50, 20);
		frame.getContentPane().add(lblNewLabel_2);
		
		comboBox = new JComboBox<String>();  //设置comboBox控件属性,位置
		new OperationSqlData().getGoodsNameToCombox(comboBox);
		comboBox.setSelectedItem(null);
		comboBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//每次选择商品,先清空输入框,再抓取商品单位
				textField_1.setText(null);
				textField_2.setText(null);;
				textField_3.setText(null);				
				String unit = new OperationSqlData().getUnitByGoodsName(comboBox.getSelectedItem().toString());
				textField_3.setText(unit);
			}
		});
		comboBox.setBounds((screenWidth-180)/2+60, (screenHeight-140)/2, 180, 20);
		frame.getContentPane().add(comboBox);
		
		textField_1 = new JTextField(); //设置输入Field控件属性,位置
		textField_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (comboBox.getSelectedIndex() >= 0)
				{
					//抓取报废商品的库存成本
					float price = new OperationSqlData().getStockCostByGoodsName(comboBox.getSelectedItem().toString());
					float t_price = Float.parseFloat(textField_1.getText())*price;
					//保留两位小数
					BigDecimal bd = new BigDecimal(t_price);
					bd = bd.setScale(2, RoundingMode.HALF_UP);
					textField_2.setText(bd.toString());
				}
			}
		});
		textField_1.setBounds((screenWidth-180)/2+60, (screenHeight-140)/2+40*1, 120, 20);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);
		
		textField_2 = new JTextField();
		textField_2.setEditable(false);
		textField_2.setBounds((screenWidth-180)/2+60, (screenHeight-140)/2+40*2, 120, 20);
		frame.getContentPane().add(textField_2);

		textField_3 = new JTextField();
		textField_3.setHorizontalAlignment(SwingConstants.CENTER);
		textField_3.setEditable(false);
		textField_3.setBounds((screenWidth-180)/2+190, (screenHeight-140)/2+40*1, 50, 20);
		frame.getContentPane().add(textField_3);
		textField_3.setColumns(10);		
		
		btnNewButton = new JButton("提交");  //设置提交button属性,位置和提交事件处理
		btnNewButton.setFont(new Font("仿宋", Font.BOLD, 16));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_1.getText().isEmpty()||comboBox.getSelectedIndex()<0) //检查商品名字段是否为空
				{
					   JOptionPane.showMessageDialog(null, "输入栏位不能为空!

"); return; } if (textField_2.getText().isEmpty()) //检查商品名字段是否为空 { JOptionPane.showMessageDialog(null, "先按Enter查看报废成本。"); return; } int ret =new OperationSqlData().StockIn(comboBox.getSelectedItem().toString(), "-"+textField_1.getText(), textField_3.getText(), "-"+textField_2.getText()); if (ret == 1) //依据SQL返回值推断运行结果,并显示对话框 { JOptionPane.showMessageDialog(null, "报废成功!

"); } else { JOptionPane.showMessageDialog(null, "报废失败!"); } } }); btnNewButton.setBounds((screenWidth-180)/2+60, (screenHeight-140)/2+40*3, 120, 20); frame.getContentPane().add(btnNewButton); } }


报表部分:

package org.screen;

import java.awt.EventQueue;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.tree.DefaultTreeModel;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JTable;
import javax.swing.JSpinner;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;

public class report_screen {

	private JFrame frame;
	private JTable table;
	private JTree tree;
	private JScrollPane scrollPane;
	private JScrollPane scrollPane_1;
	private JSpinner spinner;
	private JSpinner spinner_1;	
	private JRadioButton checkBox;
	private String business;
	private DefaultTableModel model1;
	private DefaultTableModel model2;
	private DefaultTableModel model3;
	/**
	 * Launch the application.
	 */


	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					report_screen window = new report_screen();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public report_screen() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	@SuppressWarnings("serial")
	private void initialize() {
		frame = new JFrame();
		int screenWidth = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
		int screenHeight = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;		
		frame.setBounds(0, 0, screenWidth, screenHeight);
		frame.getContentPane().setLayout(null);

		JLabel label = new JLabel("開始日期");
		label.setFont(new Font("仿宋", Font.BOLD, 16));
		label.setBounds(180, 20, 80, 20);
		frame.getContentPane().add(label);		

		JLabel label_1 = new JLabel("结束日期");
		label_1.setFont(new Font("仿宋", Font.BOLD, 16));
		label_1.setBounds(390, 20, 80, 20);
		frame.getContentPane().add(label_1);	

		checkBox = new JRadioButton("锁定日期");
		checkBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				//锁定后日期不可编辑
				if(checkBox.isSelected() == true)
				{
					spinner.setEnabled(false);
					spinner_1.setEnabled(false);
				}
				else{
					spinner.setEnabled(true);
					spinner_1.setEnabled(true);
				}
			}
		});
		checkBox.setFont(new Font("仿宋", Font.PLAIN, 16));
		checkBox.setBounds(600, 20, 100, 20);
		frame.getContentPane().add(checkBox);
		checkBox.setSelected(false);

		GregorianCalendar gc=new GregorianCalendar(); //当前日期的前一个月
		gc.setTime(new Date());
		gc.add(2, -1);		
		SpinnerModel dateModel=null;
		dateModel = new SpinnerDateModel(gc.getTime(), null, null,Calendar.DAY_OF_MONTH);
		spinner = new JSpinner();
		spinner.setFont(new Font("仿宋", Font.BOLD, 14));
		spinner.setBounds(270, 20, 105, 20);
		frame.getContentPane().add(spinner);
		spinner.setModel(dateModel);  
		spinner.setEditor(new JSpinner.DateEditor(spinner,"yyyy-MM-dd"));		

		SpinnerModel dateModel_1=null;
		dateModel_1 = new SpinnerDateModel(new Date(), null, null,Calendar.DAY_OF_MONTH);
		spinner_1 = new JSpinner();
		spinner_1.setFont(new Font("仿宋", Font.BOLD, 14));
		spinner_1.setBounds(480, 20, 105, 20);
		frame.getContentPane().add(spinner_1);
		spinner_1.setModel(dateModel_1);  
		spinner_1.setEditor(new JSpinner.DateEditor(spinner_1,"yyyy-MM-dd"));			

		//new一个树状导航,选择不同的报表种类
		tree = new JTree();
		tree.setShowsRootHandles(true);
		tree.setModel(new DefaultTreeModel(
				new DefaultMutableTreeNode("报表") {
					{
						DefaultMutableTreeNode node_1;
						node_1 = new DefaultMutableTreeNode("记录");
						node_1.add(new DefaultMutableTreeNode("进货记录"));					
						node_1.add(new DefaultMutableTreeNode("销售记录"));
						node_1.add(new DefaultMutableTreeNode("报废记录"));
						add(node_1);
						node_1 = new DefaultMutableTreeNode("库存");
						node_1.add(new DefaultMutableTreeNode("当前库存"));
						add(node_1);
						node_1 = new DefaultMutableTreeNode("利润");
						node_1.add(new DefaultMutableTreeNode("利润统计"));
						add(node_1);
					}
				}
				));
		tree.addTreeSelectionListener(new TreeSelectionListener() {

			@Override
			public void valueChanged(TreeSelectionEvent e) {
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
				if(node == null)
					return;
				if (checkBox.isSelected()==false)  //日期锁定后同意运行报表
				{
					JOptionPane.showMessageDialog(null, "请首先锁定日期");
					return;	
				}

				Object select_node = node.getUserObject();
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 创建指定格式的当前时间

				switch (select_node.toString()) {
				case "进货记录": //依据日期抓取进货记录
					String[] header1 = { "日期", "品名", "进货数量", "单位", "进货单位价格", "进货总价"};// 设置表头
					Object[][] item1 = new Object[0][6];// 设置单身
					model1 = new DefaultTableModel(item1, header1) {
						public boolean isCellEditable(int row, int column) {
							return false;
						}
					};// 创建一个model。并设置model数据不可编辑
					table = new JTable(model1);// 依据model创建一个Jtable
					table.setFocusable(false);// 关闭鼠标选中单个坐标	
					scrollPane_1.setViewportView(table);

					int r1 = model1.getRowCount();
					while(r1>0)
					{
						model1.removeRow(r1-1);
						r1--;
					}

					Object[] obj1 = new Object[6];
					ArrayList<Object[]> list1 = new OperationSqlData().getStockRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59",0 , false);
					int row1 = list1.size();
					float cost = 0;
					for(int i=0; i<row1; i++)
					{
						obj1 = list1.get(i);
						model1.addRow(new Object[6]);
						int j = model1.getRowCount();
						model1.setValueAt(obj1[0], j-1, 0);
						model1.setValueAt(obj1[1], j-1, 1);
						model1.setValueAt(obj1[2], j-1, 2);
						model1.setValueAt(obj1[3], j-1, 3);
						cost = Float.parseFloat(obj1[4].toString())/Float.parseFloat(obj1[2].toString());
						cost = (float)(Math.round(cost*100))/100;
						model1.setValueAt(cost, j-1, 4);
						model1.setValueAt(obj1[4], j-1, 5);
					}	
					business = "stock";
					reportMouseClick();
					break;
				case "销售记录"://依据日期抓取销售记录			
					String[] header2 = { "日期", "品名", "销售数量", "单位", "销售单位价格", "销售总价"};// 设置表头
					Object[][] item2 = new Object[0][6];// 设置单身
					model2 = new DefaultTableModel(item2, header2) {
						public boolean isCellEditable(int row, int column) {
							return false;
						}
					};// 创建一个model,并设置model数据不可编辑
					table = new JTable(model2);// 依据model创建一个Jtable
					table.setFocusable(false);// 关闭鼠标选中单个坐标	
					scrollPane_1.setViewportView(table);

					int r2 = model2.getRowCount();
					while(r2>0)
					{
						model2.removeRow(r2-1);
						r2--;
					}

					Object[] obj2 = new Object[6];
					ArrayList<Object[]> list2 = new OperationSqlData().getSalesRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59", false);
					int row2 = list2.size();
					for(int i=0; i<row2; i++)
					{
						obj2 = list2.get(i);
						model2.addRow(new Object[6]);
						int j = model2.getRowCount();
						model2.setValueAt(obj2[0], j-1, 0);
						model2.setValueAt(obj2[1], j-1, 1);
						model2.setValueAt(obj2[2], j-1, 2);
						model2.setValueAt(obj2[3], j-1, 3);
						model2.setValueAt(obj2[4], j-1, 4);
						model2.setValueAt(obj2[5], j-1, 5);
					}
					business = "sales";
					reportMouseClick();
					break;
				case "报废记录": //依据日期抓取报废记录
					String[] header3 = { "日期", "品名", "报废数量", "单位", "成本单位价格", "报废总成本"};// 设置表头
					Object[][] item3 = new Object[0][6];// 设置单身
					model3 = new DefaultTableModel(item3, header3) {
						public boolean isCellEditable(int row, int column) {
							return false;
						}
					};// 创建一个model,并设置model数据不可编辑
					table = new JTable(model3);// 依据model创建一个Jtable
					table.setFocusable(false);// 关闭鼠标选中单个坐标	
					scrollPane_1.setViewportView(table);

					int r3 = model3.getRowCount();
					while(r3>0)
					{
						model3.removeRow(r3-1);
						r3--;
					}

					Object[] obj3 = new Object[6];
					ArrayList<Object[]> list3 = new OperationSqlData().getStockRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59",-1 , false);
					int row3 = list3.size();
					float cost1 = 0;
					for(int i=0; i<row3; i++)
					{
						obj3 = list3.get(i);
						model3.addRow(new Object[6]);
						int j = model3.getRowCount();
						model3.setValueAt(obj3[0], j-1, 0);
						model3.setValueAt(obj3[1], j-1, 1);
						model3.setValueAt(obj3[2], j-1, 2);
						model3.setValueAt(obj3[3], j-1, 3);
						cost1 = Float.parseFloat(obj3[4].toString())/Float.parseFloat(obj3[2].toString());
						model3.setValueAt(cost1, j-1, 4);
						model3.setValueAt(obj3[4], j-1, 5);
					}
					business = "stock_waste";
					reportMouseClick();
					break;
				case "当前库存":  //依据日期抓取进货报废和销售记录,计算当前库存
					String[] header4 = {"品名", "库存数量", "单位"};// 设置表头
					Object[][] item4 = new Object[0][3];// 设置单身
					DefaultTableModel model4 = new DefaultTableModel(item4, header4) {
						public boolean isCellEditable(int row, int column) {
							return false;
						}
					};// 创建一个model,并设置model数据不可编辑
					table = new JTable(model4);// 依据model创建一个Jtable
					table.setFocusable(false);// 关闭鼠标选中单个坐标	
					scrollPane_1.setViewportView(table);

					int r4 = model4.getRowCount();
					while(r4>0)
					{
						model4.removeRow(r4-1);
						r4--;
					}

					Object[] obj4 = new Object[6];
					Object[] obj4_sales = new Object[4];
					ArrayList<Object[]> list4 = new OperationSqlData().getStockRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59",0 , true);
					ArrayList<Object[]> list4_sales = new OperationSqlData().getSalesRecordByDate("0000-00-00 00:00:00", "9999-99-99 99:99:99", true);
					int row4 = list4.size();
					int row4_sales = list4_sales.size();
					float stock_last = 0;
					for(int i=0; i<row4; i++)
					{
						model4.addRow(new Object[3]);
						int j = model4.getRowCount();
						obj4 = list4.get(i);

						for (int k=0; k<row4_sales; k++)
						{
							obj4_sales = list4_sales.get(k);
							if (obj4_sales[0].toString().equals(obj4[0].toString()))
							{
								stock_last = Float.parseFloat(obj4[1].toString()) - Float.parseFloat(obj4_sales[1].toString());
								model4.setValueAt(stock_last, j-1, 1);
								break;
							}
							else 
							{
								model4.setValueAt(obj4[1], j-1, 1);
							}	
						}

						if (row4_sales == 0)
							model4.setValueAt(obj4[1], j-1, 1);
						model4.setValueAt(obj4[0], j-1, 0);
						model4.setValueAt(obj4[2], j-1, 2);
					}						

					break;
				case "利润统计": //依据销售利润 报废成本 统计终于净利润
					String[] header5 = { "品名", "销售数量","报废数量","单位", "平均销售单位价格", "库存成本单位价格", "销售利润", "报废成本","净利润"};// 设置表头
					Object[][] item5 = new Object[0][9];// 设置单身
					DefaultTableModel model5 = new DefaultTableModel(item5, header5) {
						public boolean isCellEditable(int row, int column) {
							return false;
						}
					};// 创建一个model,并设置model数据不可编辑
					table = new JTable(model5);// 依据model创建一个Jtable
					table.setFocusable(false);// 关闭鼠标选中单个坐标	
					scrollPane_1.setViewportView(table);	
					int r5 = model5.getRowCount();
					while(r5>0)
					{
						model5.removeRow(r5-1);
						r5--;
					}

					Object[] obj5_sales = new Object[4];
					Object[] obj5_waste = new Object[9];
					Object[] obj5 = new Object[9];
					ArrayList<Object[]> list5_sales = new OperationSqlData().getSalesRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59", true);
					ArrayList<Object[]> list5_waste = new OperationSqlData().getStockRecordByDate(df.format(spinner.getValue())+" "+"00:00:00", df.format(spinner_1.getValue())+" "+"23:59:59", -1, true);

					int row5_sales = list5_sales.size();
					int row5_waste = list5_waste.size();

					for (int i=0; i<row5_sales; i++)
					{
						obj5_sales = list5_sales.get(i);
						float price = new OperationSqlData().getStockCostByGoodsName(obj5_sales[0].toString());
						price =  (float)(Math.round(price*100))/100;
						obj5[0] = obj5_sales[0];
						obj5[1] = obj5_sales[1];
						obj5[2] = 0.00;
						obj5[3] = obj5_sales[2];
						obj5[4] =  (float)(Math.round((Float.parseFloat(obj5_sales[3].toString())/Float.parseFloat(obj5_sales[1].toString()))*100))/100;				
						obj5[5] = price;
						obj5[6] = new BigDecimal(Float.parseFloat(obj5[1].toString())*(Float.parseFloat(obj5[4].toString())-price)).setScale(2, RoundingMode.HALF_UP);
						obj5[7] = 0.00;
						obj5[8] = obj5[6];
						for (int j=0; j<row5_waste; j++)
						{
							obj5_waste = list5_waste.get(j);
							if (obj5_waste[0].equals(obj5_sales[0]))
							{
								obj5[2] = obj5_waste[1];
								obj5[7] = obj5_waste[3];
								obj5[8] =  new BigDecimal(Float.parseFloat(obj5[6].toString()) + Float.parseFloat(obj5[7].toString())).setScale(2, RoundingMode.HALF_UP);
								list5_waste.remove(j);
								row5_waste =  row5_waste - 1;
								break;
							}
						}	

						model5.addRow(new Object[9]);
						int m = model5.getRowCount();
						model5.setValueAt(obj5[0], m-1, 0);
						model5.setValueAt(obj5[1], m-1, 1);
						model5.setValueAt(obj5[2], m-1, 2);					
						model5.setValueAt(obj5[3], m-1, 3);
						model5.setValueAt(obj5[4], m-1, 4);
						model5.setValueAt(obj5[5], m-1, 5);	
						model5.setValueAt(obj5[6], m-1, 6);					
						model5.setValueAt(obj5[7], m-1, 7);
						model5.setValueAt(obj5[8], m-1, 8);							
					}

					if (row5_waste > 0)
					{
						for(int k=0; k<row5_waste; k++)
						{
							obj5_waste = list5_waste.get(k);	
							obj5[0] = obj5_waste[0];
							obj5[1] = 0.00;
							obj5[2] = obj5_waste[1];
							obj5[3] = obj5_waste[2];
							obj5[4] = 0.00;
							float price = new OperationSqlData().getStockCostByGoodsName(obj5_waste[0].toString());
							price = (float)(Math.round(price*100))/100;
							obj5[5] = price;
							obj5[6] = 0.0;
							obj5[7] = obj5_waste[3];
							obj5[8] = Float.parseFloat(obj5_waste[3].toString());

							model5.addRow(new Object[9]);
							int m = model5.getRowCount();
							model5.setValueAt(obj5[0], m-1, 0);
							model5.setValueAt(obj5[1], m-1, 1);
							model5.setValueAt(obj5[2], m-1, 2);					
							model5.setValueAt(obj5[3], m-1, 3);
							model5.setValueAt(obj5[4], m-1, 4);
							model5.setValueAt(obj5[5], m-1, 5);	
							model5.setValueAt(obj5[6], m-1, 6);					
							model5.setValueAt(obj5[7], m-1, 7);
							model5.setValueAt(obj5[8], m-1, 8);					
						}
					}
					//最后一行插入利润总计
					int row_last = model5.getRowCount();
					float sales_bft = 0;
					float stock_cost = 0;
					float last_bft = 0;
					for(int p=0; p<row_last; p++)
					{
						if (!(model5.getValueAt(p, 6)==null))
						{
							sales_bft =  sales_bft + Float.parseFloat(model5.getValueAt(p, 6).toString());
						}
						if (!(model5.getValueAt(p, 7)==null))
						{
							stock_cost = stock_cost + Float.parseFloat(model5.getValueAt(p, 7).toString());
						}
						if (!(model5.getValueAt(p, 8)==null))
						{
							last_bft = last_bft + Float.parseFloat(model5.getValueAt(p, 8).toString());
						}
					}
					sales_bft = (float)(Math.round(sales_bft*100))/100;
					stock_cost = (float)(Math.round(stock_cost*100))/100;
					last_bft = (float)(Math.round(last_bft*100))/100;


					model5.addRow(new Object[9]);
					model5.setValueAt("总计", row_last, 0);
					model5.setValueAt(sales_bft, row_last, 6);
					model5.setValueAt(stock_cost, row_last, 7);
					model5.setValueAt(last_bft, row_last, 8);
					break;					
				default:
					break;
				}
			}
		});

		scrollPane = new JScrollPane();
		scrollPane.setViewportView(tree);
		scrollPane.setBounds(10, 10, 160, screenHeight-10);
		frame.getContentPane().add(scrollPane);		

		scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(180, 50, screenWidth-200, screenHeight-50);
		frame.getContentPane().add(scrollPane_1);
	}

	class PopupActionListener implements ActionListener {
		public void actionPerformed(ActionEvent event) {
			int answer = JOptionPane.showConfirmDialog(null,  "删除数据不增加报表计算,确定要删除选中记录?", "提交信息",JOptionPane.YES_NO_OPTION);
			if (answer == 0)
			{
				int ret = 0;
				if (business.equals("stock"))
				{
					ret = new OperationSqlData().DeleteSqlDataByGoodsNameDate(model1.getValueAt(table.getSelectedRow(), 1).toString(), model1.getValueAt(table.getSelectedRow(), 0).toString(), "stock");
					model1.removeRow(table.getSelectedRow());
				}
				else if(business.equals("sales"))
				{
					ret = new OperationSqlData().DeleteSqlDataByGoodsNameDate(model2.getValueAt(table.getSelectedRow(), 1).toString(), model2.getValueAt(table.getSelectedRow(), 0).toString(), "sales");
					model2.removeRow(table.getSelectedRow());				
				}
				else if (business.equals("stock_waste"))
				{
					ret = new OperationSqlData().DeleteSqlDataByGoodsNameDate(model3.getValueAt(table.getSelectedRow(), 1).toString(), model3.getValueAt(table.getSelectedRow(), 0).toString(), "stock");	
					model3.removeRow(table.getSelectedRow());
				}

				if (ret == 1)
					JOptionPane.showMessageDialog(null, "删除成功");
				else
					JOptionPane.showMessageDialog(null, "删除失败"); 
			}
		}
	}	

	ActionListener acitonListener = new PopupActionListener();   


	public void reportMouseClick()  //右键提供指定行区域删除选项。处理选项事件
	{
		final JPopupMenu jp = new JPopupMenu();
		final JMenuItem item = jp.add("删除该条记录");
		item.addActionListener(acitonListener);

		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() == MouseEvent.BUTTON3) {
					// 弹出菜单
					if(table.getSelectedRow() > -1)
					{
						int y = table.getSelectedRow() * table.getRowHeight();
						if(e.getY() > y && e.getY() <= y+16)
						{
							jp.show(table, e.getX(), e.getY());
						}
					}
				}
			}
		});  
	}
}


最后是数据库操作部分:


package org.screen;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class OperationSqlData {
	//定义数据库变量	
	private String  url;
	private String passname;
	private String password;
	private String driver;
	private Statement st;
	private Connection con;
	private ResultSet rst;	

	public OperationSqlData()  //构造数据库链接默认值
	{
		passname = "admin";  //SQL Server登陆账号
		password = "init1234";	//SQL Server登录password
		driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //驱动载入
		try {
			Class.forName(driver);

		} catch (ClassNotFoundException e) {
			JOptionPane.showMessageDialog(null, "数据库载入失败!");
			e.printStackTrace();
		}
		try {
			url = "jdbc:sqlserver://"+InetAddress.getLocalHost().getHostAddress()+";"+"DatabaseName=goodsData";//URL链接
		} catch (UnknownHostException e) {
			JOptionPane.showMessageDialog(null, "数据库载入失败!");
			e.printStackTrace();
		}	
	}

	public OperationSqlData(String p_name, String p_word)  //构造指定帐号密码数据库链接
	{
		passname = p_name; 
		password = p_word;
		driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		try {
			Class.forName(driver);

		} catch (ClassNotFoundException e) {
			JOptionPane.showMessageDialog(null, "数据库载入失败。");
			e.printStackTrace();
		}
		try {
			url = "jdbc:sqlserver://"+InetAddress.getLocalHost().getHostAddress()+";"+"DatabaseName=goodsData";
		} catch (UnknownHostException e) {
			JOptionPane.showMessageDialog(null, "数据库载入失败!");
			e.printStackTrace();
		}		
	}

	public void getGoodsNameToCombox(JComboBox<String> combox)
	{
		String sql = "SELECT distinct goods FROM stock where qty > 0";// 数据库取品名
		// 连接数据库,运行查询语句
		try {
			con = DriverManager.getConnection(url, passname, password);
			con.setAutoCommit(true);
			st = con.createStatement();
			rst = st.executeQuery(sql);
			// 取出的结果增加combox的Item
			while (rst.next()) {
				combox.addItem(rst.getString("goods"));
			}

			// 关闭数据库连接
			rst.close();
			st.close();
			con.close();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "商品名数据载入异常。 ");
			e.printStackTrace();
		}	   
	}

	public String getUnitByGoodsName(String goods) {
		String unit = null;
		//从库存表抓取商品单位
		String sql = "SELECT distinct unit FROM stock WHERE qty> 0 AND goods = ?

"; try { con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(true); PreparedStatement ps = con.prepareStatement(sql); //SQL预处理 ps.setString(1, goods); //SQL參数 ResultSet rt = ps.executeQuery(); //运行SQL while(rt.next()) { unit = rt.getString("unit"); //从运行结果中得到商品单位 } // 关闭数据库连接 ps.close(); rt.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "商品单位数据载入异常!

"); e.printStackTrace(); } return unit; //返回单位 } public String getSalesPriceByGoodsName(String goods) { String sales_price = null; //从定价表中抓取销售单位价格 String sql = "SELECT unitprice FROM Price WHERE goods = ?"; try { con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(true); PreparedStatement ps = con.prepareStatement(sql);// SQL预处理 ps.setString(1, goods); ResultSet rt = ps.executeQuery(); while(rt.next()) { sales_price = rt.getString("unitprice"); } // 关闭数据库连接 ps.close(); rt.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "销售单位价格数据载入异常! "); e.printStackTrace(); } return sales_price; } public ArrayList<Object[]> getSalesRecordByDate(String date_begin, String date_end, Boolean sum_qty_totalprice) { ArrayList<Object[]> list = new ArrayList<Object[]>(); String sql = null; if (sum_qty_totalprice) { sql = "SELECT goods, SUM(qty) AS s_qty, unit, SUM(totalprice) AS s_totalprice FROM sales where date between ?

AND ? GROUP BY goods, unit";//抓取销售记录数据按商品名和单位汇总 } else{ sql = "SELECT date, goods, qty, unit, unitprice, totalprice FROM sales where date between ? AND ? ORDER BY date DESC";//抓取销售记录数据按时间排序 } try { con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(true); PreparedStatement ps = con.prepareStatement(sql);// SQL预处理 ps.setString(1, date_begin); //指定抓取销售记录起始时间 ps.setString(2, date_end); //指定抓取销售记录终止时间 ResultSet rt = ps.executeQuery(); Object[] obj = null; if (sum_qty_totalprice) { while(rt.next()) { obj = new Object[4];//Object数组增加arraylist obj[0] = rt.getString("goods"); obj[1] = rt.getFloat("s_qty"); obj[2] = rt.getString("unit"); obj[3] = rt.getFloat("s_totalprice"); list.add(obj); } } else{ while(rt.next()) { obj = new Object[6]; obj[0] = rt.getString("date"); obj[1] = rt.getString("goods"); obj[2] = rt.getFloat("qty"); obj[3] = rt.getString("unit"); obj[4] = rt.getFloat("unitprice"); obj[5] = rt.getFloat("totalprice"); list.add(obj); } } // 关闭数据库连接 ps.close(); rt.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "销售记录数据载入异常! "); e.printStackTrace(); } return list; } public float getStockCostByGoodsName(String goods) { float stock_cost = 0; // 这里计算的是商品进货成本(qty>0) String sql = "SELECT goods,SUM(qty) AS s_qty,SUM(amount) AS s_amount FROM stock WHERE goods = ? AND qty>0 GROUP by goods"; try { con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(true); PreparedStatement ps = con.prepareStatement(sql);// SQL预处理 ps.setString(1, goods); ResultSet rt = ps.executeQuery(); while(rt.next()) { float s_amount = rt.getFloat("s_amount"); float s_qty = rt.getFloat("s_qty"); stock_cost = s_amount/s_qty; } // 关闭数据库连接 ps.close(); rt.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "成本数据载入异常! "); e.printStackTrace(); } return stock_cost; } public ArrayList<Object[]> getStockRecordByDate(String date_begin, String date_end, int status, Boolean sum_amount_qty) { ArrayList<Object[]> list = new ArrayList<Object[]>(); String sql = null; //sun_amount_qty是否根据商品名和单位加总库存数量和成本, //status的值: -1计算报废库存。0计算总库存; 1计算进货库存 if (sum_amount_qty) { if (status == -1) sql = "SELECT goods, SUM(qty) AS s_qty, unit, SUM(amount) AS s_amount FROM stock where qty < 0 AND date between ?

AND ? GROUP by goods,unit"; else if (status == 1) sql = "SELECT goods, SUM(qty) AS s_qty, unit, SUM(amount) AS s_amount FROM stock where qty > 0 AND date between ? AND ? GROUP by goods,unit"; else if (status == 0) sql = "SELECT goods, SUM(qty) AS s_qty, unit, SUM(amount) AS s_amount FROM stock where date between ? AND ? GROUP by goods,unit"; } else { if(status == -1) sql = "SELECT date, goods, qty, unit, amount FROM stock where qty < 0 AND date between ? AND ? ORDER BY date DESC"; else sql = "SELECT date, goods, qty, unit, amount FROM stock where qty > 0 AND date between ? AND ? ORDER BY date DESC"; } try { con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(true); PreparedStatement ps = con.prepareStatement(sql);// SQL预处理 ps.setString(1, date_begin); ps.setString(2, date_end); ResultSet rt = ps.executeQuery(); Object[] obj = null; if (sum_amount_qty) //根据是否汇总处理输出结果 { while(rt.next()) { obj = new Object[4]; obj[0] = rt.getString("goods"); obj[1] = rt.getFloat("s_qty"); obj[2] = rt.getString("unit"); obj[3] = rt.getFloat("s_amount"); list.add(obj); } } else { while(rt.next()) { obj = new Object[5]; obj[0] = rt.getString("date"); obj[1] = rt.getString("goods"); obj[2] = rt.getFloat("qty"); obj[3] = rt.getString("unit"); obj[4] = rt.getFloat("amount"); list.add(obj); } } // 关闭数据库连接 ps.close(); rt.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "库存数据载入异常! "); e.printStackTrace(); } return list; } public void CommitSalesStockPricingToSql(DefaultTableModel model, JTable table) //传入用model定义的table { //这里先删除原有定价记录,再插入新纪录 String sql1 = "DELETE FROM price WHERE goods = ? "; String sql2 = "INSERT INTO price (goods, unit, cost, unitprice) VALUES(?,?,?,?)"; try { // 设置数据库链接,设置手动提交数据 con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(false); PreparedStatement ps1 = con.prepareStatement(sql1);// SQL预处理 PreparedStatement ps2 = con.prepareStatement(sql2);// SQL预处理 int line = table.getRowCount(); // 循环每一行,假设有值增加数据库批处理 for (int i = 0; i < line; i++) { if(!(model.getValueAt(i, 5)==null)) //首先推断是否有输入值。再推断是否为空值,有值则删除 { if (!(model.getValueAt(i, 5).toString().isEmpty())) { ps1.setString(1, (String) model.getValueAt(i, 0)); ps1.addBatch(); ps2.setString(1, (String) model.getValueAt(i, 0)); ps2.setString(2, (String) model.getValueAt(i, 3)); ps2.setString(3, model.getValueAt(i, 4).toString()); ps2.setString(4, model.getValueAt(i, 5).toString()); ps2.addBatch(); } } } ps1.executeBatch();// 运行批处理。弹出对话消息。显示成功失败 con.commit(); //关闭数据库相关链接 ps1.close(); int[] rt = ps2.executeBatch();// 运行批处理,弹出对话消息,显示成功失败 con.commit(); if (rt.length > 0) JOptionPane.showMessageDialog(null, "提交成功!"); ps2.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "提交失败! "); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } } public Integer StockIn(String name, String qty, String unit, String amount) { int ret = 0; String sql = "INSERT INTO stock (goods, date, qty, unit, amount) VALUES (?

, ?, ?, ?

, ?

)"; // 定义SQL语句 try { con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(true); // 设置数据自己主动提交数据库 PreparedStatement ps = con.prepareStatement(sql); // SQL预处理 ps.setString(1, name);// 动态參数运行SQL SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 创建指定格式的当前时间 ps.setString(2, df.format(new Date())); ps.setString(3, qty); ps.setString(4, unit); ps.setString(5, amount); ret = ps.executeUpdate(); // 运行SQL ps.close(); //关闭数据库链接 con.close(); return ret; } catch (SQLException e) { e.printStackTrace(); return ret; } } public void CommitSalesToSql(DefaultTableModel model, JTable table) { // 插入销售记录到数据库 String sql = "INSERT INTO sales (goods, date, qty, unit, unitprice, totalprice) VALUES (?, ?, ?, ?

, ?

, ?)";// 批量插入Jtable中数据 try { // 设置数据库链接。设置手动提交数据 con = DriverManager.getConnection(url, passname, password); con.setAutoCommit(false); PreparedStatement ps = con.prepareStatement(sql);// SQL预处理 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置指定格式的当前日期时间 String date = df.format(new Date()); float f4 = 0; int line = table.getRowCount(); // 循环每一行。假设有值增加数据库批处理 for (int i = 0; i < line; i++) { if ((String) model.getValueAt(i, 0) != null) { ps.setString(1, (String) model.getValueAt(i, 0)); ps.setString(2, date); float f1 = Float.parseFloat(model.getValueAt(i, 1).toString()); ps.setFloat(3, f1); ps.setString(4, (String)model.getValueAt(i, 2)); float f2 = Float.parseFloat(model.getValueAt(i, 3).toString()); ps.setFloat(5, f2); float f3 = Float.parseFloat(model.getValueAt(i, 4).toString()); ps.setFloat(6, f3); ps.addBatch(); f4 = f3 + f4; } } f4 = (float)(Math.round(f4*100))/100; // 弹出选择对话框,计算总金额,提示是否提交 int answer = JOptionPane.showConfirmDialog(null, "总金额" + f4 + "元" + " " + "确认提交?", "提交信息", JOptionPane.YES_NO_OPTION); if (answer == 0) { int rst[] = ps.executeBatch();// 运行批处理,弹出对话消息。显示成功失败 if (rst.length > 0) { JOptionPane.showMessageDialog(null, "交易成功"); con.commit(); } else if(rst.length == 0) { JOptionPane.showMessageDialog(null, "无数据"); } } //关闭数据库相关链接 ps.close(); con.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "交易失败"); try { con.rollback(); con.close(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } } public Integer DeleteSqlDataByGoodsNameDate(String goods, String date, String business) { String sql = null; int ret = 0; if(business.equals("stock")||business.equals("stock_waste")) sql = "DELETE FROM stock where goods = ?

AND date = ?

"; else if (business.equals("sales")) sql = "DELETE FROM sales where goods = ?

AND date = ?"; // 连接数据库。运行查询语句 try { con = DriverManager.getConnection(url, passname,password); con.setAutoCommit(false); // 设置数据自己主动提交数据库 PreparedStatement ps = con.prepareStatement(sql); // SQL预处理 ps.setString(1, goods); ps.setString(2, date); ret = ps.executeUpdate(); // 运行SQL con.commit(); ps.close(); //关闭数据库链接 con.close(); return ret; } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); return ret; } } public void DeleteSqlDataByYear(String date_last)//清理数据库旧记录 { String sql1 = "DELETE FROM stock where date < ?

"; String sql2 = "DELETE FROM sales where date < ?

"; int answer = JOptionPane.showConfirmDialog(null, "确认要删除"+date_last+"之前的数据? ", "提交信息", JOptionPane.YES_NO_OPTION); if (answer != 0) { return; } // 连接数据库。运行查询语句 try { con = DriverManager.getConnection(url, passname,password); con.setAutoCommit(false); // 设置数据不自己主动提交数据库 PreparedStatement ps1 = con.prepareStatement(sql1); // SQL预处理 ps1.setString(1, date_last); ps1.executeUpdate(); // 运行SQL PreparedStatement ps2 = con.prepareStatement(sql2); // SQL预处理 ps2.setString(1, date_last); ps2.executeUpdate(); // 运行SQL con.commit(); ps1.close(); //关闭数据库链接 ps2.close(); con.close(); JOptionPane.showMessageDialog(null, "清除数据成功!

"); } catch (SQLException e) { try { con.rollback(); //失败回滚 } catch (SQLException e1) { e1.printStackTrace(); } JOptionPane.showMessageDialog(null, "清除数据失败"); e.printStackTrace(); } } }



JAVA学习作品之销售管理系统V1.0