Как редактировать текстовый файл, используя JTextField с указанным форматом c? - PullRequest
0 голосов
/ 20 апреля 2020

Я создаю программу инвентаризации, которая включает кассу и режим администратора. Режим администратора может изменить название товара, цену и запас товара. Все элементы хранятся в текстовом файле.

Содержимое текстового файла (с косыми чертами для разделения имен, цен и т. Д. c):

 ID     Item Name                 Price   Stocks
00001 / Xbox 360                 / 7999  / 10
00002 / Xbox Series X            / 25999 / 20
00003 / Playstation 4 Pro        / 22999 / 15
00004 / Nintendo Switch          / 17999 / 27
00005 / Nintendo Switch Lite     / 11999 / 15

Я читаю и отображаю предметы, использующие JTable. Заголовки столбцов добавляются в коде:

String filePath = "C:\\Users\\zagad\\IdeaProjects\\DATABYTES\\stock\\consoles\\consoles.txt";
                File file = new File(filePath);
                try {
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    DefaultTableModel model = (DefaultTableModel) productTable.getModel();
                    Object[] tableLines = br.lines().toArray();

                    for (int i = 0; i < tableLines.length; i++) {
                        String line = tableLines[i].toString().trim();
                        String[] dataRow = line.split("/");
                        productTable.getColumnModel().getColumn(0).setPreferredWidth(21);
                        productTable.getColumnModel().getColumn(1).setPreferredWidth(120);
                        productTable.getColumnModel().getColumn(2).setPreferredWidth(30);
                        productTable.getColumnModel().getColumn(3).setPreferredWidth(30);
                        model.addRow(dataRow);
                    }

Вот эталонное изображение макета:

enter image description here

Имеет JTable и четыре JTextFields. Есть ли идея, что я могу редактировать текстовый файл напрямую, что пользователь вводит из JTextFields с соответствующим расположением элементов в текстовом файле?

Любая идея приветствуется. Спасибо!

Ответы [ 4 ]

1 голос
/ 24 апреля 2020

Мне не удалось обновить код класса InventoryDemo в моем предыдущем посте, поэтому я сделаю это здесь:

<code>package inventorydemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;


public class InventoryDemo {

public enum ErrorMsg {
    LOAD_ERR("Inventory Items have not been loaded in yet!"),
    NOT_ADMIN("Invalid Operation! Admin Status Required!"),
    ID_EXISTS("Invalid ID! That ID Already Exists!"),
    NAME_EXISTS("Invalid Item Name! That Name Already Exists!");

    String msg;

    ErrorMsg(String msg) {
        this.msg = msg;
    }

    public String msg() {
        return msg;
    }

}

private String encoding = "UTF-8"; // options: "US-ASCII", "UTF-8", "UTF-16"
public static List<InventoryItems> items = new ArrayList<>();
private boolean isInAdminMode = false;
private String dataFile = "";
private String ls = System.lineSeparator();


public static void main(String[] args) {
    // App is started this way to avoid the need for statics.
    new InventoryDemo().startApp(args);
}

private void startApp(String[] args) {
    if (!loadDataFile()) {
        System.err.println("Error Loading: " + dataFile);
        System.exit(0);
    }

    Scanner input = new Scanner(System.in);

    System.out.println("This code is run from the startApp() method" + ls 
                     + "located within the InventoryDemo class. Its" + ls
                     + "intent is to demonstrate the how the methods" + ls
                     + "withint this class function." );
    pressAnyKey(input);

    System.out.println("Available Inventory Items");
    System.out.println("=========================");
    String[] allItems = getAllInventoryItems();
    if (allItems != null) {
        for (String strg : allItems) {
            System.out.println(strg);
        }
    }

    pressAnyKey(input);

    showFormattedTable();

    pressAnyKey(input);

    System.out.println();
    System.out.println("Available Inventory Items (with formated ID & Name)");
    String header = String.format("%-7s %-26s", "ID", "Item Name");
    String topLine = String.join("", Collections.nCopies(header.length(), "="));
    String underline = String.join("", Collections.nCopies(header.length(), "-"));
    System.out.println(topLine);
    System.out.println(header);
    System.out.println(underline);
    allItems = getAllInventoryItems("%-7s %-26s");
    if (allItems != null) {
        for (String strg : allItems) {
            System.out.println(strg);
        }
    }
    System.out.println(topLine);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Record (by ID: 00004)");
    System.out.println("=========================================");
    String itemString = getItemString("00004");
    System.out.println(itemString);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific ID (by Name: Playstation 4 Pro)");
    System.out.println("===================================================");
    itemString = getItemID("Playstation 4 Pro");
    System.out.println(itemString);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Name (by ID: 00004)");
    System.out.println("=======================================");
    itemString = getItemName("00004");
    System.out.println(itemString);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Price (by ID: 00003)");
    System.out.println("========================================");
    double itemprice = getItemPrice("00003");
    System.out.println(itemprice);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Quantity (by ID: 00002)");
    System.out.println("===========================================");
    int itemQuant = getItemQuantity("00002");
    System.out.println(itemQuant);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Change Name for: 'Playstation 4 Pro' at ID: "
            + "'00003' TO 'Some Kinda Game-Box'");
    System.out.println("============================================"
            + "================================");
    itemString = getItemString("00003");
    System.out.println("Current Name: -->  " + itemString);
    setItemName("00003", "Some Kinda Game-Box");
    itemString = getItemString("00003");
    System.out.println("Name is Now:  -->  " + itemString);

    pressAnyKey(input);

    System.out.println();
    String itemToAdd = "00006/LG LED 60\" Television/70555.0/08";
    System.out.println("Add a new Inventory Item (duplicate ID's are not allowed).");
    System.out.println("Adding (with 'NO Auto-ID-Increment'): "
            + itemToAdd);
    System.out.println("======================================"
            + "======================================");
    if (addInventoryItem(itemToAdd)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not add (" + itemToAdd + ") to Records List!");
    }

    pressAnyKey(input);

    System.out.println();
    itemToAdd = "DYSON 430 Vacume/65437.0/6";
    System.out.println("Add a new Inventory Item (duplicate ID's are not allowed).");
    System.out.println("Adding (with 'Auto-ID-Increment'): "
            + itemToAdd);
    System.out.println("======================================"
            + "=======================");
    if (addInventoryItem(itemToAdd)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not add (" + itemToAdd + ") to Records List!");
    }

    pressAnyKey(input);

    System.out.println();
    System.out.println("Delete an Inventory Item ID (based on Item ID: 00006).");
    String itemIDToDelete = "00006";
    if (deleteInventoryItemID(itemIDToDelete)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not delete record ID (" + itemIDToDelete + ") from Records List!");
    }

    pressAnyKey(input);

    System.out.println();
    System.out.println("Delete an Inventory Item Name (based on Item Name: DYSON 430 Vacume).");
    String itemNameToDelete = "DYSON 430 Vacume";
    if (deleteInventoryItemName(itemNameToDelete)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not delete record Item Name (" + itemNameToDelete + ") from Records List!");
    }
}

private void showFormattedTable() {
    System.out.println();
    System.out.println("   Available Inventory Items (with formatting)");
    String header = String.format("%-7s %-26s %-8s %-5s", "ID", "Item Name", "Price", "Stock");
    String topLine = String.join("", Collections.nCopies(header.length(), "="));
    String underline = String.join("", Collections.nCopies(header.length(), "-"));
    System.out.println(topLine);
    System.out.println(header);
    System.out.println(underline);
    String[] allItems = getAllInventoryItems("%-7s %-26s $%-9s %-5s");
    if (allItems != null) {
        for (String strg : allItems) {
            System.out.println(strg);
        }
    }
    System.out.println(topLine);
}

/**
 * Deletes the Inventory Item in Records List and data file that contains the 
 * supplied Item ID.<br><br>
 * 
 * @param idToDelete (String) The ID Number of the record to delete.<br>
 * 
 * @return (Boolean) True if successful and False if not.
 */
public boolean deleteInventoryItemID(String idToDelete) {
    if (!isInAdminMode) {
        System.err.println(ErrorMsg.NOT_ADMIN.msg);
        return false;
    }
    if (items.isEmpty()) {
        System.err.println(ErrorMsg.LOAD_ERR.msg);
        return false;
    }
    for (int i = 0; i < items.size(); i++) {
        if (items.get(i).getId().equals(idToDelete)) {
            items.remove(i);
            break;
        }
    }
    refreshDataBase();
    return true;
}

/**
 * Deletes ALL Inventory Items in Records List and data file that contains the 
 * supplied Item Name.<br><br>
 * 
 * @param nameToDelete (String) The Item Name to delete (case insensitive).<br>
 * 
 * @return (Boolean) True if successful and False if not.
 */
public boolean deleteInventoryItemName(String nameToDelete) {
    if (!isInAdminMode) {
        System.err.println(ErrorMsg.NOT_ADMIN.msg);
        return false;
    }
    if (items.isEmpty()) {
        System.err.println(ErrorMsg.LOAD_ERR.msg);
        return false;
    }
    for (int i = 0; i < items.size(); i++) {
        if (items.get(i).getItemName().equalsIgnoreCase(nameToDelete)) {
            items.remove(i);
            i--;
        }
    }
    refreshDataBase();
    return true;
}

/**
 * Admin Rights required!<br><BR>
 * <p>
 * Adds a Inventory Item to the Records List and database file.<br><br>
 * This method can produce a unique ID string automatically if (and only if)
 * an ID value is <b>not</b> supplied within the Inventory Item string. If
 * an ID <b>is supplied</b> within the Inventory Item string then that ID
 * will be used <b>UNLESS</b> that particular ID already exists in which
 * case this method will not apply the addition and a message is displayed
 * to Console indicating as such.
 *
 * @param itemToAdd (String) The string to be supplied must be a forward
 *                  slash (<b>/</b>) delimited <b>String</b> consisting
 *                  consisting of the 4 data parts that make up any
 *                  particular Inventory Item:<pre>
 *
 *     1) The unique Item ID String (optional);
 *     2) The Item Name String;
 *     3) The Item Price (as a String);
 *     4) The Item Quantity (as a String).

* * Типичная строка элемента инвентаризации, предоставленная этому методу, должна выглядеть как: *
 *     "00006/LG LED 60\" Television/70555.0/08"

* * Или это может выглядеть (если запрашивается автоидентификация): *
 *     "LG LED 60\" Television/70555.0/08"

* * Предоставление дублирующих идентификаторов (идентификатор, который уже находится в файле базы данных или * Список записей) не допускается. * * @return (Boolean) True, если добавление прошло успешно, и False, если нет. * / publi c логический addInventoryItem (String itemToAdd) {if (! isInAdminMode) {System.err.println (ErrorMsg.NOT_ADMIN.msg); вернуть ложь; } try {String [] itemParts = itemToAdd.split ("\\ s {0,} / \\ s {0,}"); // Требуется ли автоматическое увеличение идентификатора? if (! itemParts [0] .matches ("\\ d +") && itemParts.length == 3) {// Да ... String newID = getUniqueID (); String [] parts = new String [4]; parts [0] = newID; parts [1] = itemParts [0]; parts [2] = itemParts [1]; parts [3] = itemParts [2]; itemParts = parts; } String id = itemParts [0]; if (doItemIDAlreadyExist (id)) {System.err.println ("Идентификатор элемента (" + id + ") представляет собой" + ErrorMsg.ID_EXISTS.msg); вернуть ложь; } String name = itemParts [1]; if (doItemNameAlreadyExist (name)) {System.err.println ("Имя элемента (" + name + ") является" + ErrorMsg.NAME_EXISTS.msg); вернуть ложь; } double price = Double.parseDouble (itemParts [2]); int quant = Integer.parseInt (itemParts [3]); items.add (новые InventoryItems (идентификатор, имя, цена, количество)); refreshDataBase (); } catch (Exception ex) {System.err.println (ex); вернуть ложь; } верните истину; } publi c boolean doesItemIDAlreadyExist (идентификатор строки) {boolean res = false; if (items.isEmpty ()) {res = false; } else {for (InventoryItems itms: items) {if (itms.getId (). equals (id)) {res = true; перемена; }}} return res; } publi c boolean doesItemNameAlreadyExist (String name) {boolean res = false; if (items.isEmpty ()) {res = false; } else {for (InventoryItems itms: items) {if (itms.getItemName (). equalsIgnoreCase (name)) {res = true; перемена; }}} return res; } publi c String getUniqueID () {if (items.isEmpty ()) {return "00001"; } int max = 0; for (InventoryItems itms: items) {String idVal = itms.getId (); if (! idVal.matches ("\\ d +")) {continue; } int val = Integer.parseInt (idVal); if (val> max) {max = val; }} if (max == 0) {return String.format ("% 5s", 1) .replace ('', '0'); } else {return String.format ("% 5s", (max + 1)). replace ('', '0'); }} publi c String [] getAllInventoryItems (String ... formatString) {if (items.isEmpty ()) {System.err.println (ErrorMsg.LOAD_ERR.msg); вернуть ноль; } String format = ""; if (formatString.length> 0) {format = formatString [0]; } String [] itms = new String [items.size ()]; for (int i = 0; i = 1) {// Фактическая строка целочисленных значений if (lineParts [0] .matches ("\\ d +")) {id = lineParts [0]; } if (lineParts.length> = 2) {// Содержит ли строка имя или является пустой. name = (lineParts [1] .equals ("")? "Unknown": lineParts [1]); if (lineParts.length> = 3) {// Это строка с целым или двойным / плавающим значением if (lineParts [2] .matches ("-? \\ d + (\\. \\ d +)?")) {цена = Double.parseDouble (lineParts [2]); } if (lineParts.length> = 4) {// Фактическая строка целочисленных значений if (lineParts [0] .matches ("\\ d +")) {quant = Integer.parseInt (lineParts [3]); }}}}} items.add (новые InventoryItems (идентификатор, имя, цена, количество)); } success = true; } catch (FileNotFoundException ex) {System.err.println (ex); успех = ложь; } catch (IOException ex) {System.err.println (ex); успех = ложь; } вернуть успех; } publi c логическое saveItemsToFile () {if (! isInAdminMode) {System.err.println (ErrorMsg.NOT_ADMIN.msg); вернуть ложь; } String header = String.format ("% - 8s% -27s% -10s% -5s% n", "ID", "Имя элемента", "Цена", "Акции"); try (PrintWriter writer = new PrintWriter (new OutputStreamWriter (новый FileOutputStream (dataFile), кодировка))) {writer.append (заголовок); for (int i = 0; i
*

* Этот метод вернет true, если предоставленный путь и имя файла уже * существуют. * * @param pathString Путь и файл для создания (если они еще не * существуют). * * @return Логическое значение true или false. Возвращает true, если создание было * успешным, и false, если не было успешным. * / publi c stati c логический createPathAndTextFile (String pathString) {if (pathString.isEmpty ()) {System.err.println ("createPathAndTextFile () - путь и созданный текстовый файл:" + false); вернуть ложь; } if (new File (pathString) .exists ()) {return true; } String pathToFile = новый файл (pathString) .getAbsolutePath (). Substring (0, новый файл (pathString) .getAbsolutePath (). LastIndexOf (File. разделитель)); String fileToCreate = новый файл (pathString) .getAbsolutePath (). Substring (новый файл (pathString) .getAbsolutePath (). LastIndexOf (File.separator) + 1); try {// Сделать путь к каталогам, если он еще не существует ... File dir = new File (pathToFile); if (! dir.exists ()) {dir.mkdirs (); } // Сделать текстовый файл ... File file = new File (dir, fileToCreate); FileWriter newFile = новый FileWriter (файл); newFile.close (); if (new File (pathString) .exists ()) {return true; }} catch (IOException ex) {System.err.println ("createPathAndTextFile () - Обнаружено исключение:" + System.lineSeparator () + ex.getMessage ()); } вернуть ложь; } publi c boolean isInAdminMode () {return isInAdminMode; } publi c void setIsInAdminMode (boolean isInAdminMode) {this.isInAdminMode = isInAdminMode; } publi c String getDataFilePath () {return dataFile; } publi c void setDataFilePath (String dataFile) {this.dataFile = dataFile; } publi c String getEncoding () {возврат кодировки; } publi c void setEncoding (String encoding) {this.encoding = encoding; } / ** * Удаляет (обрезает) начальные и конечные пробелы и удаляет * любые BOM (метки порядка байтов) из всех различных кодировок символов.

* * @param inputString (String) Строка Unicode удалить спецификации из.
* * @return (String) * / private stati c String trimBOMs (String inputString) {inputString = inputString.trim () .replaceAll ("\ uFEFF | \ uEFBBBF | \ uFFFE | \ u0000FEFF | \ uFFFE0000 | \ u2B2F7638 "," ") .replaceAll (" \ u2B2F7639 | \ u2B2F762B | \ u2B2F762F | \ u2B2F76382D | \ uF7644 C "," "\ uFEFF u36). | \ u84319533 "," "); return inputString; } private void pressAnyKey (вход сканера) {System.out.println (ls + "Нажмите клавишу Enter, чтобы продолжить (q, чтобы выйти) ..."); String anyKey = input.nextLine (); if (anyKey.toLowerCase (). equals ("q")) {System.exit (0); }}}

Существует много кода, который можно удалить из этого класса, если он фактически используется с приложением DB_ GUI.

1 голос
/ 24 апреля 2020

Я прошу прощения за задержку, однако у меня есть другие, более неотложные обязательства.

Как и было обещано, здесь приведена демонстрация того, как использовать методы, содержащиеся в классе InventoryDemo , для формы , аналогичной тому, что вы отображали в своем сообщении.

enter image description here

Это работающее демо-приложение работает быстро, поэтому не ожидайте никакой реальной оптимизации. Это будет зависеть от вас, когда вы создадите свое собственное приложение. Простота делает для лучшего понимания.

Демонстрация, которую можно запустить (названная DB_ GUI) ниже, использует классы, предоставленные в моем предыдущем посте :

  • InventoryItems Class ( InventoryItems. java)
  • InventoryDemo Class ( InventoryDemo. java)

В класс InventoryDemo были внесены очень незначительные изменения, и обновление было выполнено для этого кода в моем предыдущем посте .

. Этот работающий код работает следующим образом:

Вы начинаете с пустой базы данных (без текстовых файлов). Файлы текстовых данных создаются автоматически по мере необходимости, и каждый файл представляет определенную c категорию инвентаря, например: Письменные принадлежности , Игровые приставки и др. c. Эти категории создаются с помощью редактируемого JComboBox *1044*, расположенного в верхней части окна приложения. Если в этом JComboBox имеется категория, которая не уже содержится в комбинированном списке, то она добавляется в этот список и создается файл данных для подготовки к хранению предметов инвентаря, связанных с этой указанной c категорией .

Файлы данных создаются в каталоге с именем InventoryCategories , который автоматически создается в вашей локальной файловой системе в каталоге root диска, который является вашим конкретным приложение запущено Убедитесь, что для таких действий существуют соответствующие разрешения, прежде чем пытаться запустить это демонстрационное приложение.

Для создания категорий и редактирования, добавления, сохранения или удаления данных в полях JTextFields формы Admin Доступ должен быть должен быть получен. Единственный элемент данных, который может быть изменен обычным пользователем, - это поле Количество . Чтобы go перейти в режим администратора, выберите ссылку Admin , расположенную непосредственно под таблицей JTable. Вам будет необходимо ввести пароль, который в настоящее время 1234 . Вы можете изменить этот пароль на любой другой, изменив строковое значение, содержащееся в переменной поля класса ADMIN_PASSWORD в приведенном ниже коде.

В режиме администратора:

  • Чтобы отредактировать элемент инвентаризации, выберите его в таблице и затем отредактируйте все, что вам нравится, из JTextFields. Когда вы закончите редактирование и сохраните свою работу, нажмите кнопку Сохранить .
  • Чтобы добавить элемент инвентаризации в текущую активную категорию, нажмите кнопку Добавить . Все JTextField's очистятся. Укажите необходимые данные в JTextFields формы, затем, когда закончите, нажмите кнопку Сохранить . Эта запись будет сохранена (добавлена) в соответствующий файл данных и помещена в JTable. Предоставление элемента ID является необязательным, поскольку, если он не указан, будет автоматически создан идентификатор с идентификатором запуска 00001 . Вы не можете предоставить повторяющиеся значения идентификатора в одной и той же категории.
  • Чтобы удалить элемент инвентаря из текущей активной категории, выберите нужный элемент инвентаря в JTable, элемент будет отображаться в полях JTextFields, расположенных в нижняя часть формы. Выберите кнопку Удалить . Появится диалоговое окно подтверждения, нажмите кнопку Да , чтобы подтвердить удаление, и элемент инвентаря будет удален как из файла данных, так и из таблицы JTable.

Для отключения режима администратора :

Просто выберите ссылку Admin , расположенную в нижней части JTable. Эта ссылка переключает на go вход и выход из режима администратора.

Код приложения:

/*
Data text file names are based from the names of the categoryies 
created in Form. If a 'Writing Instruments' category is created 
then the data file created for that category's date will be named: 

                  Writing Instruments.txt

If a 'Game Consoles' category is created then the data file created 
for that category's date will be named: 

                     Game Consoles.txt

and so on. Categories are created by entering a specific category 
name (that DOES NOT already exist) into the Categories Drop-Down 
List (comboBox).
*/
package inventorydemo;

import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;



public class DB_GUI extends javax.swing.JFrame {

    private static final long serialVersionUID = 1L;
    private final InventoryDemo demo = new InventoryDemo();
    private final String ADMIN_PASSWORD = "1234";
    private boolean appStarted = false;

public DB_GUI() {
    initComponents();

    fillCategoriesCombo();
    categoryComboBox.setSelectedIndex(-1);

    // Set the JTable's Header font size to match the JTable's font size.
    JTableHeader header = jTable1.getTableHeader();
    header.setFont(header.getFont().deriveFont((float) jTable1.getFont().getSize()));

    // Center Text in JTable Header Cells.
    alignJTableHeaderText(jTable1, 0);

    // Set JTable's Column Widths
    setJTableColumnWidths(jTable1, 13d, 62d, 15d, 10d);

    // Set JTable's background color to White.
    jTable1.setFillsViewportHeight(true);
    jScrollPane1.getViewport().setBackground(Color.white);

    // Modifying the Look & Feel
    // Set JTable Header Background color to White.
    UIManager.getDefaults().put("TableHeader.background", Color.WHITE);
    // Remove JTable Header borders
    UIManager.getDefaults().put("TableHeader.cellBorder", BorderFactory.createEmptyBorder(0, 0, 0, 0));
    // Set JTextField's inactive background color to White.
    UIManager.getDefaults().put("TextField.inactiveBackground", Color.WHITE);

    // Key Binding for Category Combo. Passes what was entered to 
    // the addNewCategory() method when the ENTER key is pressed.
    // Used to add new Categories.
    categoryComboBox.getEditor().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (demo.isInAdminMode()) {
                addNewCategory(categoryComboBox.getEditor().getItem().toString());
            }
            else {
                JFrame iFrame = new JFrame();
                iFrame.setAlwaysOnTop(true); 
                iFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                iFrame.setLocationRelativeTo(null);
                JOptionPane.showMessageDialog(iFrame, "You need Admin Access to "
                        + "create categories!", "Admin Required!", JOptionPane.WARNING_MESSAGE);
                iFrame.dispose();
            }
        }
    });

    // Center text in ComboBox.
    ((JLabel) categoryComboBox.getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);

    // Set startup focus to the Admin link.
    lblAdminAccess.requestFocus();
    appStarted = true;
}

@SuppressWarnings("unchecked")
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jSeparator1 = new javax.swing.JSeparator();
    productNameBox = new javax.swing.JTextField();
    categoryComboBox = new javax.swing.JComboBox<>();
    jLabel3 = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JSeparator();
    productIDBox = new javax.swing.JTextField();
    jSeparator5 = new javax.swing.JSeparator();
    productPriceBox = new javax.swing.JTextField();
    jSeparator6 = new javax.swing.JSeparator();
    productQuantityBox = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTable1 = new javax.swing.JTable();
    saveButton = new javax.swing.JButton();
    doneButton = new javax.swing.JButton();
    deleteButton = new javax.swing.JButton();
    addButton = new javax.swing.JButton();
    lblAdminAccess = new javax.swing.JLabel();
    lblStatus = new javax.swing.JLabel();
    jSeparator3 = new javax.swing.JSeparator();
    jSeparator4 = new javax.swing.JSeparator();
    lblItems = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setAlwaysOnTop(true);
    setResizable(false);

    jPanel1.setBackground(new java.awt.Color(255, 255, 255));

    jLabel1.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
    jLabel1.setText("Product ID:");
    jLabel1.setToolTipText("");

    jLabel2.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
    jLabel2.setText("Price:");
    jLabel2.setToolTipText("");

    jSeparator1.setBackground(new java.awt.Color(255, 51, 51));
    jSeparator1.setForeground(new java.awt.Color(255, 0, 0));
    jSeparator1.setToolTipText("");
    jSeparator1.setName(""); // NOI18N
    jSeparator1.setOpaque(true);
    jSeparator1.setRequestFocusEnabled(false);
    jSeparator1.setVerifyInputWhenFocusTarget(false);

    productNameBox.setEditable(false);
    productNameBox.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
    productNameBox.setForeground(new java.awt.Color(153, 153, 153));
    productNameBox.setHorizontalAlignment(javax.swing.JTextField.CENTER);
    productNameBox.setToolTipText("");
    productNameBox.setBorder(null);
    productNameBox.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    productNameBox.setDisabledTextColor(new java.awt.Color(153, 153, 153));
    productNameBox.setSelectionColor(new java.awt.Color(204, 204, 204));

    categoryComboBox.setBackground(new java.awt.Color(255, 255, 255));
    categoryComboBox.setEditable(true);
    categoryComboBox.setForeground(new java.awt.Color(51, 51, 255));
    categoryComboBox.setAutoscrolls(true);
    categoryComboBox.setBorder(null);
    categoryComboBox.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            categoryComboBoxItemStateChanged(evt);
        }
    });

    jLabel3.setFont(new java.awt.Font("sansserif", 1, 12)); // NOI18N
    jLabel3.setText("Quantity:");

    jSeparator2.setBackground(new java.awt.Color(255, 51, 51));
    jSeparator2.setForeground(new java.awt.Color(255, 0, 0));
    jSeparator2.setToolTipText("");
    jSeparator2.setName(""); // NOI18N
    jSeparator2.setOpaque(true);
    jSeparator2.setRequestFocusEnabled(false);
    jSeparator2.setVerifyInputWhenFocusTarget(false);

    productIDBox.setEditable(false);
    productIDBox.setForeground(new java.awt.Color(153, 153, 153));
    productIDBox.setToolTipText("");
    productIDBox.setBorder(null);

    jSeparator5.setBackground(new java.awt.Color(255, 51, 51));
    jSeparator5.setForeground(new java.awt.Color(255, 0, 0));
    jSeparator5.setToolTipText("");
    jSeparator5.setName(""); // NOI18N
    jSeparator5.setOpaque(true);
    jSeparator5.setRequestFocusEnabled(false);
    jSeparator5.setVerifyInputWhenFocusTarget(false);

    productPriceBox.setEditable(false);
    productPriceBox.setForeground(new java.awt.Color(153, 153, 153));
    productPriceBox.setBorder(null);

    jSeparator6.setBackground(new java.awt.Color(255, 51, 51));
    jSeparator6.setForeground(new java.awt.Color(255, 0, 0));
    jSeparator6.setToolTipText("");
    jSeparator6.setName(""); // NOI18N
    jSeparator6.setOpaque(true);
    jSeparator6.setRequestFocusEnabled(false);
    jSeparator6.setVerifyInputWhenFocusTarget(false);

    productQuantityBox.setForeground(new java.awt.Color(0, 0, 255));
    productQuantityBox.setBorder(null);

    jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
    jScrollPane1.setBorder(null);
    jScrollPane1.setViewportBorder(null);
    jScrollPane1.setOpaque(true);

    jTable1.setBorder(null);
    jTable1.setFont(new java.awt.Font("sansserif", 0, 11)); // NOI18N
    jTable1.setForeground(new java.awt.Color(102, 102, 102));
    jTable1.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null},
            {null, null, null, null}
        },
        new String [] {
            "ID", "Product Name", "Price", "Qty"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.Double.class, java.lang.Integer.class
        };
        boolean[] canEdit = new boolean [] {
            false, false, false, false
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    jTable1.setFillsViewportHeight(true);
    jTable1.setGridColor(new java.awt.Color(255, 255, 255));
    jTable1.setOpaque(false);
    jTable1.setSelectionBackground(new java.awt.Color(204, 204, 204));
    jTable1.setSelectionForeground(new java.awt.Color(0, 0, 0));
    jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            jTable1MouseClicked(evt);
        }
    });
    jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(java.awt.event.KeyEvent evt) {
            jTable1KeyReleased(evt);
        }
    });
    jScrollPane1.setViewportView(jTable1);

    saveButton.setText("Save");
    saveButton.setEnabled(false);
    saveButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            saveButtonActionPerformed(evt);
        }
    });

    doneButton.setText("Done");
    doneButton.setToolTipText("");
    doneButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            doneButtonActionPerformed(evt);
        }
    });

    deleteButton.setText("Delete");
    deleteButton.setToolTipText("");
    deleteButton.setEnabled(false);
    deleteButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            deleteButtonActionPerformed(evt);
        }
    });

    addButton.setText("Add");
    addButton.setToolTipText("");
    addButton.setEnabled(false);
    addButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            addButtonActionPerformed(evt);
        }
    });

    lblAdminAccess.setFont(new java.awt.Font("sansserif", 0, 10)); // NOI18N
    lblAdminAccess.setForeground(java.awt.Color.blue);
    lblAdminAccess.setText("<html><u>Admin</u></html>");
    lblAdminAccess.setToolTipText("<html> Turn Admin Mode: <font color=red>ON</font> </html> ");
    lblAdminAccess.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    lblAdminAccess.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            lblAdminAccessMouseClicked(evt);
        }
    });

    lblStatus.setBackground(new java.awt.Color(255, 255, 255));
    lblStatus.setFont(new java.awt.Font("sansserif", 0, 11)); // NOI18N
    lblStatus.setForeground(new java.awt.Color(102, 102, 102));
    lblStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    lblStatus.setText("<html>Add or select a product category (Admin required to add).</html>");
    lblStatus.setToolTipText("");
    lblStatus.setBorder(null);
    lblStatus.setOpaque(true);

    jSeparator3.setBackground(new java.awt.Color(0, 153, 153));
    jSeparator3.setToolTipText("");

    jSeparator4.setBackground(new java.awt.Color(0, 153, 153));
    jSeparator4.setToolTipText("");

    lblItems.setFont(new java.awt.Font("sansserif", 0, 11)); // NOI18N
    lblItems.setText("<html>Items: <font color=blue>0</font></html>");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(50, 50, 50)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE))
                    .addGap(32, 32, 32)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(productIDBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(productPriceBox, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(productQuantityBox, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(productNameBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addComponent(lblStatus)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(lblItems, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblAdminAccess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(28, 28, 28)
                            .addComponent(categoryComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(30, 30, 30)
                            .addComponent(saveButton)
                            .addGap(18, 18, 18)
                            .addComponent(addButton)
                            .addGap(18, 18, 18)
                            .addComponent(deleteButton)
                            .addGap(18, 18, 18)
                            .addComponent(doneButton)))
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
        .addComponent(jSeparator3)
        .addComponent(jSeparator4)
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(12, 12, 12)
            .addComponent(categoryComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(lblAdminAccess, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(lblItems, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(4, 4, 4)
            .addComponent(productNameBox, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(24, 24, 24)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addGap(18, 18, 18)
                    .addComponent(jLabel2)
                    .addGap(18, 18, 18)
                    .addComponent(jLabel3))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                    .addComponent(productIDBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(productPriceBox, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator5, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(productQuantityBox, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jSeparator6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(18, 18, 18)
            .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(saveButton)
                .addComponent(doneButton)
                .addComponent(deleteButton)
                .addComponent(addButton))
            .addGap(11, 11, 11)
            .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(lblStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
    setLocationRelativeTo(null);
}

Поскольку код такой большой, я предоставляю его в двух постах. Просто скопируйте / вставьте код в следующий пост прямо под этим кодом.

1 голос
/ 24 апреля 2020

Оставшийся код для поста ниже:

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
    fillProductBoxes();
    lblStatus.setText("<html><center>View or edit fields.</center></html>");
}                                    

private void lblAdminAccessMouseClicked(java.awt.event.MouseEvent evt) {                                            
    // Admin label foreground color is Blue
    if (lblAdminAccess.getForeground().getRGB() == -16776961) {
        lblStatus.setText("<html><center>Provide Admin Password!</center></html>");
        String passWrd = JOptionPane.showInputDialog(this, "<html>Please provide "
                + "your <font color=magenta>Admin</font> Password:<br><br></html>",
                "Admin Password", JOptionPane.PLAIN_MESSAGE);
        if (passWrd == null) {
            lblStatus.setText("");
            return;
        }
        if (!passWrd.equals(ADMIN_PASSWORD)) {
            lblStatus.setText("<html><center>Invalid Admin password supplied!</center></html>");
            JOptionPane.showMessageDialog(this, "<html><center><b>You have supplied an Invalid "
                                        + "Password!</b></center><br></html>",
                                        "Invalid Password!", JOptionPane.ERROR_MESSAGE);
            return;
        }
        lblAdminAccess.setForeground(Color.MAGENTA);
        lblAdminAccess.setToolTipText("<html> Turn Admin Mode: <font color=red>OFF</font> </html>");
        demo.setIsInAdminMode(true);
        setFormForAdminEditing(true);
        lblStatus.setText("<html><center>In Admin Mode!</center></html>");
    }

    else {
        lblAdminAccess.setForeground(Color.BLUE);
        lblAdminAccess.setToolTipText("<html> Turn Admin Mode: <font color=red>ON</font> </html>");
        setFormForAdminEditing(false);
        demo.setIsInAdminMode(false);
        lblStatus.setText("<html><center>Released from Admin Mode!</center></html>");
    }

}                                           

private void doneButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    System.exit(0);
}                                          

private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (productNameBox.getText().equals("")
            || productPriceBox.getText().equals("")
            || productQuantityBox.getText().equals("")) {
        lblStatus.setText("<html><center><b>A required field is empty!</b></center></html>");
        JOptionPane.showMessageDialog(this, "<html>A required field is empty! All fields<br>"
                + "(except the <font color=blue>ID</font> field) must be "
                + "supplied!<br><br><font size='2'><center>The "
                + "<font color=red>ID</font> field is optional."
                + "</center></font><br><br></html>", "Field Empty!",
                JOptionPane.WARNING_MESSAGE);
        return;
    }

    // If it's just an edit...
    if (!InventoryDemo.items.isEmpty() && jTable1.getSelectedRow() != -1 && 
            productIDBox.getText().equals(InventoryDemo.items.get(jTable1.getSelectedRow()).getId())) {
        InventoryDemo.items.get(jTable1.getSelectedRow()).setItemName(productNameBox.getText());
        if (productIDBox.getText().equals("")) {
            productIDBox.setText(demo.getUniqueID());
        }
        else {
            productIDBox.setText(String.format("%5s", productIDBox.getText()).replace(' ', '0'));
        }
        InventoryDemo.items.get(jTable1.getSelectedRow()).setId(productIDBox.getText());
        InventoryDemo.items.get(jTable1.getSelectedRow()).setPrice(Double.parseDouble(productPriceBox.getText()));
        InventoryDemo.items.get(jTable1.getSelectedRow()).setQuantity(Integer.parseInt(productQuantityBox.getText()));
        demo.refreshDataBase();
        lblItems.setText("<html>Items: <font color=blue>" + fillJTableFromList(jTable1) + "</font></html>");
        lblStatus.setText("<html><b><center><font color=red>Item Saved!</font></center></b></html>");
        return;
    }

    else if (!productIDBox.getText().equals("") && demo.getItemName(productIDBox.getText()) != null) {
        String existingItemName = demo.getItemName(productIDBox.getText());
        lblStatus.setText("<html><center><b>Item ID Already Exists In Database!</b></center></html>");
        int res = JOptionPane.showConfirmDialog(this, "<html>The ID supplied already "
                + "exists for another product item<br>named:<br><center><font color=blue>"
                + existingItemName + "</font></center><br>You can not change an ID of "
                + "this particualar product unless<br>the ID is <b>unique</b> (does not "
                + "already exist).<br><br><center>Do you want to auto-generate a unique "
                + "ID?</center><br><br></html>", "Invalid ID Supplied",
                JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

        if (res != JOptionPane.YES_OPTION) {
            return;
        }
        // Set a Unique ID number
        productIDBox.setText(demo.getUniqueID());
    }

    // Get a unique ID number if one isn't provided.
    if (productIDBox.getText().equals("")) {
        productIDBox.setText(demo.getUniqueID());
    }
    else {
        // Make sure the Product ID has the proper 0 padding (for example: 00012).
        productIDBox.setText(String.format("%5s", productIDBox.getText()).replace(' ', '0'));
    }

    demo.addInventoryItem(new StringBuffer("").append(productIDBox.getText()).append("/")
            .append(productNameBox.getText()).append("/")
            .append(productPriceBox.getText()).append("/")
            .append(productQuantityBox.getText()).toString());
    demo.refreshDataBase();
    lblItems.setText("<html>Items: <font color=blue>" + fillJTableFromList(jTable1) + "</font></html>");
    lblStatus.setText("<html><b><center><font color=red>Item Saved!</font></center></b></html>");
}                                          

private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    clearFields();
    productNameBox.requestFocus();
    lblStatus.setText("<html><center>Add desired Item (ID is optional).</center></html>");
}                                         

private void categoryComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {                                                  
    // Ignore firings when combo is getting filled.
    if (!appStarted) {
        return;
    }
    String selected = categoryComboBox.getSelectedItem().toString();
    if (selected == null || selected.equals("")) {
        return;
    }
    // If an attempt is made to create a category without admin rights
    if (!demo.isInAdminMode() && !new File("/InventoryCategories/" + selected + ".txt").exists()) {
        return;
    }
    demo.setDataFilePath("/InventoryCategories/" + selected + ".txt");
    clearFields();
    clearJTable(jTable1);
    if (demo.loadDataFile()) {
        lblItems.setText("<html>Items: <font color=blue>" + fillJTableFromList(jTable1) + "</font></html>");
        lblStatus.setText("<html><center>View or edit desired Item.</center></html>");
    }
    else {
        lblStatus.setText("<html>Loading of data file (<font color=red>" + selected + ".txt</font>) failed to carry out!</html>");
    }
}                                                 

private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {                                    
    if ((evt.getKeyCode() == KeyEvent.VK_DOWN || 
                            evt.getKeyCode() == KeyEvent.VK_UP) && 
                            jTable1.getRowCount() >= 0) {
        fillProductBoxes();
        lblStatus.setText("<html><center>View or edit fields.</center></html>");
    }
}                                   

private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    if (InventoryDemo.items.isEmpty()) {
        JOptionPane.showMessageDialog(this, "There are no Inventory Items to delete!", 
                                      "Nothing To Delete", JOptionPane.INFORMATION_MESSAGE);
    }
    else if (jTable1.getSelectedRow() == -1) {
        JOptionPane.showMessageDialog(this, "There is no Inventory Item Selected To Delete!", 
                                      "Nothing Selected To Delete", JOptionPane.INFORMATION_MESSAGE);
    }
    else if (JOptionPane.showConfirmDialog(this, "<html>Are you sure you want "
                + "to delete the item:<br><br><font color=blue><b><center>" + 
                InventoryDemo.items.get(jTable1.getSelectedRow()).getItemName() + 
                "</b></font><br><center>from database for this Category?" + "<br><br><font size='2'>"
                + "<center>There is no <b>Undo</b> for this action!</font><br><br></html>", 
                "Delete Record?", JOptionPane.YES_NO_OPTION, 
                JOptionPane.QUESTION_MESSAGE) != JOptionPane.YES_OPTION) {
    }
    else {
        InventoryDemo.items.remove(jTable1.getSelectedRow());
        demo.refreshDataBase();
        clearFields();
        lblItems.setText("<html>Items: <font color=blue>" + fillJTableFromList(jTable1) + "</font></html>");
        lblStatus.setText("<html><center><b>Item Deleted!</b></center></html>");
    }
}                                            

private void addNewCategory(String categoryName) {
    if (!demo.isInAdminMode()) {
        lblStatus.setText("<html<center><b>Admin rights required!</b></center></html>");
        JOptionPane.showMessageDialog(this, "<html>You must have <b>Administrator Rights</b> to add<br>"
                + "Categories to the database!<br><br></html>", "Admin Required!",
                JOptionPane.WARNING_MESSAGE);
        categoryComboBox.getEditor().setItem("");
        return;
    }
    String dataFileName = "/InventoryCategories/" + categoryName.trim() + ".txt";
    if (new File(dataFileName).exists()) {
        lblStatus.setText("<html><center><b>Category Already Exists!</b></center></html>");
        JOptionPane.showMessageDialog(this, "The Category named '" + categoryName
                + "' already exits!", "New Category Error!", JOptionPane.WARNING_MESSAGE);
        return;
    }
    else {
        lblStatus.setText("");
        int res = JOptionPane.showConfirmDialog(this, "<html>The Category named "
                + "'<font color=blue>" + categoryName + "</font>' does not exist."
                + "<br><br><center>Do you want to create it?</center><br><br></html>",
                "Create Category?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (res != JOptionPane.YES_OPTION) {
            return;
        }
        else {
            demo.setDataFilePath(dataFileName);
        }
    }

    lblStatus.setText("<html>New category named <font color=blue>" + categoryName
            + "</font> was created.</html>");
    categoryComboBox.addItem(categoryName);
    categoryComboBox.revalidate(); categoryComboBox.repaint();
    categoryComboBox.setSelectedItem(categoryName);
    demo.loadDataFile();
}

private void clearFields() {
    productNameBox.setText("");
    productIDBox.setText("");
    productPriceBox.setText("");
    productQuantityBox.setText("");
}

private void setFormForAdminEditing(boolean onOff) {
    productNameBox.setEditable(onOff);
    productIDBox.setEditable(onOff);
    productPriceBox.setEditable(onOff);
    saveButton.setEnabled(onOff);
    addButton.setEnabled(onOff);
    deleteButton.setEnabled(onOff);

    if (onOff) {
        productNameBox.setForeground(Color.BLUE);
        productIDBox.setForeground(Color.BLUE);
        productPriceBox.setForeground(Color.BLUE);
        productNameBox.requestFocus();
    }
    else {
        productNameBox.setForeground(Color.GRAY);
        productIDBox.setForeground(Color.GRAY);
        productPriceBox.setForeground(Color.GRAY);
        jTable1.requestFocus();
    }

}

public static void main(String args[]) {
    new DB_GUI().startApp(args);
}

private void startApp(String[] args) {
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new DB_GUI().setVisible(true);
        }
    });


}

@SuppressWarnings("unchecked")
private void fillCategoriesCombo() {
    File files = new File("/InventoryCategories");
    if (!files.exists()) {
        return;
    }

    final List<String> values = new ArrayList<>();
    String[] categories = getFilesListFromDirectory("/InventoryCategories", true);
    values.addAll(Arrays.asList(categories));
    categoryComboBox.setModel(new DefaultComboBoxModel(values.toArray()));
}

private int fillJTableFromList(JTable table) {
    clearJTable(jTable1);

    if (InventoryDemo.items.isEmpty()) {
        JOptionPane.showMessageDialog(this, "<html>There are currently no inventory "
                              + "items<br>for this category!<br><br></html>", 
                              "No Inventory", JOptionPane.INFORMATION_MESSAGE);
        return 0;
    }

    DefaultTableModel model = (DefaultTableModel) table.getModel();
    int recordCount = 0;
    table.removeAll();

    // Clear current table rows
    while (model.getRowCount() > 0) {
        for (int i = 0; i < model.getRowCount(); i++) {
            model.removeRow(i);
        }
    }

    // Fill the JTable Model.
    Object[] dataArray = new Object[4];
    for (int i = 0; i < InventoryDemo.items.size(); i++) {
        dataArray[0] = InventoryDemo.items.get(i).getId();
        dataArray[1] = InventoryDemo.items.get(i).getItemName();
        dataArray[2] = InventoryDemo.items.get(i).getPrice();
        dataArray[3] = InventoryDemo.items.get(i).getQuantity();
        model.addRow(dataArray);
        recordCount++;
    }
    return recordCount;

}

private void fillProductBoxes() {
    int selRow = jTable1.getSelectedRow();
    if (selRow < 0) {
        return;
    }
    String id = (String) jTable1.getValueAt(selRow, 0);
    String name = (String) jTable1.getValueAt(selRow, 1);
    String price = String.valueOf(jTable1.getValueAt(selRow, 2));
    String qty = String.valueOf(jTable1.getValueAt(selRow, 3));

    productNameBox.setText(name);
    productIDBox.setText(id);
    productPriceBox.setText(price);
    productQuantityBox.setText(qty);
}

/**
 * Returns a String Array containing all the file names that are contained
 * within the supplied folder (directory) path. This method does not check
 * nested folders. Sub-Folders are ignored during the process.<br><br>
 * <p>
 * The file names string array that is returned can be made to return the
 * file names with name extensions removed if the optional
 * removeFileExtension parameter is supplied a boolean true.<br>
 *
 * @param directoryPath       (String) The directory to get file names
 *                            from.<br>
 *
 * @param removeFileExtension (Optional - Boolean - Default is False) Read
 *                            above information.<br>
 *
 * @return (1D String Array) A String Array containing all the file names
 *         found within the supplied folder path.
 */
public static String[] getFilesListFromDirectory(String directoryPath, boolean... removeFileExtension) {
    File file = new File(directoryPath);
    if (!file.isDirectory()) {
        System.err.println("getFilesListFromDirectory() Method Error! "
                + "The supplied directoy path does not lead to a directory!"
                + System.lineSeparator() + "(" + directoryPath + ")"
                + System.lineSeparator());
        return null;
    }
    boolean noExtension = false;
    if (removeFileExtension.length > 0) {
        noExtension = removeFileExtension[0];
    }
    String[] files = file.list();
    ArrayList<String> list = new ArrayList<>();
    for (String string : files) {
        if (new File(file.getPath() + File.separator + string).isFile()) {
            if (noExtension) {
                if (string.lastIndexOf(".") > 0) {
                    if (string.split("\\.\\.").length > 1) {
                        list.add(string);
                    }
                    else {
                        list.add(string.substring(0, string.lastIndexOf(".")));
                    }
                }
                else {
                    list.add(string);
                }
            }
            else {
                list.add(string);
            }
        }
    }
    return list.toArray(new String[0]);
}

public static void clearJTable(JTable theTable) {
    DefaultTableModel dtm = (DefaultTableModel) theTable.getModel();
    while (dtm.getRowCount() > 0) {
        for (int i = 0; i < dtm.getRowCount(); i++) {
            dtm.removeRow(i);
        }
    }
}

public static void alignJTableHeaderText(JTable theTable, int alignType) {
    // Alignment options are: Align_LEFT (2), Align_CENTER (0), Align_RIGHT (4),
    // Align_LEADING (10), or Align_TRAILING (11)
    for (int i = 0; i < theTable.getColumnCount(); i++) {
        theTable.getTableHeader().getColumnModel().getColumn(i)
                .setHeaderRenderer(new HeaderRenderer(theTable, alignType));
    }
}

/**
 * Set the pixel widths for the supplied Table Columns by way of
 * percentage.<br><br>
 *
 * @param table            (JTable) The JTable variable name.<br>
 *
 * @param widthPercentages (Double) Double values need to be supplied.
 *                         Consider the JTable being a width of 100%. When
 *                         supplying width percentages for all columns then
 *                         the sum of all percentages supplied should equal
 *                         100% (although not absolutely necessary).
 */
public static void setJTableColumnWidths(JTable table, double... widthPercentages) {
    int tablePreferredWidth = table.getParent().getSize().width; //.getPreferredSize().width;
    double total = 0;
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
        total += widthPercentages[i];
    }

    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
        TableColumn column = table.getColumnModel().getColumn(i);
        column.setPreferredWidth((int) (tablePreferredWidth * (widthPercentages[i] / total)));
    }
}


// Variables declaration - do not modify                     
private javax.swing.JButton addButton;
private javax.swing.JComboBox<String> categoryComboBox;
private javax.swing.JButton deleteButton;
private javax.swing.JButton doneButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JSeparator jSeparator4;
private javax.swing.JSeparator jSeparator5;
private javax.swing.JSeparator jSeparator6;
private javax.swing.JTable jTable1;
private javax.swing.JLabel lblAdminAccess;
private javax.swing.JLabel lblItems;
private javax.swing.JLabel lblStatus;
private javax.swing.JTextField productIDBox;
private javax.swing.JTextField productNameBox;
private javax.swing.JTextField productPriceBox;
private javax.swing.JTextField productQuantityBox;
private javax.swing.JButton saveButton;
// End of variables declaration                   
}

Renderer SubClass ***">
class HeaderRenderer implements TableCellRenderer {

DefaultTableCellRenderer renderer;
int horAlignment;

public HeaderRenderer(JTable table, int horizontalAlignment) {
    horAlignment = horizontalAlignment;
    renderer = (DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer();
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int row, int col) {
    Component c = renderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
    JLabel label = (JLabel) c;
    label.setHorizontalAlignment(horAlignment);
    return label;
}
}
1 голос
/ 21 апреля 2020

Поскольку строки данных вашего файла (записи данных) отформатированы заданным c способом с различным интервалом, вы должны обрезать любые начальные или конечные пробелы из столбчатых данных, поскольку они считываются, чтобы помещаться в JTable. В настоящее время вы разделяете каждую строку файла данных с помощью:

String[] dataRow = line.split("/"); 

Это не удалит все отступы, примененные к каждому столбцу данных, который был помещен в эти данные, когда они были отформатированы и сохранены в файл. , Это заполнение необходимо будет обработать (удалить), когда вам действительно нужно работать с этими данными. Гораздо лучше удалить все эти пробелы, когда вы выполняете разбиение, например:

String[] dataRow = line.split("\\s{0,}/\\s{0,}");

Вы раскрыли очень мало информации относительно того, что ваше конкретное приложение действительно содержит как типы данных ( хотя большинство из них очевидно), то, что уже создано (классы, переменные-члены / экземпляры, поля, статика и т. д. c), код, используемый для сохранения ваших данных из JTable в файл, и т. д. c, и т. c. Поэтому все работы остаются открытыми для предположений или 101 вопроса, которые я, в частности, не буду задавать. Из-за этого приведенный ниже код будет базироваться c и более ориентирован на систему инвентаризации в стиле консоли, а не на систему GUI. Вам нужно будет применить код к указанным c областям вашего приложения, где вы считаете нужным.

Для начала вам нужен класс Items . Поскольку каждый элемент инвентаря содержит определенные c атрибуты, такие как ID , Имя элемента , Цена и Количество (на складе), вам нужны средства для хранения этих данных в памяти, чтобы с ними можно было работать так, чтобы любой фрагмент данных можно было быстро получить и обработать. Ваш класс может выглядеть следующим образом:

public class InventoryItems {

    private String id;
    private String itemName;
    private double price;
    private int quantity;

    public InventoryItems() {    }

    public InventoryItems(String id, String itemName, double price, int quantity) {
        this.id = id;
        this.itemName = itemName;
        this.price = price;
        this.quantity = quantity;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return new StringBuffer("").append("ID: ").append(id).append(", Item Name: ")
                                   .append(itemName).append(", Price: $").append(price)
                                   .append(", Quantity: ").append(quantity).toString();
    }

    /**
     * Returns instance data as a String in the format specified in your supplied 
     * format string.
     * 
     * @param formatString
     * @return
    */
    public String toString(String formatString) {
        if (formatString == null || formatString.equals("")) {
            return toString();
        }
        // String Format Specifiers must be separated 
        // with a single white-space.
        switch (formatString.split("\\s+").length) {
            case 1:
                return String.format(formatString, id);
            case 2:
                return String.format(formatString, id, itemName);
            case 3:
                return String.format(formatString, id, itemName, price);
            case 4:
                return String.format(formatString, id, itemName, price, quantity);
            default:
                return toString();
        }
    }
}

Теперь вам нужны вспомогательные методы для: загрузки данных вашего файла (записи инвентаризации), получения определенной c записи, получения определенных c атрибутов элемента, сохранения указанных c атрибуты элемента, сохранение записей и т. Д. c, и т. Д. c. Эти методы могут выглядеть следующим образом:

<code>import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;


public class InventoryDemo {

public enum ErrorMsg {
    LOAD_ERR("Inventory Items have not been loaded in yet!"),
    NOT_ADMIN("Invalid Operation! Admin Status Required!"),
    ID_EXISTS("Invalid ID! That ID Already Exists!"),
    NAME_EXISTS("Invalid Item Name! That Name Already Exists!");

    private String msg;

    ErrorMsg(String msg) {
        this.msg = msg;
    }

    public String msg() {
        return msg;
    }

}

private String encoding = "UTF-8"; // options: "US-ASCII", "UTF-8", "UTF-16"
private final List<InventoryItems> items = new ArrayList<>();
private boolean isInAdminMode = true;
private String dataFile = "InventoryItems.txt";
private String ls = System.lineSeparator();

public static void main(String[] args) {
    // App is started this way to avoid the need for statics.
    new InventoryDemo().startApp(args);
}

private void startApp(String[] args) {
    if (!loadDataFile()) {
        System.err.println("Error Loading: " + dataFile);
        System.exit(0);
    }

    Scanner input = new Scanner(System.in);

    System.out.println("This code is run from the startApp() method" + ls 
                     + "located within the InventoryDemo class. Its" + ls
                     + "intent is to demonstrate the how the methods" + ls
                     + "withint this class function." );
    pressAnyKey(input);

    System.out.println("Available Inventory Items");
    System.out.println("=========================");
    String[] allItems = getAllInventoryItems();
    if (allItems != null) {
        for (String strg : allItems) {
            System.out.println(strg);
        }
    }

    pressAnyKey(input);

    showFormattedTable();

    pressAnyKey(input);

    System.out.println();
    System.out.println("Available Inventory Items (with formated ID & Name)");
    String header = String.format("%-7s %-26s", "ID", "Item Name");
    String topLine = String.join("", Collections.nCopies(header.length(), "="));
    String underline = String.join("", Collections.nCopies(header.length(), "-"));
    System.out.println(topLine);
    System.out.println(header);
    System.out.println(underline);
    allItems = getAllInventoryItems("%-7s %-26s");
    if (allItems != null) {
        for (String strg : allItems) {
            System.out.println(strg);
        }
    }
    System.out.println(topLine);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Record (by ID: 00004)");
    System.out.println("=========================================");
    String itemString = getItemString("00004");
    System.out.println(itemString);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific ID (by Name: Playstation 4 Pro)");
    System.out.println("===================================================");
    itemString = getItemID("Playstation 4 Pro");
    System.out.println(itemString);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Name (by ID: 00004)");
    System.out.println("=======================================");
    itemString = getItemName("00004");
    System.out.println(itemString);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Price (by ID: 00003)");
    System.out.println("========================================");
    double itemprice = getItemPrice("00003");
    System.out.println(itemprice);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Retrieve A Specific Quantity (by ID: 00002)");
    System.out.println("===========================================");
    int itemQuant = getItemQuantity("00002");
    System.out.println(itemQuant);

    pressAnyKey(input);

    System.out.println();
    System.out.println("Change Name for: 'Playstation 4 Pro' at ID: "
            + "'00003' TO 'Some Kinda Game-Box'");
    System.out.println("============================================"
            + "================================");
    itemString = getItemString("00003");
    System.out.println("Current Name: -->  " + itemString);
    setItemName("00003", "Some Kinda Game-Box");
    itemString = getItemString("00003");
    System.out.println("Name is Now:  -->  " + itemString);

    pressAnyKey(input);

    System.out.println();
    String itemToAdd = "00006/LG LED 60\" Television/70555.0/08";
    System.out.println("Add a new Inventory Item (duplicate ID's are not allowed).");
    System.out.println("Adding (with 'NO Auto-ID-Increment'): "
            + itemToAdd);
    System.out.println("======================================"
            + "======================================");
    if (addInventoryItem(itemToAdd)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not add (" + itemToAdd + ") to Records List!");
    }

    pressAnyKey(input);

    System.out.println();
    itemToAdd = "DYSON 430 Vacume/65437.0/6";
    System.out.println("Add a new Inventory Item (duplicate ID's are not allowed).");
    System.out.println("Adding (with 'Auto-ID-Increment'): "
            + itemToAdd);
    System.out.println("======================================"
            + "=======================");
    if (addInventoryItem(itemToAdd)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not add (" + itemToAdd + ") to Records List!");
    }

    pressAnyKey(input);

    System.out.println();
    System.out.println("Delete an Inventory Item ID (based on Item ID: 00006).");
    String itemIDToDelete = "00006";
    if (deleteInventoryItemID(itemIDToDelete)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not delete record ID (" + itemIDToDelete + ") from Records List!");
    }

    pressAnyKey(input);

    System.out.println();
    System.out.println("Delete an Inventory Item Name (based on Item Name: DYSON 430 Vacume).");
    String itemNameToDelete = "DYSON 430 Vacume";
    if (deleteInventoryItemName(itemNameToDelete)) {
        showFormattedTable();
    }
    else {
        System.err.println("Could not delete record Item Name (" + itemNameToDelete + ") from Records List!");
    }
}

private void showFormattedTable() {
    System.out.println();
    System.out.println("   Available Inventory Items (with formatting)");
    String header = String.format("%-7s %-26s %-8s %-5s", "ID", "Item Name", "Price", "Stock");
    String topLine = String.join("", Collections.nCopies(header.length(), "="));
    String underline = String.join("", Collections.nCopies(header.length(), "-"));
    System.out.println(topLine);
    System.out.println(header);
    System.out.println(underline);
    String[] allItems = getAllInventoryItems("%-7s %-26s $%-9s %-5s");
    if (allItems != null) {
        for (String strg : allItems) {
            System.out.println(strg);
        }
    }
    System.out.println(topLine);
}

/**
 * Deletes the Inventory Item in Records List and data file that contains the 
 * supplied Item ID.<br><br>
 * 
 * @param idToDelete (String) The ID Number of the record to delete.<br>
 * 
 * @return (Boolean) True if successful and False if not.
 */
public boolean deleteInventoryItemID(String idToDelete) {
    if (!isInAdminMode) {
        System.err.println(ErrorMsg.NOT_ADMIN.msg);
        return false;
    }
    if (items.isEmpty()) {
        System.err.println(ErrorMsg.LOAD_ERR.msg);
        return false;
    }
    for (int i = 0; i < items.size(); i++) {
        if (items.get(i).getId().equals(idToDelete)) {
            items.remove(i);
            break;
        }
    }
    refreshDataBase();
    return true;
}

/**
 * Deletes ALL Inventory Items in Records List and data file that contains the 
 * supplied Item Name.<br><br>
 * 
 * @param nameToDelete (String) The Item Name to delete (case insensitive).<br>
 * 
 * @return (Boolean) True if successful and False if not.
 */
public boolean deleteInventoryItemName(String nameToDelete) {
    if (!isInAdminMode) {
        System.err.println(ErrorMsg.NOT_ADMIN.msg);
        return false;
    }
    if (items.isEmpty()) {
        System.err.println(ErrorMsg.LOAD_ERR.msg);
        return false;
    }
    for (int i = 0; i < items.size(); i++) {
        if (items.get(i).getItemName().equalsIgnoreCase(nameToDelete)) {
            items.remove(i);
            i--;
        }
    }
    refreshDataBase();
    return true;
}

/**
 * Admin Rights required!<br><BR>
 * <p>
 * Adds a Inventory Item to the Records List and database file.<br><br>
 * This method can produce a unique ID string automatically if (and only if)
 * an ID value is <b>not</b> supplied within the Inventory Item string. If
 * an ID <b>is supplied</b> within the Inventory Item string then that ID
 * will be used <b>UNLESS</b> that particular ID already exists in which
 * case this method will not apply the addition and a message is displayed
 * to Console indicating as such.
 *
 * @param itemToAdd (String) The string to be supplied must be a forward
 *                  slash (<b>/</b>) delimited <b>String</b> consisting
 *                  consisting of the 4 data parts that make up any
 *                  particular Inventory Item:<pre>
 *
 *     1) The unique Item ID String (optional);
 *     2) The Item Name String;
 *     3) The Item Price (as a String);
 *     4) The Item Quantity (as a String).

* * Типичная строка элемента инвентаризации, предоставляемая этому методу, должна выглядеть следующим образом: *
 *     "00006/LG LED 60\" Television/70555.0/08"

* * Или может выглядеть (если Идентификатор запрашивается): *
 *     "LG LED 60\" Television/70555.0/08"

* * Предоставление дублированных идентификаторов (идентификатор, который уже находится в файле базы данных или * списке записей) не допускается. * * @return (Boolean) True, если добавление прошло успешно, и False, если нет. * / publi c логический addInventoryItem (String itemToAdd) {if (! isInAdminMode) {System.err.println (ErrorMsg.NOT_ADMIN.msg); вернуть ложь; } try {String [] itemParts = itemToAdd.split ("\\ s {0,} / \\ s {0,}"); // Требуется ли автоматическое увеличение идентификатора? if (! itemParts [0] .matches ("\\ d +") && itemParts.length == 3) {// Да ... String newID = getUniqueID (); String [] parts = new String [4]; parts [0] = newID; parts [1] = itemParts [0]; parts [2] = itemParts [1]; parts [3] = itemParts [2]; itemParts = parts; } String id = itemParts [0]; if (doItemIDAlreadyExist (id)) {System.err.println ("Идентификатор элемента (" + id + ") представляет собой" + ErrorMsg.ID_EXISTS.msg); вернуть ложь; } String name = itemParts [1]; if (doItemNameAlreadyExist (name)) {System.err.println ("Имя элемента (" + name + ") является" + ErrorMsg.NAME_EXISTS.msg); вернуть ложь; } double price = Double.parseDouble (itemParts [2]); int quant = Integer.parseInt (itemParts [3]); items.add (новые InventoryItems (идентификатор, имя, цена, количество)); refreshDataBase (); } catch (Exception ex) {System.err.println (ex); вернуть ложь; } верните истину; } publi c boolean doesItemIDAlreadyExist (идентификатор строки) {boolean res = false; if (items.isEmpty ()) {res = false; } else {for (InventoryItems itms: items) {if (itms. getId (). equals (id)) {res = true; перемена; }}} return res; } publi c boolean doesItemNameAlreadyExist (String name) {boolean res = false; if (items.isEmpty ()) {res = false; } else {for (InventoryItems itms: items) {if (itms.getItemName (). equalsIgnoreCase (name)) {res = true; перемена; }}} return res; } publi c String getUniqueID () {if (items.isEmpty ()) {System.err.println (ErrorMsg.LOAD_ERR.msg); вернуть ноль; } int max = 0; for (InventoryItems itms: items) {String idVal = itms.getId (); if (! idVal.matches ("\\ d +")) {continue; } int val = Integer.parseInt (idVal); if (val> max) {max = val; }} if (max == 0) {return String.format ("% 5s", 1) .replace ('', '0'); } else {return String.format ("% 5s", (max + 1)). replace ('', '0'); }} publi c String [] getAllInventoryItems (String ... formatString) {if (items.isEmpty ()) {System.err.println (ErrorMsg.LOAD_ERR.msg); вернуть ноль; } String format = ""; if (formatString.length> 0) {format = formatString [0]; } String [] itms = new String [items.size ()]; for (int i = 0; i = 1) {// Фактическая строка целочисленных значений if (lineParts [0] .matches ("\\ d +")) {id = lineParts [0]; } if (lineParts.length> = 2) {// Содержит ли строка имя или является пустой. name = (lineParts [1] .equals ("")? "Unknown": lineParts [1]); if (lineParts.length> = 3) {// Это строка с целым или двойным / плавающим значением if (lineParts [2] .matches ("-? \\ d + (\\. \\ d +)?")) {цена = Double.parseDouble (lineParts [2]); } if (lineParts.length> = 4) {// Фактическая строка целочисленных значений if (lineParts [0] .matches ("\\ d +")) {quant = Integer.parseInt (lineParts [3]); }}}}} items.add (новые InventoryItems (идентификатор, имя, цена, количество)); } success = true; } catch (FileNotFoundException ex) {System.err.println (ex); успех = ложь; } catch (IOException ex) {System.err.println (ex); успех = ложь; } вернуть успех; } publi c логическое saveItemsToFile () {if (! isInAdminMode) {System.err.println (ErrorMsg.NOT_ADMIN.msg); вернуть ложь; } String header = String.format ("% - 8s% -27s% -10s% -5s% n", "ID", "Имя элемента", "Цена", "Акции"); try (PrintWriter writer = new PrintWriter (новый OutputStreamWriter (новый FileOutputStream (dataFile), кодировка))) {// try (PrintWriter writer = новый PrintWriter (новый файл (dataFile)))) {writer.append (заголовок); for (int i = 0; i
* * @param inputString (String) Строка Unicode удалить спецификации из.
* * @return (String) * / private stati c String trimBOMs (String inputString) {inputString = inputString.trim () .replaceAll ("\ uFEFF | \ uEFBBBF | \ uFFFE | \ u0000FEFF | \ uFFFE0000 | \ u2B2F7638 "," ") .replaceAll (" \ u2B2F7639 | \ u2B2F762B | \ u2B2F762F | \ u2B2F76382D | \ uF7644 C "," \ uF \ uFEF3) UEF (UF) UF (UF) UF (UF) UF (все) UF (UF). | \ u84319533 "," "); return inputString; } private void pressAnyKey (вход сканера) {System.out.println (ls + "Нажмите клавишу Enter, чтобы продолжить (q, чтобы выйти) ..."); String anyKey = input.nextLine (); if (anyKey.toLowerCase (). equals ("q")) {System.exit (0); }}}

Создайте новый Java Проект приложения с именем InventoryDemo и скопируйте / вставьте в него предоставленные классы. Это должно дать вам представление о том, как создавать инструменты для того, что вам нужно.

...