Use el idioma Java para escribir un programa que simule la función de liquidación de compras de un supermercado en línea. Requiere que el programa tenga una interfaz gráfica de usuario después de ejecutarse, que permite a los usuarios ingresar información sobre varios productos comprados, y finalmente dar la lista de compras del usuario y el precio total.
Análisis de requisitos:
1. El administrador agrega productos y sus precios
2. Imprimir información de pedido y código de orden de liquidación al comprar productos por los usuarios:
/ * * Creador: Zhang Junqiang * Tiempo: 2016/5/15 * */paquete sales; import java.awt.*; import java.awt.event.*; import java.util.vector; import javax.swing.*; import java.sql.*; Class Goods {public String [] nombre; Price Public [] Precio; Bienes () {name = new String [100]; precio = nuevo flotador [100]; }} El supermercado de clase pública extiende jframe {public static void main (string [] args) lanza SQLException {mainwinow mainwin = new MainWinow ("Teckout de compras de supermercados en línea"); mainwin.setDefaultCloseOperation (jframe.exit_on_close); Mainwin.setBounds (300, 300, 500, 400); mainwin.setVisible (verdadero); Mainwin.setwin (Mainwin); mainwin.setminwindowlayout (); }} clase Mainwinow extiende jframe {bienes bienes; Usuario privado de JButton; Gerente privado de JButton; Privado Jlabel LoginLabel; Private Managinwindow Magwin; Userwindow privado Userwin; oyente privado lis; Privado Mainwinow Loginwin; Private int Goodsnum; / * * Interfaz de configuración * */ private jlabel setNamelabel; Jlabel privado SetPricelabel; JTEXTFIELD PRIVADO SETNAMETEXT; Private JTextfield setPricetExt; Private JButton InputBut; Textarea privada inputaraea; Privado JButton ReturnBut1; Jbutton privado Cancelbut; / * * Interfaz de usuario * */ private vector <string> buyItem; flotador privado [] buycount; privado int buynum; Privado JComboBox GoodsCombox; Privado JButton ReturnBut2; Jlabel privado Jlabel ChoiceGoodLabel; Privado Jlabel ShowPricelabel; Privado JTextfield ShowPrice; Textura privada ShowChoice; Privado Jlabel Showbuynum; Private JTextfield ShowBuynumText; Privado JButton Submitbuy; Privado JButton DeleteBuybut; Choicelist privado jlist; Privado JButton Countbut; Float privado Sumoney; / *** Importación de base de datos*/ Declaración stmt; Mainwinow (String WinName) lanza SQLException {Super (WinName); Goodsnum = 0; buynum = 0; sumoney = (float) 0; bienes = nuevos bienes (); user = new JButton ("Soy un usuario"); gerente = nuevo JButton ("Soy un administrador"); LoginLabel = new JLabel ("¡Seleccione rol!"); magwin = new ManageWindow ("Establecer producto"); Magwin.setBounds (300, 300, 500, 400); magwin.setDefaultCloseOperation (do_nothing_on_close); userwin = new UserWindow ("Bienvenido a la compra"); userwin.setBounds (300, 300, 500, 400); userwin.setDefaultCloseOperation (do_nothing_on_close); lis = nuevo oyente (); / * * Establecer Inicialización de la interfaz * */ setnamelabel = new JLabel ("Nombre comercial:"); setPricelabel = new JLabel ("Price:"); setNamEtext = new JTextField (5); setPricetext = new JTextField (5); inputBut = new JButton ("Confirmar para agregar"); inputAREA = new TextAREA (); returnBut1 = new JButton ("return"); cancelBut = new JButton ("RetRact Add"); / * * Inicialización de la interfaz de usuario * */ GoodsCombox = new JComboBox (); returnBut2 = new JButton ("return"); ChoiceGoodLabel = new JLabel ("Seleccione el producto:"); showPricelabel = new JLabel ("Price"); showPrice = new JTextfield (5); showChoice = new TextAREA (); showBuynum = new JLabel ("Cantidad de compra:"); showBuynumText = new JTextField (5); SubtBuy = new JButton ("Confirmar compra"); deleteBuyBut = new JButton ("Eliminar orden"); countBut = new JButton ("Liquidación de orden"); choiCelist = new JList (); buyItem = new Vector <String> (); buyCount = new Float [100]; / * * Importación de la base de datos * */ try {class.forname ("com.mysql.jdbc.driver"); } Catch (ClassNotFoundException e) {// TODO Auto Generado Bloque E.PrintStackTrace (); } String url = "jdbc: mysql: // localhost: 3306/dispositivo"; String user = "root"; Cadena contraseña = "ZJQ1314520"; Conexión con = drivermanager.getConnection (url, usuario, contraseña); stmt = con.createStatement (); / * * Exportar de datos de la base de datos * */ importsql (); } public void importsql () lanza SQLException {int i = 1; // TODO Método Generado automático ResultSet Result = stmt.executeQuery ("Seleccione Nombre, precio de Goods_info"); while (result.next ()) {goods.name [i-1] = result.getString (1); Goods.price [i-1] = float.parsefloat (resultado.getString (2)); i ++; } Goodsnum = i-1; } public void setwin (mainwinow w) {loginwin = w; } public void setMinWinDowlayout () {Container logincon = new Container (); logincon.setLayout (new FlowLayout ()); logincon.add (gerente); logincon.add (usuario); gerente.addactionListener (LIS); user.AddactionListener (LIS); this.setLayout (new BorderLayout ()); this.add (LoginLabel, BorderLayout.north); this.add (Logincon, BorderLayout.Center); this.Validate (); / * * Establecer el diseño de la interfaz * */ magwin.setLayout (new FlowLayout ()); magwin.add (setnamelabel); magwin.add (setnametext); magwin.add (setPricelabel); magwin.add (setPricetExt); magwin.add (inputBut); magwin.add (inputaraa); Magwin.add (CancelBut); magwin.add (returnBut1); inputBut.AddactionListener (LIS); returnBut1.AddactionListener (LIS); cancelBut.AddactionListener (LIS); / * * Diseño de la interfaz de usuario * */ userwin.setLayout (new BorderLayout ()); Container Usercon = new Container (); Usercon.setLayout (new FlowLayout ()); Usercon.add (ChoiceGoodLabel); Usercon.add (GoodsCombox); Usercon.add (showPricelabel); Usercon.add (ShowPrice); Usercon.add (showbuynum); Usercon.add (showBuynumText); Usercon.add (SubtBuy); userwin.add (Usercon, BorderLayout.north); //choicelist.setListData(goods.name); userwin.add (ChoicElist, BorderLayout.Center); userwin.add (new JScrollPane (ChoicElist)); Contenedor butcon = nuevo contenedor (); butcon.setLayout (new FlowLayout ()); butcon.add (DeleteBuyBut); butcon.add (countBut); butcon.add (returnBut2); userwin.add (Butcon, BorderLayout.South); GoodsCOMBOX.AdDITEMLISTENER (new itemListener () {@Override public void itemStateChanged (ItemEvent e) {// TODO Método generado automático INT INT I = GoodsCOMBox.getSelectedIndex (); if (i> = 0) showPrice.setText (Goods.Price [i] .Tostring ());}}); returnBut2.AddactionListener (LIS); SubtBuy.AddactionListener (LIS); deletebuybut.addactionListener (lis); countBut.AddactionListener (LIS); } private void addComboxItem () {// TODO Auto Generado Stub for (int i = 0; i <Goodsnum; i ++) {GoodsCombox.additem (Goods.name [i]); }} El oyente de clase implementa ActionListener {@Override public Void ActionPerformed (ActionEvent E) {// TODO Auto Generated Method Stub if (E.GetSource () == Manager) {addGoods (); loginwin.setVisible (falso); magwin.setVisible (verdadero); } if (e.getSource () == user) {loginwin.setVisible (falso); userwin.setVisible (verdadero); GoodsCOMBox.RemoveAllItems (); addComboxItem (); } if (e.getSource () == inputBut) {// string showOut = ""; if (setNeMeText.gettext (). Equals ("") || setPricetExt.gettext (). Equals ("")) {joptionPane.showMessEdialog (magwin, "¡Sin elementos de repuesto!", "ADVERTENCIA", JOptionPane.Plain_Message); } else {goods.name [GoodsNum] = setNeMeText.gettext (); Goods.price [GoodsNum] = float.parsefloat (setPricetExt.gettext ()); Pruebe { / * * escriba en la base de datos * * / stmt.executeUpdate ("inserte en Goods_info (name, precio) valores ('"+goods.name [Goodsnum]+"', '"+(float) goods.price [Goodsnum]+"')"); } Catch (SQLException e1) {// TODO Auto Generado Bloque E1.PrintStackTrace (); } GoodsNum ++; addGoods (); setnametext.settext (""); setPricetExt.setText (""); // showout = "Nombre comercial:"+setNamettext.gettext ()+"/t"+"Precio:"+setPricetExt.gettext ()+"/n"; //inputoa.append(showout); }} if (e.getSource () == CancelBut) {if (GoodsNum> 0) {GoodsNum--; String Deletename = Goods.name [GoodsNum]; String DeletePrice = Goods.price [Goodsnum] .ToString (); //System.out.println(deletename); / * * Eliminar elementos en la base de datos * */ string sql = "delete de Goods_info Where name = '"+Deletename+"' y precio = '"+DeletePrice+"'"; intente {stmt.executeupdate (sql); } Catch (SQLException e1) {// TODO Auto Generado Bloque E1.PrintStackTrace (); } // Connection Con = dbManager .getConnection () ;; // Preparado PS = Con.PrepareStatement (SQL); addGoods (); }} if (e.getSource () == returnBut1) {loginwin.setVisible (true); magwin.setVisible (falso); } / * * Respuesta de evento de la interfaz de usuario * * / if (e.getSource () == returnBut2) {LoginWin.SetVisible (true); userwin.setVisible (falso); } if (e.getSource () == SubmitBuy) {if (! ShowBuynumText.GetText (). Equals ("")) {buyCount [GoodsCOMBox.getSelectedIndex ()] = Float.Parsefloat (showBuyyMText.getText ()); String ContentItem = ""; Float Summon = float.parsefloat (showBuynumText.gettext ())*(float) Goods.price [GoodsCOMBOX.GetSelectedIndex ()]; ContentItem = "Comercio Nombre:"+Goods.name [GoodsCOMBox.GetSelectedIndex ()]+""+"Precio unitario:"+Goods.Price [GoodsCOMBox.GetSelectedIndex ()]. ToString ()+""+"Cantidad de compra:"+showBUynumText.getText ()+"+" Total Price: "+Summon.Tostring (); buyItem.Addelement (ContentItem); // buyItem [buynum] = contentItem; buynum ++; chooselist.removeAll (); ChoicElist.setListData (buyItem); sumoney+= invocar; } else {joptionPane.ShowMessEdialog (Magwin, "La cantidad de compra no puede estar vacía", "Advertencia", JoptionPane.Plain_Message); }} if (e.getSource () == DeleteBuybut) {if (ChoicElist.GetSelectedValue () == NULL) {jOptionPane.ShowMessEdialog (magwin, "no se selecciona ningún elemento que se elimine", "Advertencia", joptionPane.plain_message); } else if (buynum> 0) {int i = choicElist.getSelectedIndex (); Cadena selectitem = buyItem.get (i); //System.out.println(Selectitem); String DeletePrice = ""; for (int j = 0; j <selectitem.length ()-3; j ++) {// system.out.println (selectItem.substring (j, j+3)); if (selectItem.substring (J, j+3) .equals ("Total Price:")) {DelEtePrice = SelectItem.Substring (j+3, selectItem.length ()); System.out.println (DeletePrice); sumoney- = float.parsefloat (DeletePrice); romper; }} buyItem.remove (i); choiCelist.removeAll (); ChoicElist.setListData (buyItem); ChoicElist.Validate (); buynum--; } else {joptionPane.ShowMessEdialog (Magwin, "El carrito de compras está vacío, no se puede eliminar", "Advertencia", JOptionPane.Plain_Message); }} if (e.getSource () == countBut) {// Sumtone for (int i = 0; i <buyitem.size (); i ++) {string str = buyitem.get (i) .substring (0, 2); if (str.equals ("precio total")) {buyitem.remove (i); }} buyItem.addelement ("Price total:"+Sumtone.ToString ()); choiCelist.removeAll (); ChoicElist.setListData (buyItem); ChoicElist.Validate (); }} private void addGoods () {if (! inputarea.gettext (). Equals ("")) inputARea.setText (""); // TODO STUB AUTO GENERADO PARA (INT I = 0; i <Goodsnum; i ++) {String Massage = "Comercio:"+Goods.name [i]+"/t"+"Precio:"+Goods.price [i] .ToString ()+"/n"; inputArea.append (masaje); }}} class ManageWindow extiende jframe {manageWindow (título de cadena) {super (título); }} clase UserWindow extiende jframe {userWindow (title de cadena) {super (título); }}¡Elimine la parte de la base de datos relevante y ejecutarla en su computadora!
Capturas de pantalla relacionadas:
Interfaz de administrador:
Interfaz de usuario:
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.