1

So I have a MainFrame class which has a JTable in it, listing all Products stored in DB. The JButton with the help of listeners will open AddProduct (another class, and another window/frame) in which I can add product in the DB. Unfortunately, I'm not exactly sure how can I update/revalidate JTable in MainFrame once AddProduct adds new product and autocloses. Could some please give me some idea as how can I easily resolve this?

Since program is rather large, here are relevant parts of it: From MainFrame.java

public JPanel tabProducts() {
    JPanel panel = new JPanel(new MigLayout("","20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));

    /** Labels **/
    JLabel label = new JLabel("List of all available products");

    /** Buttons **/
    JButton add = new JButton("Add product");
    add.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new AddProduct();
        }
    });
    JButton update = new JButton("Update product");
    update.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            new UpdateProduct(ps.getProductByID(15));
        }
    });

    /** TABLE: Products **/
    String[] tableTitle = new String[] {"ID", "Name", "Type", "Price", "In stock"};
    String[][] tableData = null;
    DefaultTableModel model = new DefaultTableModel(tableData, tableTitle);
    JTable table = null;
    /** Disable editing of the cell **/
    table = new JTable(model){
        public boolean isCellEditable(int r, int c) {
            return false;
        }
    };
    /** Load the products from DB **/
    List<Product> listInv = ps.getProductsByAtt(new ArrayList<String>());
    for (int i = 0; i < listInv.size(); i++) {
        model.insertRow(i, new Object[] {
                listInv.get(i).getID(),
                listInv.get(i).getName(),
                listInv.get(i).getType(),
                listInv.get(i).getPrice(),
                listInv.get(i).getQuantity()
        });
    }
    /** Add scroll pane **/
    JScrollPane scrollpane = new JScrollPane(table);

    /** Add everything to the panel **/
    panel.add(label, "wrap, span");
    panel.add(scrollpane, "wrap, span");
    panel.add(add);
    panel.add(update);

    return panel;
}

And AddProduct.java

public class AddProduct {

    private JFrame frame;
    private JButton add, cancel;
    private JRadioButton food, beverage;
    private JTextField name, price, quantity;
    private IProductService ps = new ProductService();
    private ButtonGroup group = new ButtonGroup();
    private Product p;
    private String type = "";

    public AddProduct() {
        /** Frame options **/
        frame = new JFrame("Add new product");
        frame.setSize(400, 280);
        frame.setMinimumSize(new Dimension(400, 280));
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        /** Default panel **/
        final JPanel panel = new JPanel(new MigLayout("","20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));

        /** Radio Buttons to choose between the food and the beverages **/
        food = new JRadioButton("Food");
        beverage = new JRadioButton("Beverage");
        group.add(food);
        group.add(beverage);
        food.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                type = "Food";
                frame.validate();
            }
        });
        beverage.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                type = "Beverage";
                frame.validate();
            }
        });

        /** Add everything to the panel **/
        panel.add(new JLabel("Product ID"));
        panel.add(new JLabel(Integer.toString(ps.getProductNr()+1)), "wrap, span 2");
        panel.add(new JLabel("Name"));
        panel.add(name = new JTextField(""), "wrap, span 2");
        panel.add(new JLabel("Type"));
        panel.add(food);
        panel.add(beverage, "wrap");
        panel.add(new JLabel("Price"));
        panel.add(price = new JTextField(""), "wrap, span 2");
        panel.add(new JLabel("Quantity"));
        panel.add(quantity = new JTextField(""), "wrap, span 2");


        /** Button: ADD **/
        add = new JButton("Add product");
        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if ( !type.equals("Food") && !type.equals("Beverage")) {
                    JOptionPane.showMessageDialog(panel, "Please choose the type of this product.");
                } else if (name.getText().equals("")) {
                    JOptionPane.showMessageDialog(panel, "Please type a name for this product.");
                } else if (price.getText().equals("")) {
                    JOptionPane.showMessageDialog(panel, "Please enter the price for this product.");
                } else if (quantity.getText().equals("")) {
                    JOptionPane.showMessageDialog(panel, "Please enter the available amount of this product in stock.");
                } else {
                    try {
                        p = new Product(ps.getProductNr()+1, name.getText(), type, Double.parseDouble(price.getText()), Integer.parseInt(quantity.getText()));
                        if (ps.addProduct(p)) {
                            JOptionPane.showMessageDialog(panel, "Product successfully added!");
                            frame.validate();
                            frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
                        }
                    } catch (Exception ex) {
                        addFinalError();
                    }
                }
            }
        });

        /** Button: CANCEL **/
        cancel = new JButton("Cancel");
        cancel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
            }
        });

        /** Add buttons to the panel **/
        panel.add(cancel);
        panel.add(add, "span 2");

        /** Add panel to frame and make it visible **/
        frame.add(panel);
        frame.setVisible(true);

    }

    /**
     * In case more then one error is encountered
     */
    private void addFinalError(){
        JOptionPane.showMessageDialog(frame, "An error occured while adding the product. Please make sure the following is correct:\n\n" +
                " Name  : Can contain letters and numbers\n" +
                " Price  : Must be a number\n" +
                " Quantity  : Must be a whole number\n");
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
vedran
  • 2,167
  • 9
  • 29
  • 47
  • Not really sure what to try. My second day ever working with gui, so I'm kind of freaking out, because this is just a small setback compared to the rest of program which I'm yet to do. I've googled it, but most of the answers weren't helpful or I didn't know how to implement them. So, as I asked where should I start. I'm not looking for someone to program for me just to point me in right way. – vedran Mar 20 '12 at 11:18

3 Answers3

1

You need to work on the JTable model part and then refresh , revalidate will work. Just try some examples of JTable dynamic updates like create TableModel and populate jTable dynamically

Community
  • 1
  • 1
Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128
  • 2
    again: you don't _need_ (not repaint not refresh not revalidate) to do anything on the _JTable_ if the model behaves ... – kleopatra Mar 20 '12 at 11:58
0

maybe a static Method in the AddProduct class that returns the created Product will solve your problem. Take a look at the JOptionPane API for example static String showInputDialog(Object message)

Seffel
  • 397
  • 2
  • 14
0

The easy way would be to have a method in the main class that fills the table with data and in your actionPerformed method where you are handling adding a new record call that method after a record has been added. That way the main class is handling the update of the table model and the internals of the JTable will handle the repainting of the table. You could even use a method from the UpdateProducts to only update the table if adding a record was successful.

public void actionPerformed(ActionEvent e) { 
        UpdateProduct up = new UpdateProduct();
        if(up.addRecord(ps.getProductByID(15))){ 
          fillTable();
        }
    }

Hope that helps some.

ChadNC
  • 2,528
  • 4
  • 25
  • 39
  • 1
    you probably mean the right thing, just _main class is handling ...redrawing of the JTable_ is wrong: the table internals will trigger all necessary redraws (repaints in Swing speak, btw) - provided the model is firing the correct events which DefaultTableModel does – kleopatra Mar 20 '12 at 11:57
  • Thanks for clearing that up. I don't get to use swing too often. – ChadNC Mar 20 '12 at 12:06