0

I want to create a table where every time a new row is added, a new check box in a certain column will also be added. I've don my research but i still cant find the right answer for my question, and sometimes i find it hard to understand some of the instructions SO here is my problem:

I have added a check box inside the column (the "e")of my table but it doesn't show. The check box only shows if i click it.

package app.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.DefaultCellEditor;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.SwingConstants;

import app.dao.item.impl.ReadItemFromDB;
import app.model.Item;

public class Inventory {

private JFrame inventoryframe;
private JTable table;
private JTextField textField;
private JCheckBox checkbox;
/**
 * Launch the application.
 */
public  void InventoryWindow() {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Inventory window = new Inventory();
                window.inventoryframe.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public Inventory() {
    initialize();

}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    inventoryframe = new JFrame();
    inventoryframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
    inventoryframe.getContentPane().setBackground(new Color(153, 204, 102));
    inventoryframe.getContentPane().setForeground(new Color(255, 255, 255));
    inventoryframe.getContentPane().setPreferredSize(new Dimension(1365, 747));
    inventoryframe.pack();
    inventoryframe.getContentPane().setLayout(null);

    JLabel lblInventory = new JLabel("Inventory Management");
    lblInventory.setBounds(56, 32, 234, 27);
    lblInventory.setFont(new Font("Tahoma", Font.PLAIN, 22));
    inventoryframe.getContentPane().add(lblInventory);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(56, 130, 479, 249);
    inventoryframe.getContentPane().add(scrollPane);

    table = new JTable();
    table.setShowVerticalLines(false);
    table.setShowHorizontalLines(false);
    table.setShowGrid(false);
    table.setFillsViewportHeight(true);
    table.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                    "t", "e"
            }
            ));
    scrollPane.setViewportView(table);


    checkbox = new JCheckBox("borrow");
    checkbox.setHorizontalAlignment(SwingConstants.CENTER);
    checkbox.setBounds(360, 63, 97, 23);

    TableColumn sportColumn = table.getColumnModel().getColumn(1);
    sportColumn.setCellEditor(new DefaultCellEditor(checkbox));


    doIt();
}

public void doIt(){
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    dtm.getDataVector().removeAllElements();
    dtm.getColumnClass(0);
    ReadItemFromDB myReader = new ReadItemFromDB();
    List<Item> newItemList = myReader.showItems();
    @Override
     public Class getColumnClass() {
            return getValueAt(0, 1).getClass();
        }
    for (Item myNewItems : newItemList) {
        Object[] rowData = new Object[1];


        rowData[0] =myNewItems.getItemID();



        dtm.addRow(rowData);
    }

    table.updateUI();


}



/*public Boolean getColumnClass(){
    dtm.getValueAt(0, 1).getClass();
    return null;

}*/

}

harraypotter
  • 111
  • 2
  • 2
  • 11

1 Answers1

2

"Im sorry , please elaborate more?? Can u show an example?"

No need for custom renderers or editors. Just @Override the getColumnClass() in the model of the table, use a DefaultTableModel and use just use Boolean types for that column.

There a running exmpple below, and here is the important part

    DefaultTableModel model = new DefaultTableModel(data, cols) {
        @Override
        public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }
    };
    JTable table = new JTable(model);

Here's the complete code

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class TestTableCheck {

    private static JTable createTable() {
        Object[][] data = {{true, true, true}, {false, false, false}};
        String[] cols = {"Bibitty", "Boppity", "Boo"};

        DefaultTableModel model = new DefaultTableModel(data, cols) {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable(model);

        return table;
    }

    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null,
                new JScrollPane(createTable()),
                "Table",
                JOptionPane.PLAIN_MESSAGE);
    }
}

enter image description here


UPDATE

Here is your code. Look in the initialize() method, where I commented out some of your code, and added mine below. Also I got rid of the doit() method. Also you should pack() as the end of the method, and also setVisible(). I also added a main method so it is runnable

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;

import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.DefaultCellEditor;
import javax.swing.JTextField;
import javax.swing.JCheckBox;
import javax.swing.SwingConstants;

import javax.swing.SwingUtilities;

public class Inventory {

    private JFrame inventoryframe;
    private JTable table;
    private JTextField textField;
    private JCheckBox checkbox;

    /**
     * Launch the application.
     */
    public void InventoryWindow() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Inventory window = new Inventory();
                    window.inventoryframe.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Inventory() {
        initialize();

    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        inventoryframe = new JFrame();
        inventoryframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
        inventoryframe.getContentPane().setBackground(new Color(153, 204, 102));
        inventoryframe.getContentPane().setForeground(new Color(255, 255, 255));
        inventoryframe.getContentPane().setPreferredSize(new Dimension(1365, 747));
        inventoryframe.getContentPane().setLayout(null);

        JLabel lblInventory = new JLabel("Inventory Management");
        lblInventory.setBounds(56, 32, 234, 27);
        lblInventory.setFont(new Font("Tahoma", Font.PLAIN, 22));
        inventoryframe.getContentPane().add(lblInventory);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(56, 130, 479, 249);
        inventoryframe.getContentPane().add(scrollPane);

        table = new JTable();
        table.setShowVerticalLines(false);
        table.setShowHorizontalLines(false);
        table.setShowGrid(false);
        table.setFillsViewportHeight(true);
        /* table.setModel(new DefaultTableModel(
         new Object[][]{},
         new String[]{
         "t", "e"
         }
         ));*/
        Object[][] data = {{true, true, true}, {false, false, false}};
        String[] cols = {"Bibitty", "Boppity", "Boo"};

        DefaultTableModel model = new DefaultTableModel(data, cols) {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        table.setModel(model);
        scrollPane.setViewportView(table);

        checkbox = new JCheckBox("borrow");
        checkbox.setHorizontalAlignment(SwingConstants.CENTER);
        checkbox.setBounds(360, 63, 97, 23);

        TableColumn sportColumn = table.getColumnModel().getColumn(1);
        sportColumn.setCellEditor(new DefaultCellEditor(checkbox));

       inventoryframe.pack();
       inventoryframe.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Inventory();
            }
        });
    }
}

UPDATE 2

Really this should be a whole other question, but I'm felling generous today.

Use this test class. Run it. When you click the button, it will open the Inventory class. You probably didn't instantiate Inventory in your button's actionPerformed. Make sure this class file is in the same package as the Inventory class file. And just run the class below.

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class InventoryTest extends JFrame {

    public InventoryTest() {
        setLayout(new GridBagLayout());
        JButton show = new JButton("Show Inventory");
        add(show);

        show.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                new Inventory();
            }
        });

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 400);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new InventoryTest();

            }
        });
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Hello thanks, ive been studying your code , thats why i was not able to reply quickly, please help me because i dont know where to place what. here is my code – harraypotter Jan 26 '14 at 09:47
  • thanks.. im trying to study it, sorry for taking a while.... :( im new :( and i really cant get it :( – harraypotter Jan 26 '14 at 09:52
  • Where is it? Edit your post. – Paul Samsotha Jan 26 '14 at 09:54
  • I changed my answer around to make it easier for you. This way is more correct anyway. – Paul Samsotha Jan 26 '14 at 10:09
  • ok wait ill edit my post. SOrry im new to here so i dont know where the buttons are,, wait .. – harraypotter Jan 26 '14 at 10:10
  • See my **UPDATE**. I have to step out for a bit. So if this answer works for you, please don't forget to accept it. (the check mark); – Paul Samsotha Jan 26 '14 at 10:30
  • hello. Thanks for your effort. Sorry if i cant pick it up that quickly. I added the revisions you made , but i removed some of your revisions like adding the main method . Sir, i should not put the main method in , because i have a main method in another class. And the error i encountered when i pasted your code was: when i click the button that will show this class, it does not open :( – harraypotter Jan 26 '14 at 10:41
  • Really, this should a whole other question to post on this site. The original problem was solved for you. The right thing to is `accept` this answer by clicking the check mark, then ask another question on this site. I will be nice today, help you still. Look at my **UPDATE 2** . If you're don't understand about event handling, and how to make buttons handle events, then I don't think I can really help you any further. You will need to go through some tutorials. – Paul Samsotha Jan 26 '14 at 11:05
  • I dont know if this will make it clearer, but im using Window builder in eclipse .. – harraypotter Jan 26 '14 at 11:32
  • you know that you don't _have_ to repeat the errors in the question code, don't you? Downvoting reflex temporarily frozen, though ;-) – kleopatra Jan 26 '14 at 12:00
  • @kleopatra _errors_ or _bad practices_? I didn't get an errors testing the code. As far as bad practices go, the code in the question was eclipses auto-generated, so I didn't want to mess with it much, just trying to solve the OP's problem. – Paul Samsotha Jan 26 '14 at 12:07
  • @Pink000 This is what you need to do with WindowBuilder. Right click on the button, and select **Add Event Handler -> action -> actionPerformed**. Then go to the source code and you will see the `actionPerformed` method auto-generated. That's where you need to instantiate `new Inventory()` – Paul Samsotha Jan 26 '14 at 12:09
  • a null layout/setXXSize _are errors_ - but seeing your point: walking the OP through the generated code is quite a task :-) – kleopatra Jan 26 '14 at 12:09
  • Yes i know that.. if you will see the whole Project, you will see that im doing SOME things correctly, im just really having a problem with this checkbox inside the table because to tell you the truth, im just self studying.. thats why up until now Im still browsing for some answers. – harraypotter Jan 26 '14 at 12:14