Advertisement
Guest User

Untitled

a guest
Apr 21st, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 24.05 KB | None | 0 0
  1. package com.liarstudio;
  2.  
  3. import javafx.stage.FileChooser;
  4. import org.postgresql.jdbc4.Jdbc4ResultSet;
  5. import org.postgresql.util.PSQLException;
  6.  
  7. import javax.swing.*;
  8. import java.awt.*;
  9. import javax.swing.event.ListSelectionEvent;
  10. import javax.swing.event.ListSelectionListener;
  11. import javax.swing.table.DefaultTableModel;
  12. import javax.swing.table.DefaultTableCellRenderer;
  13. import javax.swing.table.TableRowSorter;
  14. import java.awt.event.*;
  15. import java.io.*;
  16. import java.sql.Ref;
  17. import java.util.ArrayList;
  18. import java.util.Comparator;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.stream.Collectors;
  22. import java.sql.*;
  23.  
  24. /**
  25. * Created by M1DERY on 26.03.2017.
  26. */
  27. public class ShopForm extends JFrame{
  28. private JPanel panelMain;
  29. private JTable tableData;
  30. private JTextField tbNameFilter;
  31. private JRadioButton rbName;
  32. private JRadioButton rbType;
  33.  
  34.  
  35. private List<Product> products;
  36. private File file = new File("k1k.txt");
  37.  
  38.  
  39. MenuItem saveToFile;
  40. MenuItem saveToDB;
  41. Menu groupByType;
  42.  
  43. DefaultTableModel model;
  44. TableRowSorter<DefaultTableModel> sorter;
  45.  
  46.  
  47. enum ProductClass {
  48. PC, ACCESORY, SMARTPHONE;
  49. }
  50. public ShopForm() {
  51. super("Computer Shop");
  52.  
  53. setContentPane(this.panelMain);
  54. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  55. setSize(800, 300);
  56. //panelMain.setSize(900, 300);
  57. panelMain.setPreferredSize(new Dimension(800, 300));
  58. pack();
  59. setVisible(true);
  60.  
  61. products = new ArrayList<Product>();
  62. MenuInitialize();
  63. TableInitialize();
  64. RowSelectionInitialize();
  65. RefreshTable();
  66. SorterInitialize();
  67. FilterInitialize();
  68. SetButtonsVisible(false);
  69.  
  70.  
  71. }
  72. //////////////////////////////////////////////
  73. /* Секция инициализация таблицы, ее свойств */
  74. //////////////////////////////////////////////
  75.  
  76.  
  77. //Базовая инициализация таблицы
  78. private void TableInitialize() {
  79.  
  80. tableData.setRowHeight(30);
  81.  
  82.  
  83. //создаем новую модель для отображения таблицы;
  84. // ячейки доступны только для чтения
  85. model = new DefaultTableModel() {
  86. @Override
  87. public boolean isCellEditable(int row, int column) {
  88. return false;
  89. }
  90. };
  91.  
  92. model.addColumn("ID");;
  93. model.addColumn("Type");
  94. model.addColumn("Model");
  95. model.addColumn("Price");
  96. model.addColumn("Description");
  97.  
  98. tableData.setModel(model);
  99.  
  100. tableData.getColumn("ID").setPreferredWidth(120);
  101. tableData.getColumn("Type").setPreferredWidth(100);
  102. tableData.getColumn("Model").setPreferredWidth(230);
  103. tableData.getColumn("Price").setPreferredWidth(150);
  104. tableData.getColumn("Description").setPreferredWidth(300);
  105.  
  106.  
  107. DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
  108. centerRenderer.setHorizontalAlignment( JLabel.CENTER );
  109. for (int i = 0; i < tableData.getColumnCount(); i++)
  110. tableData.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );
  111.  
  112.  
  113. //tableData.getModel().setValueAt(pc.id.toString()+ System.lineSeparator() + pc.name, 0, 0);
  114.  
  115.  
  116. //tableData.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
  117.  
  118.  
  119. }
  120.  
  121. //Реакция на выбор определенной ячейки пользователем
  122. private void RowSelectionInitialize()
  123. {
  124. ListSelectionModel lsm = tableData.getSelectionModel();
  125. lsm.addListSelectionListener((ListSelectionEvent e) -> {
  126. if (!lsm.isSelectionEmpty())
  127. {
  128. Integer selectedRow = lsm.getMinSelectionIndex();
  129. Integer selectedProduct = GetProductIndex(selectedRow);
  130. /* KeyAdapter ka = new KeyAdapter() {
  131. public void keyReleased(KeyEvent e) {
  132. if (e.getKeyCode() == KeyEvent.VK_I)
  133. JOptionPane.showMessageDialog(null, products.get(selectedRow).toString());
  134. tableData.removeKeyListener(this);
  135.  
  136. }
  137. };
  138. tableData.addKeyListener(ka);*/
  139.  
  140. tableData.getActionMap().clear();
  141. tableData.getInputMap().clear();
  142.  
  143. tableData.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Info");
  144. tableData.getActionMap().put("Info", new AbstractAction() {
  145. public void actionPerformed(ActionEvent e) {
  146. //
  147. JOptionPane.showMessageDialog(null, products.get(selectedProduct).toString());
  148. }
  149. });
  150.  
  151. tableData.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "Delete");
  152. tableData.getActionMap().put("Delete", new AbstractAction() {
  153. public void actionPerformed(ActionEvent e) {
  154. if (JOptionPane.showConfirmDialog(null,
  155. "Are you sure to delete this product?") == 0);
  156. DeleteRow(selectedRow, selectedProduct);
  157. }
  158. });
  159.  
  160. tableData.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "Edit");
  161. tableData.getActionMap().put("Edit",new AbstractAction() {
  162. public void actionPerformed(ActionEvent e) {
  163. AddProduct pr = new AddProduct((ShopForm)SwingUtilities.getAncestorOfClass(ShopForm.class, (JTable)e.getSource()), products.get(selectedProduct));
  164. }});//new FrameAction(this,
  165. //products.get(selectedRow)));
  166.  
  167.  
  168. //JOptionPane.showMessageDialog(null, products.get(selectedRow).toString());
  169. }
  170. });
  171. }
  172.  
  173.  
  174. class FrameAction extends AbstractAction {
  175. ShopForm sf; Product pr;
  176. FrameAction(ShopForm new_sf, Product new_pr)
  177. {
  178. this.sf = new_sf;
  179. this.pr = new_pr;
  180. }
  181. public void actionPerformed(ActionEvent e) {
  182. AddProduct editForm = new AddProduct(sf, pr);
  183. }
  184. }
  185. //Инициализация верхнего меню, добавление ActionListener'ов
  186. private void MenuInitialize()
  187. {
  188. MenuBar menuBar = new MenuBar();
  189. Menu fileMenu = new Menu("File");
  190. Menu productsMenu = new Menu("Products");
  191. Menu helpMenu = new Menu("Help");
  192.  
  193.  
  194. MenuItem loadFromFile = new MenuItem("Load From File");
  195. loadFromFile.addActionListener(LoadFromFileAction());
  196.  
  197. MenuItem loadFromDB = new MenuItem("Load From Database");
  198. loadFromDB.addActionListener(LoadFromDBAction());
  199.  
  200. saveToFile = new MenuItem("Save To File");
  201. saveToFile.addActionListener(SaveToFileAction());
  202.  
  203. saveToDB = new MenuItem("Save to Database");
  204. saveToDB.addActionListener(SaveToDBAction());
  205.  
  206. fileMenu.add(loadFromFile); fileMenu.add(loadFromDB);
  207. fileMenu.add(saveToFile); fileMenu.add(saveToDB);
  208.  
  209. MenuItem addProduct = new MenuItem("Add");
  210. addProduct.addActionListener((ActionEvent e) -> {
  211. AddProduct addForm = new AddProduct(this);
  212. });
  213.  
  214. groupByType = new Menu("Group By Type");
  215. MenuItem sortByName = new MenuItem("Sort By Name");
  216. MenuItem sortByPrice = new MenuItem("Sort By Price");
  217.  
  218. groupByType.add(sortByPrice);groupByType.add(sortByName);
  219.  
  220. sortByPrice.addActionListener(sortGrouped(true));
  221. sortByName.addActionListener(sortGrouped(false));
  222.  
  223. productsMenu.add(addProduct); productsMenu.add(groupByType);
  224.  
  225.  
  226. menuBar.add(fileMenu); menuBar.add(productsMenu); menuBar.add(helpMenu);
  227. setMenuBar(menuBar);
  228. }
  229.  
  230. //Добавление фильтрации, задание ее логики
  231. private void FilterInitialize()
  232. {
  233. ButtonGroup group = new ButtonGroup();
  234. group.add(rbName);
  235. group.add(rbType);
  236.  
  237. tbNameFilter.addActionListener((ActionEvent e) ->
  238. {
  239. RowFilter<DefaultTableModel, Object> rf = null;
  240. try {
  241. if (rbName.isSelected())
  242. rf = RowFilter.regexFilter(tbNameFilter.getText(), 2);
  243. else
  244. rf = RowFilter.regexFilter(tbNameFilter.getText(), 1);
  245. } catch (java.util.regex.PatternSyntaxException ex) {
  246. return;
  247. }
  248. sorter.setRowFilter(rf);
  249. });
  250. }
  251. //Добавление стандартного сортировщика таблицы
  252. private void SorterInitialize()
  253. {
  254. sorter = new TableRowSorter<DefaultTableModel>
  255. ((DefaultTableModel)tableData.getModel());
  256. sorter.setComparator(3, Comparator.comparing(cell -> Double.parseDouble(((String)cell).replace(',','.').replaceAll(" ",""))));
  257. tableData.setRowSorter(sorter);
  258. }
  259.  
  260. //////////////////////////////////////////////
  261. /* Секция логики работы ActionListener'ов */
  262. //////////////////////////////////////////////
  263.  
  264. //AL загрузки из файла
  265. private ActionListener LoadFromFileAction()
  266. {
  267. return (ActionEvent e) -> {
  268. /*JFileChooser openFile = new JFileChooser();
  269. int ret = openFile.showOpenDialog(null);
  270. if (ret == JFileChooser.APPROVE_OPTION) {*/
  271. try {
  272. //file = openFile.getSelectedFile();
  273.  
  274. products.clear();
  275.  
  276. BufferedReader br = new BufferedReader(new FileReader(file));
  277. String line;
  278. while ((line = br.readLine()) != null)
  279. {
  280. Product pr;
  281. switch (Integer.parseInt(line)) {
  282. case 0:
  283. pr = new PC();
  284. break;
  285. case 1:
  286. pr = new Smartphone();
  287. break;
  288. case 2:
  289. pr = new Accesory();
  290. break;
  291. default:
  292. products.clear();
  293. throw new IOException();
  294. }
  295. pr.loadFromFile(br);
  296. SetId(pr);
  297. products.add(pr);
  298. br.readLine();
  299. }
  300.  
  301. SetButtonsVisible(true);
  302. RefreshTable();
  303.  
  304. } catch (IOException e1) {
  305. e1.printStackTrace();
  306. file = null;
  307. CleanTable();
  308. JOptionPane.showMessageDialog(null, "Can't read the file. Please, check the fields.", "Error", 2);
  309. }
  310. };
  311. }
  312.  
  313. //AL загрузки из БД
  314. private ActionListener LoadFromDBAction()
  315. {
  316. return (ActionEvent e) -> {
  317. try {
  318. Class.forName("org.postgresql.Driver");
  319.  
  320. String url = "jdbc:postgresql://localhost:5432/postgres";
  321. String user = "postgres";
  322. String password = "postgres";
  323.  
  324. products.clear();
  325.  
  326. Connection connection = DriverManager.getConnection(url, user, password);
  327.  
  328. Statement statement = connection.createStatement();
  329.  
  330. ResultSet res = statement.executeQuery("SELECT * FROM PC");
  331. while (res.next()) {
  332. PC pc = new PC();
  333. pc.loadFromDB(res);
  334. products.add(pc);
  335. }
  336.  
  337. res = statement.executeQuery("SELECT * FROM SMARTPHONE");
  338. while (res.next()) {
  339. Smartphone smartphone = new Smartphone();
  340. smartphone.loadFromDB(res);
  341. products.add(smartphone);
  342. }
  343.  
  344.  
  345. res = statement.executeQuery("SELECT * FROM ACCESORY");
  346. while (res.next()) {
  347. Accesory accesory = new Accesory();
  348. accesory.loadFromDB(res);
  349. products.add(accesory);
  350. }
  351.  
  352.  
  353. products.sort(Comparator.comparing(p -> p.id));
  354. SetButtonsVisible(true);
  355. RefreshTable();
  356. }
  357. catch (ClassNotFoundException cnfe) {
  358. JOptionPane.showMessageDialog(null, "Can't find suitable driver. Please, contact your administrator.", "Error", 2);
  359. }
  360. catch (SQLException sqle) {
  361. sqle.printStackTrace();
  362.  
  363. CleanTable();
  364. JOptionPane.showMessageDialog(null, "Some of your SQL Tables contains error. Please, check the columns.", "Error", 2);
  365. }
  366. };
  367. }
  368.  
  369. //AL сохранения в файл
  370. private ActionListener SaveToFileAction()
  371. {
  372. return (ActionEvent e) -> {
  373. if (file != null) {
  374. try {
  375. BufferedWriter bw = new BufferedWriter(new FileWriter(file, false));
  376.  
  377. for (Product product : products) {
  378. bw.write(GetClass(product).toString() + System.lineSeparator());
  379. product.saveToFile(bw);
  380. bw.write(System.lineSeparator());
  381. }
  382. bw.flush();
  383.  
  384. /*JFileChooser saveFile = new JFileChooser();
  385. saveFile.setSelectedFile(file);
  386. saveFile.showSaveDialog(null);*/
  387.  
  388. } catch (IOException e1) {
  389. e1.printStackTrace();
  390. }
  391. } else {
  392. JOptionPane.showMessageDialog(null, "There is no file! Please, open it first.", "Error", 2);
  393. }
  394. };
  395. }
  396.  
  397. //AL сохранения в БД
  398. private ActionListener SaveToDBAction()
  399. {
  400. return (ActionEvent e) -> {
  401. try {
  402.  
  403. Class.forName("org.postgresql.Driver");
  404.  
  405. String url = "jdbc:postgresql://localhost:5432/postgres";
  406. String user = "postgres";
  407. String password = "postgres";
  408.  
  409.  
  410. Connection connection = DriverManager.getConnection(url, user, password);
  411.  
  412.  
  413. Statement statement = connection.createStatement(1004, 1007);
  414. ResultSet idSet = statement.executeQuery(
  415. "SELECT \"ID\" FROM PC " +
  416. "UNION SELECT \"ID\" FROM ACCESORY " +
  417. "UNION SELECT \"ID\" FROM SMARTPHONE"
  418. );
  419.  
  420. if (idSet.isBeforeFirst()) {
  421.  
  422.  
  423. Object[] options = {"Replace",
  424. "Upgrade", "Add"};
  425. int chose = JOptionPane.showOptionDialog(null,
  426. "Would you like to REPLACE all the data, to UPGRADE changed products or just ADD new?",
  427. "Choose option",
  428. JOptionPane.YES_NO_OPTION,
  429. JOptionPane.QUESTION_MESSAGE,
  430. null, //do not use a custom Icon
  431. options, //the titles of buttons
  432. options[0]); //default button title
  433. switch (chose) {
  434. case 0:
  435. statement.execute(
  436. "DELETE FROM pc; DELETE FROM smartphone; DELETE FROM accesory");
  437. for (Product product : products)
  438. product.saveToDB(connection);
  439. break;
  440. case 1:
  441. for (Product product : products) {
  442. if (HasSameID(idSet, product)) {
  443. Statement st2 = connection.createStatement();
  444. st2.execute("DELETE FROM SMARTPHONE WHERE \"ID\" = " + product.id.toString() +
  445. "; DELETE FROM PC WHERE \"ID\" = " + product.id.toString() +
  446. "; DELETE FROM ACCESORY WHERE \"ID\" = " + product.id.toString()
  447. );
  448. }
  449. product.saveToDB(connection);
  450. }
  451. break;
  452. case 2:
  453. for (Product product : products)
  454. if (!HasSameID(idSet, product))
  455. product.saveToDB(connection);
  456. break;
  457. }
  458. } else {
  459. for (Product product : products)
  460. product.saveToDB(connection);
  461. }
  462. } catch (ClassNotFoundException cnfe) {
  463. JOptionPane.showMessageDialog(null, "Can't find suitable driver. Please, contact your administrator.", "Error", 2);
  464. }
  465. catch (SQLException sqle) {
  466. sqle.printStackTrace();
  467. }
  468.  
  469. };
  470. }
  471.  
  472. //AL, появляющийся при нажатии на кнопку "Group by".
  473. //Параметр показывает, выполняется ли помимо группировки сортировка по цене, или нет
  474. private ActionListener sortGrouped(boolean isSortingPrice)
  475. {
  476. return new ActionListener() {
  477. @Override
  478. public void actionPerformed(ActionEvent e) {
  479. Map<String, List<Product>> productsGrouped =
  480. products.stream().collect(Collectors.groupingBy(w -> w.getClass().getSimpleName()));
  481.  
  482. tableData.setRowSorter(null);
  483. sorter = null;
  484. //model.setRowCount(0);
  485. products.clear();
  486. for (String className : productsGrouped.keySet()) {
  487. if (isSortingPrice)
  488. productsGrouped.get(className).sort(Comparator.comparing(p -> p.price));//(p1, p2) -> p1.price.compareTo(p2.price))
  489. else
  490. productsGrouped.get(className).sort(Comparator.comparing(p -> p.name));
  491.  
  492.  
  493. for (Product prod : productsGrouped.get(className)) {
  494. products.add(prod);
  495. }
  496. }
  497. RefreshTable();
  498. SorterInitialize();
  499. }
  500. };
  501. }
  502.  
  503. //////////////////////////////////////////////
  504. /* Секция вспомогательных функций */
  505. //////////////////////////////////////////////
  506.  
  507. //Определение, какому классу принадлежит товар.
  508. public static Integer GetClass(Product p)
  509. {
  510. if (p instanceof PC)
  511. return 0;
  512. else {
  513. if (p instanceof Smartphone)
  514. return 1;
  515. else return 2;
  516. }
  517. }
  518.  
  519. //Если в списке товаров есть товар с таким же ID, возвращается true, иначе - false
  520. private boolean HasSameID(Product pr)
  521. {
  522. for (Product p : products)
  523. if (p.id.compareTo(pr.id)==0)
  524. return true;
  525. return false;
  526. }
  527. //Проверка, есть ли в БД товары с одинаковым ID
  528. private boolean HasSameID(ResultSet resultSet, Product p) throws SQLException
  529. {
  530. resultSet.first();
  531. do {
  532. if (Integer.compare(resultSet.getInt("ID"), p.id) == 0)
  533. return true;
  534. } while (resultSet.next());
  535. return false;
  536. }
  537. //Целочисленная сумма кодов символов строки
  538. private int SumString(String str)
  539. {
  540. int res = 0;
  541. for (char sym : str.toCharArray())
  542. {
  543. res+=sym;
  544. }
  545. return res;
  546. }
  547.  
  548. //Хеш-функция для задания ID
  549. private int HashFunc(Product pr)
  550. {
  551. return java.time.LocalTime.now().getSecond() + java.time.LocalTime.now().getNano() +
  552. //pr.getClass().getName().charAt(0) +
  553. SumString(pr.name) + SumString(pr.description);
  554. }
  555.  
  556. //Задание уникального ID с проверкой всех остальных
  557. private void SetId(Product pr)
  558. {
  559. while (pr.id == null || HasSameID(pr))
  560. pr.id = HashFunc(pr);
  561. }
  562.  
  563.  
  564. //Установка видимости кнопок, которая зависит от того, есть ли в списке хоть один товар
  565. public void SetButtonsVisible(boolean AreProductsFilled)
  566. {
  567. saveToDB.setEnabled(AreProductsFilled);
  568. saveToFile.setEnabled(AreProductsFilled);
  569. groupByType.setEnabled(AreProductsFilled);
  570. }
  571.  
  572. private int GetProductIndex(int tableIndex)
  573. {
  574. int id = Integer.getInteger((String)model.getValueAt(tableIndex, 0));
  575. for (int i = 0; i < products.size(); ++i)
  576. if (Integer.compare(id, products.get(i).id)==0)
  577. return i;
  578. return -1;
  579. }
  580. //////////////////////////////////////////////
  581. /* Секция взаимодействия данных и таблицы */
  582. //////////////////////////////////////////////
  583.  
  584.  
  585. //Добавление нового продукта
  586. public void AddProduct(Product pr)
  587. {
  588. /*int i = 0;
  589. for (; i < products.size() && i == products.get(i).id; i++)
  590. { }
  591. */
  592. SetId(pr);
  593. /*products.add(i, pr);
  594. model.insertRow(i, pr.printRow());*/
  595. products.add(pr); model.addRow(pr.printRow());
  596. tableData.setModel(model);
  597. }
  598. //Обновление данных в таблице на основе списка товаров
  599. private void RefreshTable() {
  600. model.setRowCount(0);
  601. for (Product product : products) {
  602. model.addRow(product.printRow());
  603. }
  604. tableData.setModel(model);
  605. }
  606.  
  607. private void CleanTable()
  608. {
  609. products.clear(); model.setRowCount(0);
  610. tableData.setModel(model);
  611. }
  612. //Удаление заданной строки в таблице с удалением его из списка товаров
  613. private void DeleteRow(int i)
  614. {
  615. products.remove(i);
  616. model.removeRow(i);
  617. tableData.setModel(model);
  618. }
  619. private void DeleteRow(int tableIndex, int productIndex)
  620. {
  621. products.remove(productIndex);
  622. model.removeRow(tableIndex);
  623. tableData.setModel(model);
  624. }
  625.  
  626. public void UpgradeProduct(Product old_product, Product new_product)
  627. {
  628. new_product.id = old_product.id;
  629. int index = products.indexOf(old_product);
  630. DeleteRow(index);
  631. products.add(index, new_product);
  632. model.insertRow(index, new_product.printRow());
  633. tableData.setModel(model);
  634. }
  635. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement