How to put JComboBox in JTable?

I'm trying to put JComboBox in JTable, the following is my table model. The problem is that it doesn't display a JComboBox but a string of it, something like "MyTableModel$JComboBox....". Any help would be appreciated.
class MyModel extends AbstractTableModel {
String[] columnNames = {"Column One", "Column One"};
String[] boxItem = {"Item One", "Item Two"};
String[] rows = {"Row One", "Row Two"};
JComboBox[] boxes = {
new JComboBox(boxItem),
new JComboBox(boxItem)
Object[][] data = new Object[][]{rows, boxes};
public Object getValueAt(int row, int col) {
return data[col][row];
}

Hi,
the TableModel is the wrong place to put the combo box. A model is just a representation for the data displayed in the table.
A combo box, on the other hand, is a certain way for the user to edit the values in the table (and in the model). To change the way a user edits in a table you have to set the TableCellEditor. You can do this for the whole table or for a certain column.
// in the JTable's constructor or init method
// to set JComboBox in 2nd column
// get 2nd column
TableColumn column = myTable.getColumnModel().getColumn(1);
// create combo box
JComboBox combo = new JComboBox();
combo.add("ItemOne");
combo.add("ItemTwo");
// set as editor for the column
DefaultCellEditor editor = new DefaultCellEditor(combo);
column.setCellEditor(editor);This is just an example. Try it w/ a simple table.

Similar Messages

  • How to put data in JTable from database

    hi everyone,
    i want to query the databse and put the result in the JTable and if possible i want to edit some information. For example: i have 5 records in the database query them and place them in JTable and each record has its own status. if i want to change the status For Example: the status of the 4 records are "Cleared" and the other one is "RELEASEd" so if i have JCombo Box to set the 4 records in to RELEASED status and then save the changes is that possible?
    thank you
    dhing

    In [url /thread.jsp?forum=54&thread=387565]this thread I describe how to use a result set as a basis for table data. Check some database tutorials for information on getting a result set.

  • SAMPLE CODE  + HOW ADD JCOMBOBOX IN JTABLE

    HI,
    ALL OF U
    PLZ SUGGEST ME HOW TO ADD COMBOBOX IN JTABLE.
    AND ALSO TELL HOW WE CAN ADD ITEMS IN COMBOBOX AT RUN TIME.
    PLZ SUGGEST ME.
    THANX IN ADVANCE.
    BYE

    Hi if you google you find a lot
    http://www.google.be/search?q=JTable+combobox&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:nl:official&client=firefox-a
    and
    http://www.google.be/search?q=JTable+combobox+example&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:nl:official&client=firefox-a
    Satanduvel

  • Multiple keystrokes selection for a JComboBox in JTable

    Has anyone used multiple keystrokes selection in a JComboBox inside JTable before? I can get it done outside JTable by using: http://javaalmanac.com/egs/javax.swing/combobox_CbMultiKey.html
    Looks like JTable has all kinds of problems to support JComboBox.
    Suggestions?
    Thanks,
    James

    If I read you right, you want to use a multiple keystroke combo box as an editor in a JTable?
    If you create the JComboBox as you would like it and then install it as an editor in the column(s) JTable the editor will work like the JComboBox
    Example:
    //- you would have that keyselection Manager class
    // This key selection manager will handle selections based on multiple keys.
    class MyKeySelectionManager implements JComboBox.KeySelectionManager {    ....    };
    //- Create the JComboBox with the multiple keystroke ability
    //- Create a read-only combobox
    String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
    JComboBox cboBox = new JComboBox(items);
    // Install the custom key selection manager
    cboBox.setKeySelectionManager(new MyKeySelectionManager());
    //- combo box editor for the JTable
    DefaultCellEditor cboBoxCellEditor = new DefaultCellEditor(cboBox);
    //- set the editor to the specified COlumn in the JTable - for example the first column (0)
    tcm.getColumn(0).setCellEditor(cboBoxCellEditor); Finally, it may be necessary to to put a KeyPressed listener for the Tab key, and if you enter the column that has the JComboBox:
    1) start the editting
    table.editCellAt(row, col);2) get the editor component and cast it into a JComboBox (in this case)
    Component comp = table.getEditorComponent();
    JComboBox cboComp = (JComboBox) comp;3) give this compent the foucus to do its deed     
    cboComp.requestFocus();Hope this helps!
    dd

  • How to use JEditorPane in Jtable

    Hi
    I'm trying to put HyperLinks in JTable but i don't not how to add Hand Cursor when mouse is over a hyperLink and how to active it when click it.
    Thanks
    DefaultTableModel tableModel = new DefaultTableModel(new String[][]{{"<a href=www.google.com>Google</a>, <a href=www.yahoo.com>Yahoo</a>"}}, new String[]{"URL"});
    JTable table = new JTable(tableModel);
    table.setRowHeight(24);
    table.setDefaultRenderer(Object.class, new EditorPaneTableCellRenderer());
    class EditorPaneTableCellRenderer extends JEditorPane implements TableCellRenderer
    EditorPaneTableCellRenderer()
    setContentType("text/html");
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    String link = String.valueOf(value);
    setText(link);
    setBackground(isSelected? table.getSelectionBackground() : table.getBackground());
    return this;
    }

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5273661&tstart=0

  • How to Put Legend for Multi Series Stacked Graph...?

    Hi Experts,
    Please guide me how to put Legend for Multi Series Stacked Graph...?
    Its very URGENT...!!!!
    Thanks in advance...
    Regards,
    Manoj

    I searched the forum using "jcombobox multiple columns". The first posting I read had a link to a posting with 4 different solutions.
    Why is it so hard to search the forum before posting a question????

  • Placing JComboBox in JTable ColumnHeader

    Can any one help me on how to place a JComboBox in JTable ColumnHeader....?

    try this:
    package ComponentDisplayer;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    class JComponentCellRenderer implements TableCellRenderer
        public Component getTableCellRendererComponent(JTable table, Object value,
              boolean isSelected, boolean hasFocus, int row, int column) {
            return (JComponent)value;
    }and
    package ComponentDisplayer;
    import java.awt.*;
    import java.util.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class Pable
         public static void main(String[] args)
              JFrame frame = new JFrame("Table");
              frame.addWindowListener( new WindowAdapter() {
                   public void windowClosing(WindowEvent e)
                        Window win = e.getWindow();
                        win.setVisible(false);
                        win.dispose();
                        System.exit(0);
              JTable table = new JTable(3,2);
                 TableCellRenderer renderer = new JComponentCellRenderer();
                  TableColumnModel columnModel = table.getColumnModel();
                  TableColumn column0 = columnModel.getColumn(0);
                  TableColumn column1 = columnModel.getColumn(1);
                  column0.setHeaderRenderer(renderer);
                  JComboBox jb=new JComboBox();
                  jb.insertItemAt("well", 0);
                  jb.insertItemAt("done", 1);
                  column0.setHeaderValue(jb);
                  column1.setHeaderRenderer(renderer);
                  column1.setHeaderValue(new JComboBox());
              table.setAutoResizeMode(table.AUTO_RESIZE_ALL_COLUMNS);
              table.setSize(900, 1200);
              JScrollPane sp = new JScrollPane(table);
              table.setColumnSelectionAllowed(false);
             table.setRowSelectionAllowed(true);
              frame.getContentPane().add( sp );
              frame.pack();
              frame.setVisible(true);
              //frame.show();
    }as you can see adding it is not that hard but you cannot interact with them because if my memory serves well, tableheaders cannot have focus by default. So you gotta write your own implementation of header (may be using sth like: )public class MyTableHeaderRenderer extends JComponent implements
              TableCellRenderer {
         public MyTableHeaderRenderer() {
              // TODO Auto-generated constructor stub
         public Component getTableCellRendererComponent(JTable arg0, Object arg1,
                   boolean arg2, boolean arg3, int arg4, int arg5) {
              // TODO Auto-generated method stub
              return (JComponent)arg1;
         }and then use this as default renderer in your implementation.)
    E,ther you have to handle setfocus thing or keep track of mouse events
    I hope this helps

  • How do I create a JTable with some empty cells in it?

    I have a three column JTable. The first column is a String showing description. The second column contains numbers (double) and the third column also contains numbers. In some cases not all cells in a row should contain data. So for instance, I could have row one showing only description (a String in the first column), and then row two showing description (a String in the first column) and a number (a double in the second column) in columns one and two respectively. My problem is that, the data gets copied from the cells with data to the cells which are supposed to be empty. So, how do I create a JTable with some empty cells in it.

    I have tried empty strings for those values, but it did not work. My table puts objects in an arraylist called reconciliation. The arraylist takes different objects with the same super class. The code below explains. Are you suggesting I pass null to my constructor?
    JTable table = new JTable(new ReconTableModel());The method below is from the table model
    protected  List<Reconciliation> reconciliation = new ArrayList<Reconciliation>();
    protected void fillModel(){
          reconciliation.add(new CashBook("Cash Book Report"," "," "));
          reconciliation.add(new CheckingBankAccount("Checking Bank Account"," "," "));
          reconciliation.add(new BankBalance("Bank Balance As Per Bank Statement",500," "));
          reconciliation.add(new PaymentVouchers("Payment Voucher Receipt",300," "));
          reconciliation.add(new DepositVoucher("Deposit Voucher Receipt",1000," "));
          reconciliation.add(new ReconciledBalance("Reconcilied Bank Balance",1200," "));
          reconciliation.add(new BalanceAt("Bank Balance At",800," "));
          reconciliation.add(new Difference("Difference",400," "));
          Collections.sort( reconciliation, new Comparator<Reconciliation>(){
          public int compare( Reconciliation a, Reconciliation b) {
            return a.getTransactionName().compareTo( b.getTransactionName());
      }

  • JComboBox within JTable

    Hi,
    I've got the following problem with my JComboBox:
    The JComboBox zcb is filled out of a database (this works!). This JComboBox is a column of the JTable jtbDauerlaeufe (this works, too!).
    Now the strange behaviour:
    1.) In the application I open for the first time the JDialog which the JTable is part of.
    2.) Then the correct value in the JTable column is displayed.
    3.) I click with the mouse in the column with my JComboBox => the ComboBox opens, but not with the selected (or displayed) value of my column, but with the first value of available JComboBox-values :-(
    4.) When I leave the JComboBox and open it again, then the selected/displayed value of my column is also selected within my JComboBox.
    Now my question:
    Why is this behaviour not available when I open my JComboBox the first time? And what have I to do for getting the selected value of my jtable-column when I open the JComboBox the first time???
    JComboBox zcb = new JComboBox();
    // gets the JTable-column for the JComboBox
    tc = jtbDauerlaeufe.getColumn(model.getZETColName());
    // fill the values in the JComboBox
    broker.getZaehlereinheitenBroker().fillComboBox(zcb);
    tc.setCellEditor(new DefaultCellEditor(zcb));
    Any help & hint is very welcome,
    Fe

    Hi
    The problem is not with ur JComboBox.. It lies where u set the datavector of the JTable..
    1. What type of objects does the ComboBox hold. Simple String or other Objects??
    2. How do u set the JTable data the first time??
    First time I think u wuld be explicitly setting the table data with different kind of objects , say string value for the column holding the combobox. Thats y the first time while loading it works properly.
    Try changing the combobox values with strings instead of other Objects.. tell me if it works :)
    Nisha

  • How to put web app to Oracle 8i Jserver ?

    I've developed a web app with JDev3.1 , Oracle8i 8.1.6 on NTServer4.0.
    and want to put it on Oracle Jserver 8.1.6:
    The app works well within JDev3.1.
    I depolyed my Business Components project and test well.
    I would like to know how to put web app to Jserver. Is it possible?

    when you say "web app" i am assuming you mean an applet, servlet or java server page(jsp) ??
    if you mean this, then you need to move to the rdbms 8.1.7 environment for this support.
    rdbms 8.1.7 supports servlets and jsp's in two different ways :
    externally -- on the rdbms 8.1.7 platform
    they can be run in an external apache front end included with the 8.1.7 rdbms.
    internally -- inside the rdbms 8.1.7
    they can be deployed internally to 8.1.7 in the "oracle servlet engine" (ose)
    applets and html static pages still need to be deployed to a web server on the mid-tier OR the external apache front end included with the 8.1.7 rdbms to optimize performance.
    i hope this helps ...
    p.s. if i've misunderstood your question , please restate it.
    null

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • How to put a few pages together as a panel group in the same screen ?

    Dear Friends,
    Hello. I am developing the accounting application of Journal Entry module. I have developed 5 pages for a journal entry: Journal header, Journal Line, Journal total, Journal Error and Journal Approval. I want to put 5 pages together as a panel group in the same screen so that users are convenient to use them. The format is as follows:
    Header | Lines | Total | Error | Approval
    When a user click on Header or Lines or Total or Error or Approval, its related page is displayed below it on the screen. But I don't understand how to put "Header", "Lines", "Total", "Error" and "Approval" together as above format and link them to its related page. Can anybody tell me how to do that ? Thanks.
    Lucy

    Mike,
    It's correct to make 5 pages as a seperate component.
    I am developing an accounting system using PeopleTools by myself.
    Because you understand PeopleSoft financial application, please tell me the 2 questions as follows:
    First, In Journal Line page, when select "edit Journal" and click button "process", the system check the Journal against Budget, if it's Ok, the System assign Journal ID for the Journal and put "valid" into the field of "Budget Status" and "Journal Status" in Total page. If it's not OK, the system send error message into Error page. Do you know how developer do that ?
    Second, In Journal Line Page, when select "Submit Journal" and click button "process", the system send the Journal to Approval page for approval. Do you know how developer do that ?
    Lucy

  • How to put text line just for a moment ?

    Hi,
    Do you know how to put a text line  just  for one photo? I mean I have more photos  in one portfolio but i need the text line to be seen just for one photo for the others no.
    Thank you in advance.

    You can use composition for this , where you can insert text frame for that specific photo where you want to add some description and for rest dont use text frame.
    Thanks,
    Sanjit

  • How to put separator lines in menu items in a gui status ?

    Hi,
    I have created gui status for my z transaction
    I need the separator lines in the menu items like it is seen in std transactions
    For example, in any screen , in the Help menu, we can see the following.
    Application Help
    SAP Library
    Glossary
    (line)
    Release notes
    (line)
    SAP Service Marketplace
    could you please help me how to put the lines ?
    thanks

    Hi,
    Goto Your GUI status.click on your  MENU bar.
    under the menu bar you will have your own menu items.
    where ever you want separator line  do the following way.
    you will have 2 columns under menu bar
    1) code
    2) text.
    under code dont put anything.
    but under text column you put dashes and enter or select right click there and choose separator line.
    you will get separator line.
    activate and run the ztcode.you will get .
    code                                            text
    Application Help                         
    SAP Library
    Glossary
    Release notes
    SAP Service Marketplace
    Thanks
    Parvathi

  • I have an ipod touch and i put cds on itunes on my pc , but i cant figure out how to put the music from the cds on my ipod .. can u help me ?

    i have an ipod touch and i put cds on itunes onmy computer , but i cant figure out how to put the music from the cds on my ipod touch can anyone help me?

    ok i select th e music from my music libary and go to file and click sync to my ipod and when it gets to step 3.. it says waiting for changes to be made.. yes the songs play on the itunes ..  and no it wasnt the same computer i used last time

Maybe you are looking for

  • My itunes account is locked , what should i do?

    i was trying to purches chips for zynga poker and they asked me about the security questions i answered before and i couldnt remember the answeres and my account got locked , what should i do?

  • SQL SERVER 2000 - REPORTING SERVICES DATABASE ?

    Hi! A very basic question, how to know where reporting services points to the database and server ? miga

  • BOM and routing selection during production order creation

    I am having a material which is having only one BOM and one routing. Now for this material in the material master in the selection method indicator i have put as 3 as selection only by production version. But i have not maintained any production vers

  • App store error message downloading BBM to iPod touch

    Has anybody seen this message? It's my daughters iPod. Trying to get her BBM so she and I can chat when I'm away (I have BB...not always carryin my iPad around with me). I did have BBM on my previous iPhone 5S, but it doesn't appear in my purchased a

  • Importing Web Service in SAP CPS

    Hi everyone, Build version M33.104. We are trying to import web services using the WSDL url. When i use a URL, that doesn't prompt for userid/password, it is possible to import the job definition. When i use a URL, that prompts for userid/password (w