Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

teach me java gui based on this question : Design an Item Inventory Management Form for…

  1. User

    teach me java gui based on this question : Design an Item Inventory Management Form for an adventure game using Java Swing, with an added feature to create a powerful character based on item stats. The inventory will store 3 types of items called weapons, potions, and armor. The form should include the following components and event handling:

    Text Fields: Item Name Item Power (an integer representing the power or damage of the item) Item Weight (a decimal value representing the item's weight) Combo Box: Item Type (options: Weapon, Potion, Armor) Buttons: Add Item: When clicked: a. Validates that all fields are filled and that Power and Weight are numeric. b. Adds the item to the inventory table. c. Displays a confirmation message that the item has been added. Remove Selected Item: a. Removes the selected item from the inventory.

    Clear All: a. Clears all input fields and resets the combo box to the default value.

    Equip Random Item: a. Randomly selects an item from the table and shows an alert indicating that the player has equipped that item.

    Create Powerful Character: a. Automatically selects the three most powerful items from the inventory (one Weapon, one Armor, one Potion) and displays a summary of the equipped items as the player’s final character. If there are not enough items of each type, it should display a message indicating that the character can't be fully equipped.

    Table: a. Displays the list of items with the following columns: Item Name, Type, Power, Weight.

    b. The table should dynamically update as items are added or removed.

    Layout: a. Use a BorderLayout or GridBagLayout to organize the components. b. Text fields and combo box should be in the top section. c. Buttons should be in the middle section. d. The table should occupy the bottom section of the form.

    Event Handling Requirements:

    The Add Item button: Validates that no fields are left empty and that Power and Weight are numeric before adding an item. If validation passes, adds the item to the inventory table. If validation fails, shows an error dialog. The Remove Selected Item button: Removes the currently selected row from the table. If no row is selected, shows a warning message. The Clear All button: Resets all input fields and resets the combo box to its default value. The Equip Random Item button: Randomly selects an item from the table and displays an alert that says, "You have equipped [Item Name]." The Create Powerful Character button: Selects the most powerful Weapon, Armor, and Potion based on the highest power values. Displays a final summary of the equipped items in a pop-up message: "Your character is equipped with [Weapon], [Armor], and [Potion]." If there are not enough items of each type in the inventory, shows a message that says, "Unable to create a fully equipped character." Extra Credit: Add a feature to double-click a row in the table to load the item details into the form for editing. Implement a "Search Inventory" text field that filters the table based on item name or type.

  2. Assistant

    Sure! Let's walk through designing an Item Inventory Management Form for an adventure game using Java Swing. We'll cover each requirement step-by-step, complete with explanations and sample code. By the end of this guide, you'll have a functional GUI application that meets all the specified criteria.

    Table of Contents

    1. Prerequisites
    2. Project Structure
    3. Creating the Main Frame
    4. Designing the Form Components
      • Text Fields
      • Combo Box
      • Buttons
    5. Setting Up the Inventory Table
    6. Implementing Event Handling
      • Add Item
      • Remove Selected Item
      • Clear All
      • Equip Random Item
      • Create Powerful Character
    7. Extra Features
      • Double-Click to Edit
      • Search Inventory
    8. Complete Code Example
    9. Running the Application
    10. Conclusion

    Prerequisites

    Before we begin, ensure you have the following:

    • Java Development Kit (JDK) installed. You can download it from here.
    • An Integrated Development Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans. Alternatively, you can use a text editor and compile via the command line.

    Project Structure

    We'll create a single Java class named InventoryManagementApp for simplicity. However, for larger projects, it's advisable to organize classes into packages.

    Creating the Main Frame

    First, we'll set up the main window (JFrame) for our application.

    Code Snippet

    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.awt.*;
    
    public class InventoryManagementApp extends JFrame {
        public InventoryManagementApp() {
            setTitle("Adventure Game Inventory Management");
            setSize(800, 600);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null); // Centers the window
            setLayout(new BorderLayout());
    
            // Initialize components here
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                new InventoryManagementApp().setVisible(true);
            });
        }
    }
    

    Explanation

    • JFrame Setup: We create a JFrame titled "Adventure Game Inventory Management" with a size of 800x600 pixels.
    • Layout: We're using BorderLayout to organize components into top, middle, and bottom sections.
    • Main Method: Launches the GUI on the Event Dispatch Thread (EDT) for thread safety.

    Designing the Form Components

    Text Fields

    We'll need three text fields: Item Name, Item Power, and Item Weight.

    Code Snippet

    // Inside InventoryManagementApp class
    
    private JTextField itemNameField;
    private JTextField itemPowerField;
    private JTextField itemWeightField;
    private JComboBox<String> itemTypeComboBox;
    private JButton addItemButton, removeItemButton, clearAllButton, equipRandomButton, createCharacterButton;
    private JTable inventoryTable;
    private DefaultTableModel tableModel;
    
    private void initializeForm() {
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5,5,5,5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
    
        // Labels and Fields
        JLabel nameLabel = new JLabel("Item Name:");
        itemNameField = new JTextField(15);
        JLabel powerLabel = new JLabel("Item Power:");
        itemPowerField = new JTextField(10);
        JLabel weightLabel = new JLabel("Item Weight:");
        itemWeightField = new JTextField(10);
        JLabel typeLabel = new JLabel("Item Type:");
        String[] itemTypes = {"Weapon", "Potion", "Armor"};
        itemTypeComboBox = new JComboBox<>(itemTypes);
    
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(nameLabel, gbc);
    
        gbc.gridx = 1;
        formPanel.add(itemNameField, gbc);
    
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(powerLabel, gbc);
    
        gbc.gridx = 1;
        formPanel.add(itemPowerField, gbc);
    
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(weightLabel, gbc);
    
        gbc.gridx = 1;
        formPanel.add(itemWeightField, gbc);
    
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(typeLabel, gbc);
    
        gbc.gridx = 1;
        formPanel.add(itemTypeComboBox, gbc);
    
        add(formPanel, BorderLayout.NORTH);
    }
    

    Explanation

    • JPanel with GridBagLayout: Offers flexibility to arrange components in a grid.
    • Labels and Input Fields: Each label is associated with its corresponding input field.
    • ComboBox: Provides a dropdown for selecting the item type.

    Combo Box

    Already included in the form above as itemTypeComboBox.

    Buttons

    We'll add five buttons: Add Item, Remove Selected Item, Clear All, Equip Random Item, and Create Powerful Character.

    Code Snippet

    // Inside InventoryManagementApp class
    
    private void initializeButtons() {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
    
        addItemButton = new JButton("Add Item");
        removeItemButton = new JButton("Remove Selected Item");
        clearAllButton = new JButton("Clear All");
        equipRandomButton = new JButton("Equip Random Item");
        createCharacterButton = new JButton("Create Powerful Character");
    
        buttonPanel.add(addItemButton);
        buttonPanel.add(removeItemButton);
        buttonPanel.add(clearAllButton);
        buttonPanel.add(equipRandomButton);
        buttonPanel.add(createCharacterButton);
    
        add(buttonPanel, BorderLayout.CENTER);
    }
    

    Explanation

    • JPanel with FlowLayout: Arranges buttons in a single row with spacing.
    • Buttons: Each button is created and added to the panel.

    Setting Up the Inventory Table

    We'll use a JTable with a DefaultTableModel to display the inventory items.

    Code Snippet

    // Inside InventoryManagementApp class
    
    private void initializeTable() {
        String[] columnNames = {"Item Name", "Type", "Power", "Weight"};
        tableModel = new DefaultTableModel(columnNames, 0);
        inventoryTable = new JTable(tableModel);
        inventoryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
        JScrollPane scrollPane = new JScrollPane(inventoryTable);
        scrollPane.setPreferredSize(new Dimension(780, 250));
    
        add(scrollPane, BorderLayout.SOUTH);
    }
    

    Explanation

    • DefaultTableModel: Allows dynamic addition and removal of rows.
    • JTable: Displays the items with specified columns.
    • JScrollPane: Makes the table scrollable, handling large inventories.

    Implementing Event Handling

    Now, we'll add functionality to the buttons.

    Add Item

    Requirements:

    • Validate that all fields are filled.
    • Ensure Power is an integer and Weight is a decimal.
    • Add the item to the table.
    • Show confirmation or error message.

    Code Snippet

    // Inside InventoryManagementApp class
    
    private void initializeEventHandlers() {
        addItemButton.addActionListener(e -> addItem());
        removeItemButton.addActionListener(e -> removeItem());
        clearAllButton.addActionListener(e -> clearAllFields());
        equipRandomButton.addActionListener(e -> equipRandomItem());
        createCharacterButton.addActionListener(e -> createPowerfulCharacter());
    }
    
    private void addItem() {
        String name = itemNameField.getText().trim();
        String powerStr = itemPowerField.getText().trim();
        String weightStr = itemWeightField.getText().trim();
        String type = (String) itemTypeComboBox.getSelectedItem();
    
        if (name.isEmpty() || powerStr.isEmpty() || weightStr.isEmpty() || type.isEmpty()) {
            JOptionPane.showMessageDialog(this, "All fields must be filled.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    
        int power;
        double weight;
    
        try {
            power = Integer.parseInt(powerStr);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Item Power must be an integer.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    
        try {
            weight = Double.parseDouble(weightStr);
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Item Weight must be a decimal number.", "Input Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
    
        // Add to table
        tableModel.addRow(new Object[]{name, type, power, weight});
        JOptionPane.showMessageDialog(this, "Item added successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
        clearAllFields();
    }
    

    Explanation

    • Field Validation: Checks for empty inputs.
    • Data Type Validation: Ensures that power is an integer and weight is a decimal.
    • Adding to Table: Uses tableModel.addRow() to add the item.
    • Confirmation Message: Informs the user of successful addition.
    • Clear Fields: Resets input fields after adding.

    Remove Selected Item

    Requirements:

    • Remove the selected row.
    • Show warning if no row is selected.

    Code Snippet

    private void removeItem() {
        int selectedRow = inventoryTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "No item selected to remove.", "Warning", JOptionPane.WARNING_MESSAGE);
        } else {
            int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you want to remove the selected item?", "Confirm Removal", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                tableModel.removeRow(selectedRow);
            }
        }
    }
    

    Explanation

    • Selection Check: Verifies if a row is selected.
    • Confirmation Dialog: Asks for user confirmation before removing.
    • Row Removal: Deletes the selected row from the table model.

    Clear All

    Requirements:

    • Reset all input fields and combo box.

    Code Snippet

    private void clearAllFields() {
        itemNameField.setText("");
        itemPowerField.setText("");
        itemWeightField.setText("");
        itemTypeComboBox.setSelectedIndex(0);
    }
    

    Explanation

    • Reset Fields: Clears text fields and sets the combo box to the first option.

    Equip Random Item

    Requirements:

    • Randomly select an item from the table.
    • Display an alert that the player has equipped the item.

    Code Snippet

    import java.util.Random;
    
    // Inside InventoryManagementApp class
    
    private void equipRandomItem() {
        int rowCount = tableModel.getRowCount();
        if (rowCount == 0) {
            JOptionPane.showMessageDialog(this, "Inventory is empty.", "Info", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
    
        Random rand = new Random();
        int randomIndex = rand.nextInt(rowCount);
        String itemName = (String) tableModel.getValueAt(randomIndex, 0);
        JOptionPane.showMessageDialog(this, "You have equipped " + itemName + ".", "Item Equipped", JOptionPane.INFORMATION_MESSAGE);
    }
    

    Explanation

    • Random Selection: Uses Random to pick an index within the table's row count.
    • Displaying Message: Shows which item has been equipped.

    Create Powerful Character

    Requirements:

    • Select the most powerful Weapon, Armor, and Potion.
    • Display a summary of equipped items.
    • Show a message if items are insufficient.

    Code Snippet

    private void createPowerfulCharacter() {
        String topWeapon = null;
        String topArmor = null;
        String topPotion = null;
        int maxWeaponPower = Integer.MIN_VALUE;
        int maxArmorPower = Integer.MIN_VALUE;
        int maxPotionPower = Integer.MIN_VALUE;
    
        for (int i = 0; i < tableModel.getRowCount(); i++) {
            String type = (String) tableModel.getValueAt(i, 1);
            int power = (int) tableModel.getValueAt(i, 2);
            String name = (String) tableModel.getValueAt(i, 0);
    
            switch (type) {
                case "Weapon":
                    if (power > maxWeaponPower) {
                        maxWeaponPower = power;
                        topWeapon = name;
                    }
                    break;
                case "Armor":
                    if (power > maxArmorPower) {
                        maxArmorPower = power;
                        topArmor = name;
                    }
                    break;
                case "Potion":
                    if (power > maxPotionPower) {
                        maxPotionPower = power;
                        topPotion = name;
                    }
                    break;
            }
        }
    
        if (topWeapon != null && topArmor != null && topPotion != null) {
            String message = "Your character is equipped with:\nWeapon: " + topWeapon +
                    "\nArmor: " + topArmor + "\nPotion: " + topPotion + ".";
            JOptionPane.showMessageDialog(this, message, "Powerful Character", JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this, "Unable to create a fully equipped character.", "Insufficient Items", JOptionPane.WARNING_MESSAGE);
        }
    }
    

    Explanation

    • Iterate Through Items: Goes through each item to find the highest power for each type.
    • Selecting Top Items: Keeps track of the item with the highest power for Weapon, Armor, and Potion.
    • Displaying Summary: Shows the equipped items or a warning if insufficient.

    Extra Features

    Double-Click to Edit

    Requirements:

    • Double-clicking a table row loads item details into the form for editing.

    Code Snippet

    private void initializeTableDoubleClick() {
        inventoryTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                if (evt.getClickCount() == 2) { // Double-click
                    JTable target = (JTable) evt.getSource();
                    int row = target.getSelectedRow();
                    if (row != -1) {
                        String name = (String) tableModel.getValueAt(row, 0);
                        String type = (String) tableModel.getValueAt(row, 1);
                        int power = (int) tableModel.getValueAt(row, 2);
                        double weight = (double) tableModel.getValueAt(row, 3);
    
                        itemNameField.setText(name);
                        itemTypeComboBox.setSelectedItem(type);
                        itemPowerField.setText(String.valueOf(power));
                        itemWeightField.setText(String.valueOf(weight));
    
                        // Optionally, remove the item to allow editing and re-adding
                        tableModel.removeRow(row);
                    }
                }
            }
        });
    }
    

    Explanation

    • Mouse Listener: Detects double-click events on the table.
    • Load Data: Retrieves the selected row's data and populates the form fields.
    • Optional Removal: Removes the row to facilitate editing and re-adding.

    Search Inventory

    Requirements:

    • A text field to filter the table based on item name or type.

    Code Snippet

    import javax.swing.RowFilter;
    import javax.swing.table.TableRowSorter;
    
    // Inside InventoryManagementApp class
    
    private JTextField searchField;
    private TableRowSorter<DefaultTableModel> sorter;
    
    private void initializeSearchBar() {
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        JLabel searchLabel = new JLabel("Search:");
        searchField = new JTextField(20);
    
        searchPanel.add(searchLabel);
        searchPanel.add(searchField);
    
        add(searchPanel, BorderLayout.NORTH);
        
        sorter = new TableRowSorter<>(tableModel);
        inventoryTable.setRowSorter(sorter);
    
        searchField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                filter();
            }
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
                filter();
            }
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
                filter();
            }
    
            private void filter() {
                String text = searchField.getText();
                if (text.trim().length() == 0) {
                    sorter.setRowFilter(null);
                } else {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }
        });
    }
    

    Explanation

    • Search Panel: Contains a label and a text field for searching.
    • RowFilter: Filters table rows based on the search input.
    • Document Listener: Updates the filter as the user types.

    Note: Since we're using BorderLayout, having both initializeForm() and initializeSearchBar() add components to BorderLayout.NORTH can cause conflicts. To resolve this, we can use an inner panel to house both the search bar and form.

    Updated Integration for Search and Form

    To integrate the search bar and form in the top section, modify initializeForm() and initializeSearchBar() as follows:

    private void initializeUIComponents() {
        JPanel topPanel = new JPanel(new BorderLayout());
    
        // Form Panel
        JPanel formPanel = new JPanel(new GridBagLayout());
        // [Add form components as shown earlier]
        // ... [initializeForm code, but add it to formPanel instead of directly to BorderLayout.NORTH]
    
        // Search Panel
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        JLabel searchLabel = new JLabel("Search:");
        searchField = new JTextField(20);
        searchPanel.add(searchLabel);
        searchPanel.add(searchField);
    
        topPanel.add(formPanel, BorderLayout.CENTER);
        topPanel.add(searchPanel, BorderLayout.SOUTH);
    
        add(topPanel, BorderLayout.NORTH);
    
        // Initialize sorter after tableModel is initialized
        sorter = new TableRowSorter<>(tableModel);
        inventoryTable.setRowSorter(sorter);
    
        // Add Document Listener for search
        searchField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            public void insertUpdate(javax.swing.event.DocumentEvent e) { filter(); }
            public void removeUpdate(javax.swing.event.DocumentEvent e) { filter(); }
            public void changedUpdate(javax.swing.event.DocumentEvent e) { filter(); }
    
            private void filter() {
                String text = searchField.getText();
                if (text.trim().length() == 0) {
                    sorter.setRowFilter(null);
                } else {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }
        });
    }
    

    Explanation

    • Top Panel: Combines the form and search panel within the BorderLayout.NORTH region.
    • Search Integration: Ensures both form and search bar coexist without layout conflicts.

    Complete Code Example

    Below is the complete code integrating all the components and features discussed.

    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableRowSorter;
    import java.awt.*;
    import java.util.Random;
    
    public class InventoryManagementApp extends JFrame {
        private JTextField itemNameField;
        private JTextField itemPowerField;
        private JTextField itemWeightField;
        private JComboBox<String> itemTypeComboBox;
        private JButton addItemButton, removeItemButton, clearAllButton, equipRandomButton, createCharacterButton;
        private JTable inventoryTable;
        private DefaultTableModel tableModel;
        private JTextField searchField;
        private TableRowSorter<DefaultTableModel> sorter;
    
        public InventoryManagementApp() {
            setTitle("Adventure Game Inventory Management");
            setSize(800, 600);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null); // Centers the window
            setLayout(new BorderLayout());
    
            initializeUIComponents();
            initializeButtons();
            initializeEventHandlers();
            initializeTableDoubleClick();
        }
    
        private void initializeUIComponents() {
            // Top Panel containing Form and Search
            JPanel topPanel = new JPanel(new BorderLayout());
    
            // Form Panel
            JPanel formPanel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.fill = GridBagConstraints.HORIZONTAL;
    
            // Labels and Fields
            JLabel nameLabel = new JLabel("Item Name:");
            itemNameField = new JTextField(15);
            JLabel powerLabel = new JLabel("Item Power:");
            itemPowerField = new JTextField(10);
            JLabel weightLabel = new JLabel("Item Weight:");
            itemWeightField = new JTextField(10);
            JLabel typeLabel = new JLabel("Item Type:");
            String[] itemTypes = {"Weapon", "Potion", "Armor"};
            itemTypeComboBox = new JComboBox<>(itemTypes);
    
            gbc.gridx = 0;
            gbc.gridy = 0;
            formPanel.add(nameLabel, gbc);
    
            gbc.gridx = 1;
            formPanel.add(itemNameField, gbc);
    
            gbc.gridx = 0;
            gbc.gridy = 1;
            formPanel.add(powerLabel, gbc);
    
            gbc.gridx = 1;
            formPanel.add(itemPowerField, gbc);
    
            gbc.gridx = 0;
            gbc.gridy = 2;
            formPanel.add(weightLabel, gbc);
    
            gbc.gridx = 1;
            formPanel.add(itemWeightField, gbc);
    
            gbc.gridx = 0;
            gbc.gridy = 3;
            formPanel.add(typeLabel, gbc);
    
            gbc.gridx = 1;
            formPanel.add(itemTypeComboBox, gbc);
    
            topPanel.add(formPanel, BorderLayout.CENTER);
    
            // Search Panel
            JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
            JLabel searchLabel = new JLabel("Search:");
            searchField = new JTextField(20);
            searchPanel.add(searchLabel);
            searchPanel.add(searchField);
    
            topPanel.add(searchPanel, BorderLayout.SOUTH);
    
            add(topPanel, BorderLayout.NORTH);
    
            // Buttons Panel
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
    
            addItemButton = new JButton("Add Item");
            removeItemButton = new JButton("Remove Selected Item");
            clearAllButton = new JButton("Clear All");
            equipRandomButton = new JButton("Equip Random Item");
            createCharacterButton = new JButton("Create Powerful Character");
    
            buttonPanel.add(addItemButton);
            buttonPanel.add(removeItemButton);
            buttonPanel.add(clearAllButton);
            buttonPanel.add(equipRandomButton);
            buttonPanel.add(createCharacterButton);
    
            add(buttonPanel, BorderLayout.CENTER);
    
            // Table Panel
            String[] columnNames = {"Item Name", "Type", "Power", "Weight"};
            tableModel = new DefaultTableModel(columnNames, 0) {
                // To make cells non-editable directly
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
    
            inventoryTable = new JTable(tableModel);
            inventoryTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            sorter = new TableRowSorter<>(tableModel);
            inventoryTable.setRowSorter(sorter);
    
            JScrollPane scrollPane = new JScrollPane(inventoryTable);
            scrollPane.setPreferredSize(new Dimension(780, 250));
    
            add(scrollPane, BorderLayout.SOUTH);
    
            // Add Document Listener for search
            searchField.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
                public void insertUpdate(javax.swing.event.DocumentEvent e) { filter(); }
                public void removeUpdate(javax.swing.event.DocumentEvent e) { filter(); }
                public void changedUpdate(javax.swing.event.DocumentEvent e) { filter(); }
    
                private void filter() {
                    String text = searchField.getText();
                    if (text.trim().length() == 0) {
                        sorter.setRowFilter(null);
                    } else {
                        sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                    }
                }
            });
        }
    
        private void initializeButtons() {
            // Buttons are already initialized in initializeUIComponents
            // This method can be used for additional button configurations if needed
        }
    
        private void initializeEventHandlers() {
            addItemButton.addActionListener(e -> addItem());
            removeItemButton.addActionListener(e -> removeItem());
            clearAllButton.addActionListener(e -> clearAllFields());
            equipRandomButton.addActionListener(e -> equipRandomItem());
            createCharacterButton.addActionListener(e -> createPowerfulCharacter());
        }
    
        private void initializeTableDoubleClick() {
            inventoryTable.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    if (evt.getClickCount() == 2) { // Double-click
                        JTable target = (JTable) evt.getSource();
                        int row = target.getSelectedRow();
                        if (row != -1) {
                            int modelRow = target.convertRowIndexToModel(row);
                            String name = (String) tableModel.getValueAt(modelRow, 0);
                            String type = (String) tableModel.getValueAt(modelRow, 1);
                            int power = (int) tableModel.getValueAt(modelRow, 2);
                            double weight = (double) tableModel.getValueAt(modelRow, 3);
    
                            itemNameField.setText(name);
                            itemTypeComboBox.setSelectedItem(type);
                            itemPowerField.setText(String.valueOf(power));
                            itemWeightField.setText(String.valueOf(weight));
    
                            // Remove the item to allow editing and re-adding
                            tableModel.removeRow(modelRow);
                        }
                    }
                }
            });
        }
    
        private void addItem() {
            String name = itemNameField.getText().trim();
            String powerStr = itemPowerField.getText().trim();
            String weightStr = itemWeightField.getText().trim();
            String type = (String) itemTypeComboBox.getSelectedItem();
    
            if (name.isEmpty() || powerStr.isEmpty() || weightStr.isEmpty() || type.isEmpty()) {
                JOptionPane.showMessageDialog(this, "All fields must be filled.", "Input Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
    
            int power;
            double weight;
    
            try {
                power = Integer.parseInt(powerStr);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "Item Power must be an integer.", "Input Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
    
            try {
                weight = Double.parseDouble(weightStr);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "Item Weight must be a decimal number.", "Input Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
    
            // Add to table
            tableModel.addRow(new Object[]{name, type, power, weight});
            JOptionPane.showMessageDialog(this, "Item added successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
            clearAllFields();
        }
    
        private void removeItem() {
            int selectedRow = inventoryTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "No item selected to remove.", "Warning", JOptionPane.WARNING_MESSAGE);
            } else {
                int modelRow = inventoryTable.convertRowIndexToModel(selectedRow);
                int confirm = JOptionPane.showConfirmDialog(this, "Are you sure you want to remove the selected item?", "Confirm Removal", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    tableModel.removeRow(modelRow);
                }
            }
        }
    
        private void clearAllFields() {
            itemNameField.setText("");
            itemPowerField.setText("");
            itemWeightField.setText("");
            itemTypeComboBox.setSelectedIndex(0);
        }
    
        private void equipRandomItem() {
            int rowCount = tableModel.getRowCount();
            if (rowCount == 0) {
                JOptionPane.showMessageDialog(this, "Inventory is empty.", "Info", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
    
            Random rand = new Random();
            int randomIndex = rand.nextInt(rowCount);
            String itemName = (String) tableModel.getValueAt(randomIndex, 0);
            JOptionPane.showMessageDialog(this, "You have equipped " + itemName + ".", "Item Equipped", JOptionPane.INFORMATION_MESSAGE);
        }
    
        private void createPowerfulCharacter() {
            String topWeapon = null;
            String topArmor = null;
            String topPotion = null;
            int maxWeaponPower = Integer.MIN_VALUE;
            int maxArmorPower = Integer.MIN_VALUE;
            int maxPotionPower = Integer.MIN_VALUE;
    
            for (int i = 0; i < tableModel.getRowCount(); i++) {
                String type = (String) tableModel.getValueAt(i, 1);
                int power = (int) tableModel.getValueAt(i, 2);
                String name = (String) tableModel.getValueAt(i, 0);
    
                switch (type) {
                    case "Weapon":
                        if (power > maxWeaponPower) {
                            maxWeaponPower = power;
                            topWeapon = name;
                        }
                        break;
                    case "Armor":
                        if (power > maxArmorPower) {
                            maxArmorPower = power;
                            topArmor = name;
                        }
                        break;
                    case "Potion":
                        if (power > maxPotionPower) {
                            maxPotionPower = power;
                            topPotion = name;
                        }
                        break;
                }
            }
    
            if (topWeapon != null && topArmor != null && topPotion != null) {
                String message = "Your character is equipped with:\nWeapon: " + topWeapon +
                        "\nArmor: " + topArmor + "\nPotion: " + topPotion + ".";
                JOptionPane.showMessageDialog(this, message, "Powerful Character", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "Unable to create a fully equipped character.", "Insufficient Items", JOptionPane.WARNING_MESSAGE);
            }
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> {
                new InventoryManagementApp().setVisible(true);
            });
        }
    }
    

    Explanation

    • UI Components: All components are initialized with proper layout management.
    • Event Handling: Each button has its associated action.
    • Extra Features: Double-click to edit and search functionality are integrated.
    • Non-Editable Cells: The table cells are set to non-editable directly to maintain data integrity.

    Running the Application

    1. Using an IDE:

      • Create a new Java project.
      • Add the InventoryManagementApp class.
      • Compile and run the project.
    2. Using Command Line:

      • Save the complete code in a file named InventoryManagementApp.java.
      • Open the terminal and navigate to the directory containing the file.
      • Compile:
        javac InventoryManagementApp.java
        
      • Run:
        java InventoryManagementApp
        

    Note: Ensure that the InventoryManagementApp.class file is in the current directory when running the java command.

    Conclusion

    You've now built a comprehensive Java Swing application for managing an adventure game's item inventory. This application includes:

    • Form Components: Text fields, combo box, and buttons for input and actions.
    • Inventory Table: Displays items dynamically with sorting and filtering.
    • Event Handling: Validates input, manages inventory, and equips characters.
    • Extra Features: Edit items via double-click and search functionality.

    This foundational knowledge can be expanded to include more complex features like persistent storage (e.g., saving to a file or database), enhanced UI designs, and more intricate game mechanics. Happy coding!