Results 1 to 9 of 9
  1. #1
    hind is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Talking JCheckBox in JTable column

    hi
    can someone help me please im new to java, i need to add checkboxs to the last column of my jtable so user can edit that column, all the other columns are populated with data read from txt file.

    my code
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;

    // This program allows a list of Products to be maintained i.e.
    // added, deleted and sorted. The products are displayed in
    // a JTable and also maintained in an ArrayList.

    // Some criticisms of the code:

    // 1. Quite a lot of the code seems concerned with keeping the
    // JTable and the ArrayList contents in step. Perhaps there
    // is a better way to do this by writing my own
    // TableModel.

    // 2. No data validation is implmented

    // 3. The design does not conform to the MVC pattern

    // 4. Only one sort order (by product name) is possible.
    // To make it possible to sort into other orders e.g.
    // by price it would be necessary to use a Comparator object.

    // 5. The ArrayList used does not use generics

    class StockEnquiries implements Comparable {
    private String name;
    private int phone;
    private String branch;

    public StockEnquiries(String n, int p, String b) {
    name = n;
    phone = p;
    branch = b;
    }
    public StockEnquiries() {

    }
    public String getName() {
    return name;
    }
    public int getPhone() {
    return phone;
    }
    public String getBranch() {
    return branch;
    }
    // compareTo() allows Product instances in a container
    // (e.g. an ArrayList) to be sorted by Collections.sort().

    // It can only sort things in one order (e.g. ascending order of
    // name). Need to investigate the use of Comparator objects to
    // allow different sort orders to be defined.

    public int compareTo(Object o) {
    StockEnquiries temp = (StockEnquiries) o;

    // Strings already implement compareTo() so just use that
    return (name.compareTo(temp.name));
    }
    }
    public class GUI1 extends JFrame {

    // A container for the Product instances
    ArrayList enquiries = new ArrayList();

    // GUI bits and bobs
    JPanel panInput = new JPanel(new GridLayout(2,1)),
    panAdd = new JPanel(),
    panDelSort = new JPanel();

    JTextField txtName = new JTextField(10),
    txtPhone = new JTextField(5);
    JTextField txtBranch = new JTextField(100);
    JButton btnAdd = new JButton("Add"),
    btnDelete = new JButton("Delete"),
    btnSort = new JButton("Sort Products");

    JTable tab = new JTable();

    // The DefaultTableModel will allow the contents of the
    // JTable to be manipulated.
    DefaultTableModel tabMod = new DefaultTableModel();

    StockEnquiries [] initialEnquiries = {new StockEnquiries(),
    new StockEnquiries(),
    new StockEnquiries()};

    public GUI1() {
    super("stock enquiries list");
    tab.setModel(tabMod);
    tabMod.addColumn("Name");
    tabMod.addColumn("Phone");
    tabMod.addColumn("Branch");
    tabMod.addColumn("time");
    tabMod.addColumn("enquiry");
    tabMod.addColumn("dealt with");



    btnAdd.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    addStockEnquiries();
    }
    });

    btnDelete.setToolTipText("Select the records to delete first");
    btnDelete.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    deleteStockEnquiries();
    }
    });
    btnSort.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    sortEnquiries();
    }
    });

    panAdd.add(btnAdd);
    panAdd.add(new JLabel("Product name:"));
    panAdd.add(txtName);
    panAdd.add(new JLabel("Phone Number:"));
    panAdd.add(txtPhone);
    panDelSort.add(btnDelete);
    panDelSort.add(btnSort);
    panInput.add(panAdd);
    panInput.add(panDelSort);
    getContentPane().add(panInput, BorderLayout.SOUTH);
    getContentPane().add(new JScrollPane(tab));
    loadInitialEnquiries();
    }
    // Delete a product from the ArrayList and from the JTable
    public void deleteStockEnquiries() {
    int [] rows = tab.getSelectedRows();
    for (int i = 0; i < rows.length; i++) {
    tabMod.removeRow(rows[i] - i); // delete from JTable
    enquiries.remove(rows[i] - i); // delete from ArrayList
    }
    }

    // Sort the products in the ArrayList and then
    // reload them into the JTable in the sorted order

    public void sortEnquiries() {
    Collections.sort(enquiries); // sorts into name order
    loadEnquiriesIntoTable();
    }

    // Add a new products to the ArrayList and the JTable
    public void addStockEnquiries() {
    String [] row = new String [4];
    StockEnquiries newEnquiry = new StockEnquiries(txtName.getText(), Integer.parseInt(txtPhone.getText()), txtBranch.getText());

    enquiries.add(newEnquiry); // add to the ArrayList
    row[0] = newEnquiry.getName();
    row[1] = Integer.toString(newEnquiry.getPhone());
    row[2] = newEnquiry.getBranch();
    tabMod.addRow(row); // add to the JTable
    }
    public void loadInitialEnquiries() {
    BufferedReader br = null;
    try {
    br = new BufferedReader(
    new FileReader("stockEnquiryLog.txt"));

    String s;
    String name = "";
    String phone = "";
    String branch = "";
    String enquiry ="";
    String time = "";
    int colCount = tab.getColumnCount();
    String[] row = new String[colCount];

    while ((s = br.readLine()) != null) {
    if(s.equals("<stock_enquiry>")) {

    row[0] = br.readLine(); // name
    row[1] = br.readLine(); // phone
    row[2] = br.readLine(); // branch
    row[3] = br.readLine(); // time
    row[4] = br.readLine(); // enquiry

    time = br.readLine();


    tabMod.addRow(row);
    }
    // Premature closing of InputStream by
    // this misplaced line:
    // br.close();
    }
    // Close the Reader after we are done with it.
    br.close();
    } catch(IOException e) {
    System.out.println("loadInitialEnquiries i/o error: " +
    e.getMessage());
    }
    }





    public void loadEnquiriesIntoTable() {
    tabMod.setRowCount(0);

    String [] row = new String [3];
    for (Iterator i = enquiries.iterator(); i.hasNext() {
    StockEnquiries temp = (StockEnquiries) i.next();
    row[0] = temp.getName();
    row[1] = Integer.toString(temp.getPhone());
    row[2] = temp.getBranch();
    tabMod.addRow(row);
    }
    }


    public static void main(String [] a) throws FileNotFoundException, IOException{
    GUI1 me = new GUI1();
    me.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0) ;
    }
    });
    me.pack();
    me.setVisible(true);
    }
    }

    // i know i have to create a class to represent a thing called a TableModel,apart from this im clueless can someone help
    thank you
    sorry about the newbieness i posted this in someone elses thread

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

  3. #3
    hind is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default

    thank you for link but i have already tried this tutorial and looked at many more tutorials and forums, the SimpleTableDemo.java is not compiling NoClassDefFoundError: sorry for the newb questions i got big problems today:(

  4. #4
    hind is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default

    i tried using Jradiobutton instead but its not working

    this is what i done
    class RadioButtonRenderer implements TableCellRenderer {
    public JRadioButton btn = new JRadioButton();

    public Component getTableCellRendererComponent(JTable table, Object
    value,boolean isSelected, boolean hasFocus, int row, int column) {
    if (value==null) return null;

    if(((Boolean)value).booleanValue())
    btn.setSelected(true);
    else
    btn.setSelected(false);

    if (isSelected) {
    btn.setForeground(table.getSelectionForeground());
    btn.setBackground(table.getSelectionBackground());
    } else {
    btn.setForeground(table.getForeground());
    btn.setBackground(table.getBackground());
    }
    return btn;
    }
    }

    class RadioButtonEditor extends DefaultCellEditor
    implements ItemListener {
    public JRadioButton btn = new JRadioButton();

    public RadioButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    }

    public Component getTableCellEditorComponent(JTable table, Object
    value, boolean isSelected, int row, int column) {

    if (value==null) return null;
    btn.addItemListener(this);
    if ( ( (Boolean) value).booleanValue())
    btn.setSelected(true);
    else
    btn.setSelected(false);

    return btn;
    }

    public Object getCellEditorValue() {
    if(btn.isSelected() == true)
    return new Boolean(true);
    else
    return new Boolean(false);
    }

    public void itemStateChanged(ItemEvent e) {
    super.fireEditingStopped();
    }
    }

  5. #5
    hind is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default compile error

    :mad:
    help please why isnt this compiling i am trying to add checkboxes to column [5].
    import java.io.BufferedReader;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;

    // This program allows a list of Products to be maintained i.e.
    // added, deleted and sorted. The products are displayed in
    // a JTable and also maintained in an ArrayList.

    // Some criticisms of the code:

    // 1. Quite a lot of the code seems concerned with keeping the
    // JTable and the ArrayList contents in step. Perhaps there
    // is a better way to do this by writing my own
    // TableModel.

    // 2. No data validation is implmented

    // 3. The design does not conform to the MVC pattern

    // 4. Only one sort order (by product name) is possible.
    // To make it possible to sort into other orders e.g.
    // by price it would be necessary to use a Comparator object.

    // 5. The ArrayList used does not use generics

    class StockEnquiries implements Comparable {
    private String name;
    private int phone;
    private String branch;

    public StockEnquiries(String n, int p, String b) {
    name = n;
    phone = p;
    branch = b;
    }
    public StockEnquiries() {

    }
    public String getName() {
    return name;
    }
    public int getPhone() {
    return phone;
    }
    public String getBranch() {
    return branch;
    }
    // compareTo() allows Product instances in a container
    // (e.g. an ArrayList) to be sorted by Collections.sort().

    // It can only sort things in one order (e.g. ascending order of
    // name). Need to investigate the use of Comparator objects to
    // allow different sort orders to be defined.

    public int compareTo(Object o) {
    StockEnquiries temp = (StockEnquiries) o;

    // Strings already implement compareTo() so just use that
    return (name.compareTo(temp.name));
    }

    }

    public class GUI1 extends JFrame {

    // A container for the Product instances
    ArrayList enquiries = new ArrayList();

    // GUI bits and bobs
    JPanel panInput = new JPanel(new GridLayout(2,1)),
    panAdd = new JPanel(),
    panDelSort = new JPanel();

    JTextField txtName = new JTextField(10),
    txtPhone = new JTextField(5);
    JTextField txtBranch = new JTextField(100);
    JButton btnAdd = new JButton("Add"),
    btnDelete = new JButton("Delete"),
    btnSort = new JButton("Sort Products");
    private class MyTableModel extends AbstractTableModel {

    private Object[][] data;
    private Object[] columns;

    public MyTableModel(Object[][] data, Object[] columns) {
    this.data = data;
    this.columns = columns;
    }
    public Class getColumnClass(int columnIndex) {
    return data[5][columnIndex].getClass();
    }
    public int getColumnCount() {
    return columns.length;
    }
    public int getRowCount() {
    return data.length;
    }
    public Object getValueAt(int rowIndex, int columnIndex) {
    return data[rowIndex][columnIndex];
    }
    public boolean isCellEditable(int rowIndex, int columnIndex) {
    return (columnIndex == 5);
    }
    private class CheckBoxCellEditor extends AbstractCellEditor implements TableCellEditor {
    protected JCheckBox checkBox;

    public CheckBoxCellEditor() {
    checkBox = new JCheckBox();
    checkBox.setHorizontalAlignment(SwingConstants.CEN TER);
    checkBox.setBackground( Color.white);
    }

    public Component getTableCellEditorComponent(
    JTable tab,
    Object value,
    boolean isSelected,
    int row,
    int column) {

    checkBox.setSelected(((Boolean) value).booleanValue());

    Component c = table.getDefaultRenderer(String.class).getTableCel lRendererComponent(table, value, isSelected, false, row, column);
    if (c != null) {
    checkBox.setBackground(c.getBackground());
    }

    return checkBox;
    }
    public Object getCellEditorValue() {
    return Boolean.valueOf(checkBox.isSelected());


    JTable tab = new JTable();

    // The DefaultTableModel will allow the contents of the
    // JTable to be manipulated.
    myTableModel tabMod = new myTableModel();


    public GUI1() {
    super("stock enquiries list");
    tab.setModel(tabMod);
    tabMod.addColumn("Name");
    tabMod.addColumn("Phone");
    tabMod.addColumn("Branch");
    tabMod.addColumn("time");
    tabMod.addColumn("enquiry");
    tabMod.addColumn("dealt with");



    btnAdd.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    addStockEnquiries();
    }
    });

    btnDelete.setToolTipText("Select the records to delete first");
    btnDelete.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    deleteStockEnquiries();
    }
    });
    btnSort.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    sortEnquiries();
    }
    });

    panAdd.add(btnAdd);
    panAdd.add(new JLabel("Product name:"));
    panAdd.add(txtName);
    panAdd.add(new JLabel("Phone Number:"));
    panAdd.add(txtPhone);
    panDelSort.add(btnDelete);
    panDelSort.add(btnSort);
    panInput.add(panAdd);
    panInput.add(panDelSort);
    getContentPane().add(panInput, BorderLayout.SOUTH);
    getContentPane().add(new JScrollPane(tab));
    loadInitialEnquiries();
    }
    // Delete a product from the ArrayList and from the JTable
    public void deleteStockEnquiries() {
    int [] rows = tab.getSelectedRows();
    for (int i = 0; i < rows.length; i++) {
    tabMod.removeRow(rows[i] - i); // delete from JTable
    enquiries.remove(rows[i] - i); // delete from ArrayList
    }
    }

    // Sort the products in the ArrayList and then
    // reload them into the JTable in the sorted order

    public void sortEnquiries() {
    Collections.sort(enquiries); // sorts into name order
    loadEnquiriesIntoTable();
    }

    // Add a new products to the ArrayList and the JTable
    public void addStockEnquiries() {
    String [] row = new String [4];
    StockEnquiries newEnquiry = new StockEnquiries(txtName.getText(), Integer.parseInt(txtPhone.getText()), txtBranch.getText());

    enquiries.add(newEnquiry); // add to the ArrayList
    row[0] = newEnquiry.getName();
    row[1] = Integer.toString(newEnquiry.getPhone());
    row[2] = newEnquiry.getBranch();
    tabMod.addRow(row); // add to the JTable
    }
    public void loadInitialEnquiries() {
    BufferedReader br = null;
    try {
    br = new BufferedReader(
    new FileReader("stockEnquiryLog.txt"));

    String s;
    String name = "";
    String phone = "";
    String branch = "";
    String enquiry ="";
    String time = "";
    int colCount = tab.getColumnCount();
    String[] row = new String[colCount];

    while ((s = br.readLine()) != null) {
    if(s.equals("<stock_enquiry>")) {

    row[0] = br.readLine(); // name
    row[1] = br.readLine(); // phone
    row[2] = br.readLine(); // branch
    row[3] = br.readLine(); // time
    row[4] = br.readLine(); // enquiry

    time = br.readLine();


    tabMod.addRow(row);
    }
    // Premature closing of InputStream by
    // this misplaced line:
    // br.close();
    }
    // Close the Reader after we are done with it.
    br.close();
    } catch(IOException e) {
    System.out.println("loadInitialEnquiries i/o error: " +
    e.getMessage());
    }
    }





    public void loadEnquiriesIntoTable() {
    tabMod.setRowCount(0);

    String [] row = new String [3];
    for (Iterator i = enquiries.iterator(); i.hasNext();) {
    StockEnquiries temp = (StockEnquiries) i.next();
    row[0] = temp.getName();
    row[1] = Integer.toString(temp.getPhone());
    row[2] = temp.getBranch();
    tabMod.addRow(row);
    }
    }


    public static void main(String [] a) throws FileNotFoundException, IOException{
    GUI1 me = new GUI1();
    me.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0) ;
    }
    });
    me.pack();
    me.setVisible(true);
    }
    }

  6. #6
    CJSLMAN's Avatar
    CJSLMAN is offline Moderator
    Join Date
    Oct 2008
    Location
    Mexico
    Posts
    1,159
    Rep Power
    8

    Default error?

    Please post the complete nastygram that the compiler is spitting out at compile time.

    CJSL
    Chris S.
    Difficult? This is Mission Impossible, not Mission Difficult. Difficult should be easy.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Some other recommendations that will help us help you:
    • make your test of concept code a lot shorter. Just have it create the JTable, display it and try to see if you can get checkboxes working or not. It should compile on our boxes. Leave the other stuff non-essential to your problem out.
    • when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:

      Java Code:
      &#91;code]
        // your code block goes here.
        // note the differences between the tag at the top vs the bottom.
      &#91;/code]

  8. #8
    hind is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

    Default

    iam getting compile error
    invalid method declaration; return type required
    public GUI1() {
    expected }

  9. #9
    hind is offline Member
    Join Date
    Jan 2009
    Posts
    7
    Rep Power
    0

Similar Threads

  1. insert row and column and delete row and column
    By daredavil82 in forum New To Java
    Replies: 13
    Last Post: 09-22-2011, 07:10 PM
  2. tooltips for JTable column headers
    By fossildoc in forum AWT / Swing
    Replies: 2
    Last Post: 12-18-2008, 12:42 PM
  3. Regarding JTree with JCheckBox and JRadioButton
    By partha_adt in forum AWT / Swing
    Replies: 0
    Last Post: 11-11-2008, 11:03 AM
  4. How to sort column in JTable
    By johnt in forum AWT / Swing
    Replies: 3
    Last Post: 06-14-2008, 06:48 AM
  5. jcheckbox issues need help. thanks.
    By carlos123 in forum New To Java
    Replies: 3
    Last Post: 11-05-2007, 11:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •