How do I add a JCheckBox to a JTable - URGENT HELP NEEDED

Hello All,
This is kicking my butt. I need to create a JTable that I can dynamically add and delete rows of data to and this table must contain a JCheckBox which I can read the value of. I've been able to find examples out there that provides the ability to have a JCheckBox in the JTable, but do not also provide the function to add / delete rows from the JTable. I need to have both funtions in my table. Can somebody out there please help me with this?
Here's a simple example that I'm working with as a test to figure this out. This example has the functionality to add rows of data.
Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.*;
public class TableTest extends JFrame implements ActionListener
     JButton btnAdd;
     BorderLayout layout;
     DefaultTableModel model;
     public static void main(String[] args)
          TableTest app = new TableTest();
          app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     public TableTest()
          super("Table Example");
          layout = new BorderLayout();
          Container container = getContentPane();
          container.setLayout(layout);
          btnAdd = new JButton("Add");
          btnAdd.addActionListener(this);
          model = new DefaultTableModel();
          JTable table = new JTable(model);
          // Create a couple of columns
          model.addColumn("Col1");
          model.addColumn("Col2");
          // Append a row
          model.addRow(new Object[] { "v1", "v2" });
          model.addRow(new Object[] { "v3", "v4" });
          JScrollPane scrollPane = new JScrollPane(table);
          container.add(btnAdd, BorderLayout.NORTH);
          container.add(scrollPane,BorderLayout.CENTER);
          setSize(300, 200);
          setVisible(true);
     public void actionPerformed(ActionEvent e)
          if (e.getSource() == btnAdd)
               model.addRow(new Object[]{"Test", new Boolean(true)});
}

I got it, I added the public Class getColumnClass to new DefaultTableModel(). Here it is for your viewing pleasure.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.*;
public class TableTest extends JFrame implements ActionListener
     JButton btnAdd;
     BorderLayout layout;
     DefaultTableModel model;
     JTable table;
     public static void main(String[] args)
          TableTest app = new TableTest();
          app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     public TableTest()
          super("Table Example");
          layout = new BorderLayout();
          Container container = getContentPane();
          container.setLayout(layout);
          btnAdd = new JButton("Add");
          btnAdd.addActionListener(this);
          model = new DefaultTableModel()
               public Class getColumnClass(int col)
                    switch (col)
                         case 1 :
                              return Boolean.class;
                         default :
                              return Object.class;
          table = new JTable(model);
          // Create a couple of columns
          model.addColumn("Col1");
          model.addColumn("Col2");
          // Append a row
          model.addRow(new Object[] { "v1", new Boolean(false)});
          model.addRow(new Object[] { "v3", new Boolean(false)});
          JScrollPane scrollPane = new JScrollPane(table);
          container.add(btnAdd, BorderLayout.NORTH);
          container.add(scrollPane, BorderLayout.CENTER);
          setSize(300, 200);
          setVisible(true);
     public void actionPerformed(ActionEvent e)
          if (e.getSource() == btnAdd)
               model.addRow(new Object[] { "Karl", new Boolean(true)});

Similar Messages

  • How to assign new vendor to existing wage type - urgent help needed!!

    Hi  SAP Gurus,
    I have a query for south African payroll-
    I want to assign an exiSting wage type (<b>i.e Transport 1234)</b> to <b>new vendor (600139)</b>The above wage type is aleady assigned to old vendor (600136)
    Hence from 1st June2007 onwards, the wage type will be assingned to new vendor, hence where we assign this wage type to new vendor?
    I have already done some changes in (IMG--SA payroll Reporting for Posting Payroll Results to AccountingActivities in the AC-SystemAssigning AccountsAssign Vendor Accounts , where I have assigned symbolic a/c to new vendor)
    Also, I have copied the wage type, Transport with new validity i.e 1st June2007.(IMG-SA payroll Activities in the HR-SystemMaintaining Wage Types--Define Posting Characteristics of Wage Types)
    Hence, I wanted to Know, how the wage type will post new vendor form 1st June 07?? is there any other way to addign the wagtype to new vendor??
    Hence, required your valuable inputs for same.......... )
    Points will be rewarded for same
    Tnkx & regds,
    Nithibabu

    Yes ,
    Assigning WT to new vendor through that i explain.
    just assign you WT to Symbolic account and further link will get created.
    Each employee is having its own vendor account if you don't have that then its very difficult to understand where the amount is going
    so when you make a payment to employee that payment is go and seat in to his/her vendor account so for that purpose you have to assign the employee id to employee vendor, so if you don't have relation between employee and vendor how you come to know that for which vendor the amount is paid.
    so for this purpose we need to assign the employee id to vendor.
    in SAP employee is treat as vendor and customer also.
    This setting is done by FI consultant.
    ask your FI consultant he will do for you.
    Vicky

  • How can I add icloud to macbook pro?  Do I need to buy snow leopard & lion?

    How can I add icloud to macbook pro?  Do I need to buy snow leopard & lion?

    Lion 10.7.2 is required for iCloud. Your computer must meet the requirements:
    Lion System Requirements
    Mac computer with an Intel Core 2 Duo, Core i3, Core i5, Core i7, or Xeon processor
    2GB of memory
    OS X v10.6.6 or later (v10.6.8 recommended)
    7GB of available space
    Some features require an Apple ID; terms apply.

  • Urgent help needed - new to Macs, accidently cut and paste over top of photo folder and now no sign of folder or file, no auto back-up in place, how can I restore photos pls

    Urgent help needed - new to Macs, accidently cut and paste over top of photo folder and now no sign of folder or file, no auto back-up in place, how can I restore photos pls

    Thanks for prompt reply, yes we have tried that but have now closed down the browser we where the photos were.
    We haven't sent up time machine, do you know whether there is any roll-back function on a Mac?
    Thanks

  • How do i add data from database to JTable ! Urgent

    How do i add data from database to the columns of JTable?.

    hi,
    Thanks for ur link. but this is just a part of my application which i am developing user interface in swing package for which i want to know how to show data to user in the table format where by table input data will be from the database. say something like todays activity is shown to the user in table format... So u have any idea of how to do this...

  • How can I add a row into a JTable with JButton

    Hi all. I have the following code:
    package gui;
    import db.*;
    import javax.swing.table.AbstractTableModel;
    import java.util.ArrayList;
    public class FoundersTable extends AbstractTableModel{
        private static final int COLUMNS = 8;
        private String columnNames[] = {"��� ����", "���", "�������", "�������", "���������", "��������",
                "����� �� ����������", "������ �� ����, �����"};
        private ArrayList data;
        public FoundersTable(){
            data = new ArrayList();
        public int getRowCount() {
            return data.size();
        public int getColumnCount() {
            return columnNames.length;
        public String getColumnName(int colIndex) {
            return columnNames[colIndex];
        public Object getValueAt(int rowIndex, int columnIndex) {
            return ((ArrayList)data.get(rowIndex)).get(columnIndex);
        public void setValueAt(Object value, int rowIndex, int columnIndex) {
            ((ArrayList)data.get(rowIndex)).set(columnIndex, value);
            fireTableCellUpdated(rowIndex, columnIndex);
        public void addRow(ArrayList neueZeile) {
            data.add(neueZeile);
            int index = data.size() - 1;
            fireTableRowsInserted(index, index);
        public void removeRow(int index) {
            data.remove(index);
            fireTableRowsDeleted(index, index);
        public void removeAllRows() {
            data.clear();
            fireTableRowsDeleted(0, 0);
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
    }Now in my MainJFrame class I have one button for additing and one button for removing a selected row. How can I add/remove rows with this two buttons.
    Thanks

    No my question is how can I add and remove rows WITH buttons My point was the code is the same. You use the addRow(...) method. Why did you write an addRow(...) method if you aren't going to use it?
    I don't understand your problem. Do you not know how to write an ActionListener?

  • Urgent help needed! How do I use Time Machine to restore my System disc?

    I need urgent help. First I discovered that my Library folder was empty. When I tried to restore the library to an earlier version via Timemachine it would not let me because it said the system was in use. Trying to start-up from another system on another internal drive and using various disc repairs resulted in the whole volume to disappear.
    Question is how do I get the earlier system from my Timemachine backup drive? I have another Mac where I can attach the TIme machine HD to. Can I restore it from there and then copy the files over to my corrupted disc? All my programs are on there as well, which would take me days to re-install and then there are the other bits, emails, photos etc. Can anyone help?

    lightandmagic wrote:
    Thanks for your sympathy Pondini and the encouragement. You just reminded me that I will lose a whole working day restoring !!! Do you happen to know where the emails are kept on the system and the address book? I better nick those as well as my other life sustaining bits before its too late. I don't trust anything any more.
    I don't know what you mean by "nick those." Time Machine will put everything back the way it was at the time of the backup (unless you'd excluded things).
    Do you mean you want to restore things from the period after the backup you selected?
    For Address Book or Apple Mail, start the application, then +Enter Time Machine,+ navigate to your latest backup, and you'll have a prompt to restore. For Mail, you can restore an entire mailbox. When you exit from TM, you'll see a new folder in your Mail sidebar with the restored items, so you can sift through them and move, delete, or leave them as you wish.
    Other items, you'll have to locate and restore via the Finder > Time Machine.

  • I need to sort and organize all my email addresses in apple mail? - where are they and how can I organize and copy them ? urgent help needed please

    really need urgent help - where do I find the entire list of all my email addresses? and how do I sort and organize them into folders ?

    really need urgent help - where do I find the entire list of all my email addresses? and how do I sort and organize them into folders ?

  • How to find end of the Page in Crystal ? or I need to add one Horizontal line at the end of the page.--- URGENT HELP NEEDED

    Hi friends,
    I need to add one horizontal line  for the detail section at the end of the page.
    I tried to put that line in page footer and i tried with Box also. Both are not properly working. Some space problem is coming.
    Is there any feature to find end of the Page.
    I want report format like this.
    set id  |  set name |  date  Name
      1         x           dddd   vijay
                            dddd   sarathi
                            dddd    reddy
    (End of the page)
    Thanks in advance...
    vijay.

    Do you know how many detail records are showing up per page?
    If you do - you could create a Details B section that is suppressed except for on Record N (where N is a counter, and N is the last Detail record that will show up on a page).
    The Page footer is indeed built so that it will be rendered at the bottom of your physical page of paper.

  • How can I get the JCheckBox value in JTable?

    I have a JTable with JCheckBox inside. How can I get the value when the user turn on or off the check? I need to do this when the user change the value.
    Thanks for any help.
    Renato

    Hi again,
    no - the datamodel is a class that implements the TableModel-interface - if you do not use your own model in JTable, an instance of DefaultTableModel is used - you can subclass DefaultTableModel and overwrite its setValueAt(...)-method. When you instantiate your JTable do it by passing your DefaultTableModel subclass to the constructor or in the way you do it right now and replace the default model with your model using the setModel(...)-method of JTable.
    greetings Marsian

  • How can you add artwork ?i'm gonna die help pls..

    hi i have 30g ipod white video
    i downloaded itunes 7.0 and i updated my ipod then i restore my ipod and started to drag and drop my songs after i finish transfering songs i also drag and drop the album artworks of the album everything seems ok when you look at itunes .. (and i also thicked display album artwork) and i opened my ipod when i looked the song there is no album artwork ... help me pls..

    lucycy,
    Try this -> iPod 101 - Crank Up the Tunes
    Also, for information on getting an iPod started, read this -> Fast Start: Guide to iPod basics
    When the above poster referred to "manual syncing", that means to drag-and-drop songs to your iPod (in iTunes); as opposed to wither of the two "automatic" options.
    Here's when "Edit -> Preferences -> iPod -> Music" settings look like:
    Manually managing music on your iPod
    -Kylene

  • How do you add bookmarks in safari detail please! HELP!

    detail needed

    Hi
    Click on the Help menu at the top of the screen and type bookmark
    Post back if there is something that isn't covered here.
    Have a good weekend.
    Clint

  • Urgent help needed: how to display a list of records on the screen

    Hello,
    This is very urgent. Can anyone help me. I have posted this query of mine before also but still no reply came. My whole application is dependent on this problem. Actually I am developing an application for mobile phone using MIDP. I have a record store which contains personal details for users. I am able to add records to the record store. Now I want that these records can be edited. For this I want to display a list of firstname field on the screen (and not console) so that i can select a user to edit its details. I have written the code to read the records and individual fields and display it on the console but i want to display that list on screen. I tried list and array but it s giving some error.
    I am giving the code to read the records below. Please tell me how can I display it in a list on the screen.
    public void readStream(){
    try
    byte[] recData=new byte[50];
    String varname;
    ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
    DataInputStream strmData=new DataInputStream(strmBytes);
    if (rsperdt.getNumRecords() > 0){
    ComparatorString comp=new ComparatorString();
    int i=1;
    RecordEnumeration re=rsperdt.enumerateRecords(null, comp, false);
    while(re.hasNextElement()){
    rsperdt.getRecord(re.nextRecordId(), recData,0);
    System.out.println("Record #" + i );
    varname = strmData.readUTF();
    System.out.println("Name #"+varname);
    System.out.println("---------------------------");
    i=i+1;
    strmBytes.reset();
    comp.compareStringClose();
    re.destroy();
    strmBytes.close();
    catch(Exception e){
    System.err.println("read Records class:read");
    }

    I could not understand ur point "post the code in tags". I am pasting the code below. Please help as my whole application is stuck due to this problem and I have a deadline of 7th oct.
    This midlet is getting called from some other midlet.
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.rms.*;
    import java.io.*;
    import java.util.*;
    public class frmread extends Form implements CommandListener
    static final String rec_store="db_per";
    private RecordStore rsperdt=null;
    private Vector vecname;
    private ChoiceGroup chname;
    private boolean flagSortByPriority = false, flagShowPriority = true;
    private Form fmmain;
    private Command cmdBack;
    private teledoc midlet;
    public frmread(String title, teledoc midlet)
    super(title);
    this.midlet = midlet;
    openRecStore();
    this.setCommandListener(this);
         chname = new ChoiceGroup("new", Choice.EXCLUSIVE);
         vecname = new Vector();
         cmdBack = new Command("Back", Command.BACK, 1);
    fmmain = new Form("Record Search");
         addCommand(cmdBack);
    setCommandListener(this);
    readStream();
         rebuildTodoList();
         closeRecStore();
    * Process events for this form only
    protected void rebuildTodoList()
    for(int j=chname.size(); j>0; j--)
         chname.delete(j-1);
         int priority;
         todoitem item;
         String text;
         StringBuffer sb;
         for (int j=0; j<vecname.size(); j++)
              item=(todoitem) vecname.elementAt(j);
              priority = item.getPriority();
              text = item.getText();
              sb = new StringBuffer((flagShowPriority ? (Integer.toString(priority) + "-"): ""));
              sb.append(text);
              chname.append(sb.toString(), null);
    public void commandAction(Command c, Displayable s)
    if (c == cmdBack){
    midlet.displayteledoc();
    public void readStream(){
    try
    byte[] recData=new byte[100];
    String varname;
    int varname1=0;
         ByteArrayInputStream strmBytes = new ByteArrayInputStream(recData);
         DataInputStream strmData=new DataInputStream(strmBytes);
         if (rsperdt.getNumRecords() > 0){
    ComparatorString comp=new ComparatorString();
    int i=1;
              int id = 1;
              vecname.removeAllElements();
              RecordEnumeration re=rsperdt.enumerateRecords(null, comp, false);
    while(re.hasNextElement()){
         rsperdt.getRecord(re.nextRecordId(), recData,0);
    System.out.println("Record #" + i );
    varname = strmData.readUTF();
                   varname1 = strmData.readInt();
                   id = re.nextRecordId();
                   System.out.println("Name #"+varname);
                   todoitem item = new todoitem(varname1, varname, id);
                   vecname.addElement(item);
                   System.out.println("---------------------------");
                   i=i+1;
    strmBytes.reset();
              comp.compareStringClose();
              re.destroy();
    strmBytes.close();
    catch(Exception e){
    System.err.println("read Records class:read");
    public void openRecStore(){
    try{
    rsperdt=RecordStore.openRecordStore("db_per",true);
    catch(RecordStoreException e){
    db(e.toString());
    public void closeRecStore(){
    try{
    rsperdt.closeRecordStore();
    catch(Exception e){
    db(e.toString());
    public void db(String str){
    System.err.println("Msg:" + str);
    class ComparatorString implements RecordComparator{
    private byte[] recData = new byte[20];
    private ByteArrayInputStream strmBytes = null;
    private DataInputStream strmDataType = null;
    public void compareStringClose(){
    try{
    if(strmBytes != null)
         strmBytes.close();
    if(strmDataType != null)
         strmDataType.close();
         catch (Exception e)
    public int compare(byte[] rec1, byte[] rec2)
         String str1, str2;
         try {
              int maxsize = Math.max(rec1.length, rec2.length);
              if (maxsize > recData.length)
              recData = new byte[maxsize];
                   strmBytes = new ByteArrayInputStream(rec1);
                   strmDataType = new DataInputStream(strmBytes);
                   str1=strmDataType.readUTF();
                   strmBytes = new ByteArrayInputStream(rec2);
                   strmDataType = new DataInputStream(strmBytes);
                   str2=strmDataType.readUTF();
                   int result=str1.compareTo(str2);
                   if (result == 0)
                   return RecordComparator.EQUIVALENT;
                   else if (result < 0)
                   return RecordComparator.PRECEDES;
                   else
                   return RecordComparator.FOLLOWS;
                   catch (Exception e)
                   return RecordComparator.EQUIVALENT;

  • How to make JPanel as JTable Cell Editor (Urgent help needed)

    Hi!
    I want to make JPanel (with a JTextField, 3 JLabels and 1 JTextArea) as cell editor for one column. Can somebody help me on this?
    Does anybody have any sample code? I will greatly appreciate ur help.
    Thanks,
    Snehal

    Okie. In "How to use JTables" page found in the JAVA website (there is a link from the JTable section of the JAVA API documentation), there is a sample code for a sample color chooser. What this does is, adds a button with its action listener set to pop up a color chooser window. In this, rendering is still through a JLabel.
    This example would be of good help to you. Plus, this example gives me a feeling that what u ask is possible.

  • Urgent help needed -- how to submit a web page from a PL/SQL api

    Hi,
    Could anyone tell me how to submit a remote web page through pl/sql
    Thanks,
    Rachna

    I am not sure what you mean by this question.
    You can submit from PL/SQL to an external webpage/website using the UTL_HTTP package.
    You can submit from an external webpage to a PL/SQL package if that package is invoked by you webserver. The most direct way is using the MOD_PLSQL module for Apache that Oracle ships as HttpServer and that is the foundation for Oracle Portal and HTML DB. Alternatively your webpage can submit to a JSP that invokes your PLSQL package through JDBC.
    best regards,
    Lucas

Maybe you are looking for

  • What are the parameters for the processes menu items

    Is there anywhere that lists out what the exact parameters of the process menu items are. i.e "Make Louder, Normalize, Hard Limit, Equalize Volume Levels", For instance when you use "Make Louder" you see the dialog box title change from "Analyzing pe

  • HT1689 The iTunes Store won't open on my iPod, what happened?

    My iTunes Store won't open. When it is clicked, it just flashes back to the home screen. I restarted it and turned it off and back on, but nothing helped. This all started after I upgraded to iOS 7.

  • Please help with tag files

    Hello, Is it possible to use to invoke tag files from other tag files in the project? Is it allowed by spec? 1. Create empty project. 2. Create tag file tagFile1.tag using wizard. 3. Create tag file tagFile2.tag using wizard. 4. Drag TagFile2 tag fro

  • I don't know what to even call this type of problem

    I have no idea what to even name what has happened to my MacBook Pro in the last two days, so I don't quite know where to begin to look for help. As best I can describe it--a constant, VERY rapid opening of files--to the point that I thought the whol

  • Problem opening multiple .tdms files in subroutine

    Heya- I'm using LabVIEW 8.2, professional development system. I'm using the Open / Read / Close TDMS functions as part of a subroutine in a larger program.  The subroutine is supposed to open one of several TDMS files (each of which contains bulk dat