Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.liarstudio;
- import javafx.stage.FileChooser;
- import org.postgresql.jdbc4.Jdbc4ResultSet;
- import org.postgresql.util.PSQLException;
- import javax.swing.*;
- import java.awt.*;
- import javax.swing.event.ListSelectionEvent;
- import javax.swing.event.ListSelectionListener;
- import javax.swing.table.DefaultTableModel;
- import javax.swing.table.DefaultTableCellRenderer;
- import javax.swing.table.TableRowSorter;
- import java.awt.event.*;
- import java.io.*;
- import java.sql.Ref;
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- import java.sql.*;
- /**
- * Created by M1DERY on 26.03.2017.
- */
- public class ShopForm extends JFrame{
- private JPanel panelMain;
- private JTable tableData;
- private JTextField tbNameFilter;
- private JRadioButton rbName;
- private JRadioButton rbType;
- private List<Product> products;
- private File file = new File("k1k.txt");
- MenuItem saveToFile;
- MenuItem saveToDB;
- Menu groupByType;
- DefaultTableModel model;
- TableRowSorter<DefaultTableModel> sorter;
- enum ProductClass {
- PC, ACCESORY, SMARTPHONE;
- }
- public ShopForm() {
- super("Computer Shop");
- setContentPane(this.panelMain);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setSize(800, 300);
- //panelMain.setSize(900, 300);
- panelMain.setPreferredSize(new Dimension(800, 300));
- pack();
- setVisible(true);
- products = new ArrayList<Product>();
- MenuInitialize();
- TableInitialize();
- RowSelectionInitialize();
- RefreshTable();
- SorterInitialize();
- FilterInitialize();
- SetButtonsVisible(false);
- }
- //////////////////////////////////////////////
- /* Секция инициализация таблицы, ее свойств */
- //////////////////////////////////////////////
- //Базовая инициализация таблицы
- private void TableInitialize() {
- tableData.setRowHeight(30);
- //создаем новую модель для отображения таблицы;
- // ячейки доступны только для чтения
- model = new DefaultTableModel() {
- @Override
- public boolean isCellEditable(int row, int column) {
- return false;
- }
- };
- model.addColumn("ID");;
- model.addColumn("Type");
- model.addColumn("Model");
- model.addColumn("Price");
- model.addColumn("Description");
- tableData.setModel(model);
- tableData.getColumn("ID").setPreferredWidth(120);
- tableData.getColumn("Type").setPreferredWidth(100);
- tableData.getColumn("Model").setPreferredWidth(230);
- tableData.getColumn("Price").setPreferredWidth(150);
- tableData.getColumn("Description").setPreferredWidth(300);
- DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
- centerRenderer.setHorizontalAlignment( JLabel.CENTER );
- for (int i = 0; i < tableData.getColumnCount(); i++)
- tableData.getColumnModel().getColumn(i).setCellRenderer( centerRenderer );
- //tableData.getModel().setValueAt(pc.id.toString()+ System.lineSeparator() + pc.name, 0, 0);
- //tableData.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
- }
- //Реакция на выбор определенной ячейки пользователем
- private void RowSelectionInitialize()
- {
- ListSelectionModel lsm = tableData.getSelectionModel();
- lsm.addListSelectionListener((ListSelectionEvent e) -> {
- if (!lsm.isSelectionEmpty())
- {
- Integer selectedRow = lsm.getMinSelectionIndex();
- Integer selectedProduct = GetProductIndex(selectedRow);
- /* KeyAdapter ka = new KeyAdapter() {
- public void keyReleased(KeyEvent e) {
- if (e.getKeyCode() == KeyEvent.VK_I)
- JOptionPane.showMessageDialog(null, products.get(selectedRow).toString());
- tableData.removeKeyListener(this);
- }
- };
- tableData.addKeyListener(ka);*/
- tableData.getActionMap().clear();
- tableData.getInputMap().clear();
- tableData.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Info");
- tableData.getActionMap().put("Info", new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- //
- JOptionPane.showMessageDialog(null, products.get(selectedProduct).toString());
- }
- });
- tableData.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), "Delete");
- tableData.getActionMap().put("Delete", new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- if (JOptionPane.showConfirmDialog(null,
- "Are you sure to delete this product?") == 0);
- DeleteRow(selectedRow, selectedProduct);
- }
- });
- tableData.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "Edit");
- tableData.getActionMap().put("Edit",new AbstractAction() {
- public void actionPerformed(ActionEvent e) {
- AddProduct pr = new AddProduct((ShopForm)SwingUtilities.getAncestorOfClass(ShopForm.class, (JTable)e.getSource()), products.get(selectedProduct));
- }});//new FrameAction(this,
- //products.get(selectedRow)));
- //JOptionPane.showMessageDialog(null, products.get(selectedRow).toString());
- }
- });
- }
- class FrameAction extends AbstractAction {
- ShopForm sf; Product pr;
- FrameAction(ShopForm new_sf, Product new_pr)
- {
- this.sf = new_sf;
- this.pr = new_pr;
- }
- public void actionPerformed(ActionEvent e) {
- AddProduct editForm = new AddProduct(sf, pr);
- }
- }
- //Инициализация верхнего меню, добавление ActionListener'ов
- private void MenuInitialize()
- {
- MenuBar menuBar = new MenuBar();
- Menu fileMenu = new Menu("File");
- Menu productsMenu = new Menu("Products");
- Menu helpMenu = new Menu("Help");
- MenuItem loadFromFile = new MenuItem("Load From File");
- loadFromFile.addActionListener(LoadFromFileAction());
- MenuItem loadFromDB = new MenuItem("Load From Database");
- loadFromDB.addActionListener(LoadFromDBAction());
- saveToFile = new MenuItem("Save To File");
- saveToFile.addActionListener(SaveToFileAction());
- saveToDB = new MenuItem("Save to Database");
- saveToDB.addActionListener(SaveToDBAction());
- fileMenu.add(loadFromFile); fileMenu.add(loadFromDB);
- fileMenu.add(saveToFile); fileMenu.add(saveToDB);
- MenuItem addProduct = new MenuItem("Add");
- addProduct.addActionListener((ActionEvent e) -> {
- AddProduct addForm = new AddProduct(this);
- });
- groupByType = new Menu("Group By Type");
- MenuItem sortByName = new MenuItem("Sort By Name");
- MenuItem sortByPrice = new MenuItem("Sort By Price");
- groupByType.add(sortByPrice);groupByType.add(sortByName);
- sortByPrice.addActionListener(sortGrouped(true));
- sortByName.addActionListener(sortGrouped(false));
- productsMenu.add(addProduct); productsMenu.add(groupByType);
- menuBar.add(fileMenu); menuBar.add(productsMenu); menuBar.add(helpMenu);
- setMenuBar(menuBar);
- }
- //Добавление фильтрации, задание ее логики
- private void FilterInitialize()
- {
- ButtonGroup group = new ButtonGroup();
- group.add(rbName);
- group.add(rbType);
- tbNameFilter.addActionListener((ActionEvent e) ->
- {
- RowFilter<DefaultTableModel, Object> rf = null;
- try {
- if (rbName.isSelected())
- rf = RowFilter.regexFilter(tbNameFilter.getText(), 2);
- else
- rf = RowFilter.regexFilter(tbNameFilter.getText(), 1);
- } catch (java.util.regex.PatternSyntaxException ex) {
- return;
- }
- sorter.setRowFilter(rf);
- });
- }
- //Добавление стандартного сортировщика таблицы
- private void SorterInitialize()
- {
- sorter = new TableRowSorter<DefaultTableModel>
- ((DefaultTableModel)tableData.getModel());
- sorter.setComparator(3, Comparator.comparing(cell -> Double.parseDouble(((String)cell).replace(',','.').replaceAll(" ",""))));
- tableData.setRowSorter(sorter);
- }
- //////////////////////////////////////////////
- /* Секция логики работы ActionListener'ов */
- //////////////////////////////////////////////
- //AL загрузки из файла
- private ActionListener LoadFromFileAction()
- {
- return (ActionEvent e) -> {
- /*JFileChooser openFile = new JFileChooser();
- int ret = openFile.showOpenDialog(null);
- if (ret == JFileChooser.APPROVE_OPTION) {*/
- try {
- //file = openFile.getSelectedFile();
- products.clear();
- BufferedReader br = new BufferedReader(new FileReader(file));
- String line;
- while ((line = br.readLine()) != null)
- {
- Product pr;
- switch (Integer.parseInt(line)) {
- case 0:
- pr = new PC();
- break;
- case 1:
- pr = new Smartphone();
- break;
- case 2:
- pr = new Accesory();
- break;
- default:
- products.clear();
- throw new IOException();
- }
- pr.loadFromFile(br);
- SetId(pr);
- products.add(pr);
- br.readLine();
- }
- SetButtonsVisible(true);
- RefreshTable();
- } catch (IOException e1) {
- e1.printStackTrace();
- file = null;
- CleanTable();
- JOptionPane.showMessageDialog(null, "Can't read the file. Please, check the fields.", "Error", 2);
- }
- };
- }
- //AL загрузки из БД
- private ActionListener LoadFromDBAction()
- {
- return (ActionEvent e) -> {
- try {
- Class.forName("org.postgresql.Driver");
- String url = "jdbc:postgresql://localhost:5432/postgres";
- String user = "postgres";
- String password = "postgres";
- products.clear();
- Connection connection = DriverManager.getConnection(url, user, password);
- Statement statement = connection.createStatement();
- ResultSet res = statement.executeQuery("SELECT * FROM PC");
- while (res.next()) {
- PC pc = new PC();
- pc.loadFromDB(res);
- products.add(pc);
- }
- res = statement.executeQuery("SELECT * FROM SMARTPHONE");
- while (res.next()) {
- Smartphone smartphone = new Smartphone();
- smartphone.loadFromDB(res);
- products.add(smartphone);
- }
- res = statement.executeQuery("SELECT * FROM ACCESORY");
- while (res.next()) {
- Accesory accesory = new Accesory();
- accesory.loadFromDB(res);
- products.add(accesory);
- }
- products.sort(Comparator.comparing(p -> p.id));
- SetButtonsVisible(true);
- RefreshTable();
- }
- catch (ClassNotFoundException cnfe) {
- JOptionPane.showMessageDialog(null, "Can't find suitable driver. Please, contact your administrator.", "Error", 2);
- }
- catch (SQLException sqle) {
- sqle.printStackTrace();
- CleanTable();
- JOptionPane.showMessageDialog(null, "Some of your SQL Tables contains error. Please, check the columns.", "Error", 2);
- }
- };
- }
- //AL сохранения в файл
- private ActionListener SaveToFileAction()
- {
- return (ActionEvent e) -> {
- if (file != null) {
- try {
- BufferedWriter bw = new BufferedWriter(new FileWriter(file, false));
- for (Product product : products) {
- bw.write(GetClass(product).toString() + System.lineSeparator());
- product.saveToFile(bw);
- bw.write(System.lineSeparator());
- }
- bw.flush();
- /*JFileChooser saveFile = new JFileChooser();
- saveFile.setSelectedFile(file);
- saveFile.showSaveDialog(null);*/
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- } else {
- JOptionPane.showMessageDialog(null, "There is no file! Please, open it first.", "Error", 2);
- }
- };
- }
- //AL сохранения в БД
- private ActionListener SaveToDBAction()
- {
- return (ActionEvent e) -> {
- try {
- Class.forName("org.postgresql.Driver");
- String url = "jdbc:postgresql://localhost:5432/postgres";
- String user = "postgres";
- String password = "postgres";
- Connection connection = DriverManager.getConnection(url, user, password);
- Statement statement = connection.createStatement(1004, 1007);
- ResultSet idSet = statement.executeQuery(
- "SELECT \"ID\" FROM PC " +
- "UNION SELECT \"ID\" FROM ACCESORY " +
- "UNION SELECT \"ID\" FROM SMARTPHONE"
- );
- if (idSet.isBeforeFirst()) {
- Object[] options = {"Replace",
- "Upgrade", "Add"};
- int chose = JOptionPane.showOptionDialog(null,
- "Would you like to REPLACE all the data, to UPGRADE changed products or just ADD new?",
- "Choose option",
- JOptionPane.YES_NO_OPTION,
- JOptionPane.QUESTION_MESSAGE,
- null, //do not use a custom Icon
- options, //the titles of buttons
- options[0]); //default button title
- switch (chose) {
- case 0:
- statement.execute(
- "DELETE FROM pc; DELETE FROM smartphone; DELETE FROM accesory");
- for (Product product : products)
- product.saveToDB(connection);
- break;
- case 1:
- for (Product product : products) {
- if (HasSameID(idSet, product)) {
- Statement st2 = connection.createStatement();
- st2.execute("DELETE FROM SMARTPHONE WHERE \"ID\" = " + product.id.toString() +
- "; DELETE FROM PC WHERE \"ID\" = " + product.id.toString() +
- "; DELETE FROM ACCESORY WHERE \"ID\" = " + product.id.toString()
- );
- }
- product.saveToDB(connection);
- }
- break;
- case 2:
- for (Product product : products)
- if (!HasSameID(idSet, product))
- product.saveToDB(connection);
- break;
- }
- } else {
- for (Product product : products)
- product.saveToDB(connection);
- }
- } catch (ClassNotFoundException cnfe) {
- JOptionPane.showMessageDialog(null, "Can't find suitable driver. Please, contact your administrator.", "Error", 2);
- }
- catch (SQLException sqle) {
- sqle.printStackTrace();
- }
- };
- }
- //AL, появляющийся при нажатии на кнопку "Group by".
- //Параметр показывает, выполняется ли помимо группировки сортировка по цене, или нет
- private ActionListener sortGrouped(boolean isSortingPrice)
- {
- return new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- Map<String, List<Product>> productsGrouped =
- products.stream().collect(Collectors.groupingBy(w -> w.getClass().getSimpleName()));
- tableData.setRowSorter(null);
- sorter = null;
- //model.setRowCount(0);
- products.clear();
- for (String className : productsGrouped.keySet()) {
- if (isSortingPrice)
- productsGrouped.get(className).sort(Comparator.comparing(p -> p.price));//(p1, p2) -> p1.price.compareTo(p2.price))
- else
- productsGrouped.get(className).sort(Comparator.comparing(p -> p.name));
- for (Product prod : productsGrouped.get(className)) {
- products.add(prod);
- }
- }
- RefreshTable();
- SorterInitialize();
- }
- };
- }
- //////////////////////////////////////////////
- /* Секция вспомогательных функций */
- //////////////////////////////////////////////
- //Определение, какому классу принадлежит товар.
- public static Integer GetClass(Product p)
- {
- if (p instanceof PC)
- return 0;
- else {
- if (p instanceof Smartphone)
- return 1;
- else return 2;
- }
- }
- //Если в списке товаров есть товар с таким же ID, возвращается true, иначе - false
- private boolean HasSameID(Product pr)
- {
- for (Product p : products)
- if (p.id.compareTo(pr.id)==0)
- return true;
- return false;
- }
- //Проверка, есть ли в БД товары с одинаковым ID
- private boolean HasSameID(ResultSet resultSet, Product p) throws SQLException
- {
- resultSet.first();
- do {
- if (Integer.compare(resultSet.getInt("ID"), p.id) == 0)
- return true;
- } while (resultSet.next());
- return false;
- }
- //Целочисленная сумма кодов символов строки
- private int SumString(String str)
- {
- int res = 0;
- for (char sym : str.toCharArray())
- {
- res+=sym;
- }
- return res;
- }
- //Хеш-функция для задания ID
- private int HashFunc(Product pr)
- {
- return java.time.LocalTime.now().getSecond() + java.time.LocalTime.now().getNano() +
- //pr.getClass().getName().charAt(0) +
- SumString(pr.name) + SumString(pr.description);
- }
- //Задание уникального ID с проверкой всех остальных
- private void SetId(Product pr)
- {
- while (pr.id == null || HasSameID(pr))
- pr.id = HashFunc(pr);
- }
- //Установка видимости кнопок, которая зависит от того, есть ли в списке хоть один товар
- public void SetButtonsVisible(boolean AreProductsFilled)
- {
- saveToDB.setEnabled(AreProductsFilled);
- saveToFile.setEnabled(AreProductsFilled);
- groupByType.setEnabled(AreProductsFilled);
- }
- private int GetProductIndex(int tableIndex)
- {
- int id = Integer.getInteger((String)model.getValueAt(tableIndex, 0));
- for (int i = 0; i < products.size(); ++i)
- if (Integer.compare(id, products.get(i).id)==0)
- return i;
- return -1;
- }
- //////////////////////////////////////////////
- /* Секция взаимодействия данных и таблицы */
- //////////////////////////////////////////////
- //Добавление нового продукта
- public void AddProduct(Product pr)
- {
- /*int i = 0;
- for (; i < products.size() && i == products.get(i).id; i++)
- { }
- */
- SetId(pr);
- /*products.add(i, pr);
- model.insertRow(i, pr.printRow());*/
- products.add(pr); model.addRow(pr.printRow());
- tableData.setModel(model);
- }
- //Обновление данных в таблице на основе списка товаров
- private void RefreshTable() {
- model.setRowCount(0);
- for (Product product : products) {
- model.addRow(product.printRow());
- }
- tableData.setModel(model);
- }
- private void CleanTable()
- {
- products.clear(); model.setRowCount(0);
- tableData.setModel(model);
- }
- //Удаление заданной строки в таблице с удалением его из списка товаров
- private void DeleteRow(int i)
- {
- products.remove(i);
- model.removeRow(i);
- tableData.setModel(model);
- }
- private void DeleteRow(int tableIndex, int productIndex)
- {
- products.remove(productIndex);
- model.removeRow(tableIndex);
- tableData.setModel(model);
- }
- public void UpgradeProduct(Product old_product, Product new_product)
- {
- new_product.id = old_product.id;
- int index = products.indexOf(old_product);
- DeleteRow(index);
- products.add(index, new_product);
- model.insertRow(index, new_product.printRow());
- tableData.setModel(model);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement