简体   繁体   中英

Jcheckbox inside a column in a JTable

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;

}*/

}

"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);
    }
}

在此输入图像描述


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();

            }
        });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM