Combobox in JTable question

Hello,
I have to make a button in a JTable that is activated with a right button and then like in a combobox appears a menue and every item in this menue should be activated with the left button and perform some action. Like in windows right click and then select smth.
My question is should I do it with Combobox and if yes how to activate it with the right button because it always listens to left button. It is implemented with action listener and I tried mouse listener but it wouldn"t listen to that. I will be glad to any solutions.
Thanx,
Miroslav

Hi,
And thank you for the answer. i think I will use jpop menu as u sujested(Thank you for that). Now I should only see how to make the render and the editor to put it in a cell in a JTable.
It should be activated with the right button, beacause my task is such and because I also think that it is better this way. II mean it is more natural than with the left button.
Miroslav

Similar Messages

  • Problem of selecting combobox in JTable!!

    I click comboBox in jtable and choose one item
    then move mouse away
    and then click the comboBox again
    It turns out to be strange:
    the selectedItem of the comboBox changes the first item at once
    I refered to the demo "TableRenderDemo.java" in http://java.sun.com/docs/books/tutorial/uiswing/components/example-swing/TableRenderDemo.java
    I just wanna do things like that
    but for some unknown reasons,I fail
    I compared two codes but found nothing

    here I'm giving a simple sample code. Refer this..
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class Class1 extends JFrame {
    JScrollPane jScrollPane1 = new JScrollPane();
    JTable editableTable1 = new JTable(3, 3);     
    public Class1() {
    try {          
    JComboBox c = new JComboBox();
    c.setEditable(true);
    c.addItem("a");
    c.addItem("b");
    DefaultCellEditor cellEditor = new DefaultCellEditor(c);
    TableColumn tc = editableTable1.getColumnModel().getColumn(0);
    tc.setCellEditor(cellEditor);
    this.getContentPane().setLayout(null);
    jScrollPane1.setBounds(new Rectangle(25, 19, 330, 180));
    this.getContentPane().add(jScrollPane1, null);
    jScrollPane1.getViewport().add(editableTable1, null);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    } catch(Exception e) {
    System.out.println("Exception in Class1:"+e);
    public static void main(String[] args) {
    Class1 class1 = new Class1();
    class1.setSize(400, 400);
    class1.setVisible(true);

  • Addiing ComboBox in JTable

    Can any one help mee how to add combobox in jtable i am using Abstracttablemodel.

    yes these the code where i am setting my editor and combobox
    import java.sql.ResultSet;
    import java.sql.*;
    import java.util.*;
    import javax.swing.JTable;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class clsCustMast extends clsMSGen{
        String strQuery,
                 querySrch1,
                 querySrch2;
        String strTab1Rec;
        String strTableName;
        String []strTmp;
        public clsValidate val;
        public boolean flgInsrtTab1,
                           flgInsrtTab2,
                           flgErr;
        public String strCmbFrom,
                             strCmbTo;
       /* public JComboBox cmbRgn,
                              cmbCntry;*/
        int        intSlctdTab;     
        private int intCol,
                        rowCntTab1,
                        rowCntTab2;
         final static int CNS_TAB1 = 0;
         final static int CNS_TAB2 = 1;
         final static String CNS_MANDT = "1";
         final static boolean CNS_FALSE = false;
         final static boolean CNS_TRUE = true;
         final static String strUserPassword  = "manager";          
        public void disp(){
            super.disp();
            flgInsrtTab1 = CNS_FALSE;
            flgInsrtTab2 = CNS_FALSE;
            // to get all region ids from the  tble T_regionmast and populate it in the cmbReg to be displayed in the grid
            populateRegionCntryCmb();
            // to get all region ids from the  tble T_countrymast and populate it in the cmbCntry to be displayed in the grid
            //populateCntryCmb();
            intCol = 0;
            strQuery = "select a.f_custid,a.f_postcd,a.f_faxno,a.f_phoneno,a.f_regionid," +
                      " a.f_cntryid, a.f_delflag from t_custmast a,t_custtran b" +
                      " where a.f_custid = b.f_custid" +
                      " and b.f_langid = 'EN'";
            //System.out.println(strQuery);
            ResultSet Tab1Data = prcQuery(strQuery);
            try{
                 ResultSetMetaData rmdTab1Dt = Tab1Data.getMetaData();
                 intCol = rmdTab1Dt.getColumnCount();
                 ++intCol;
                 strTmp = new String[intCol+1];
                 //JButton btn1;
                 while (Tab1Data.next()){
                      String [] record = new String[intCol];
                      //Object [] record = new Object[intCol];
                      //btn1 = new JButton("C");
                      record[0] = new JButton("B").toString();
                      //record[0] = new Boolean(false);
                      for(int i=1; i<intCol; i++)
                     record= Tab1Data.getString(i);
              if (i==1)
    cmbFrom.addItem(record[i]);
    cmbTo.addItem(record[i]);
    // System.out.println(record[i]);
    model1.addRow(record);
    model1.fireTableChanged(null);      
    catch(SQLException ex)
         System.out.println("Error1");
    ex.printStackTrace();
    strQuery = "select f_langid, b.f_custname, f_city, f_address " +
              "from t_custmast a ,T_custtran b where " +
              "a.f_custid = b.f_custid" +
                        " and b.f_langid = 'EN'";
    ResultSet Tab2Data = prcQuery(strQuery);
    try{
    intCol = 0;     
    ResultSetMetaData rmdTab2Dt = Tab2Data.getMetaData();
    intCol = rmdTab2Dt.getColumnCount();
    while (Tab2Data.next()){
    String [] record = new String[intCol];
    for(int i=0; i<intCol;i++)
    record[i]=Tab2Data.getString(i+1);
    model2.addRow(record);
    model2.fireTableChanged(null);
    catch(SQLException ex)
         System.out.println("Error2");
    ex.printStackTrace();
    System.out.println(intCol);
    //Connect the database and Returns the resultset corresponding to passed query     
         public ResultSet prcQuery(String strQuery){
              ResultSet resultQuery = dbCon.doQuery(strQuery);
              return resultQuery;
         public void populateRegionCntryCmb(){
              cmbRgn = new JComboBox();
              cmbCntry = new JComboBox();
              String queryRgn = "select f_regionid,f_cntryid from t_regionmast";
              ResultSet rsRgn = prcQuery(queryRgn);
              //String[] items = { "one", "two", "three", "four" };
              try{
                   while(rsRgn.next()){
                        //cmbRgn.addItem(rsRgn.getString(1));
                        cmbCntry.addItem(rsRgn.getString(2));
                        //System.out.println(rsRgn.getString(1)+ " " + rsRgn.getString(2));
              }catch(SQLException ex)
    {             System.out.println("Error in region cd retrieve");
    ex.printStackTrace();
              System.out.println(cmbCntry.getItemAt(0));
              //cmbCntry = new JComboBox(items);
              cmbCntry.setEditable( false );
              DefaultCellEditor dceCmbCntry = new DefaultCellEditor( cmbCntry );          
              info_table.getColumnModel().getColumn(6).setCellEditor(dceCmbCntry);
              // Set the first columm to use a ComboBox as a renderer
              info_table.getColumnModel().getColumn(6).setCellRenderer(new clsComboBoxRenderer());
         public void populateCntryCmb(){
              cmbCntry = new JComboBox();
              String queryCntry = "select f_reionid,f_cntryid from t_regionmast";
              ResultSet rsCntry = prcQuery(queryCntry);
              try{
                   if(!rsCntry.next()){
                        System.out.println("No Records in Country Master Table");
                   }else{
                        while(rsCntry.next()){
                             cmbCntry.addItem(rsCntry.getString(1));
                             //System.out.println(rsCntry.getString(1));
              }catch(SQLException ex)
         System.out.println("Error in region cd retrieve");
    ex.printStackTrace();
              System.out.println(cmbCntry.getItemAt(1));
              cmbCntry.setEditable( false );
              DefaultCellEditor dceCmbCntry = new DefaultCellEditor( cmbCntry );          
              info_table.getColumnModel().getColumn(6).setCellEditor(dceCmbCntry);
              // Set the first columm to use a ComboBox as a renderer
              info_table.getColumnModel().getColumn(6).setCellRenderer(new clsComboBoxRenderer());
         class clsComboBoxRenderer extends JComboBox implements TableCellRenderer
              public Component getTableCellRendererComponent
                        JTable info_table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column){
                             removeAllItems();
                             addItem( value );
                             return this;     
         public void add()
              String strAdd1[],
                   strAdd2[];
              intSlctdTab = tabbedPane.getSelectedIndex();
              if ( intSlctdTab == CNS_TAB1){
                   if ( flgInsrtTab1 == CNS_FALSE && flgInsrtTab2 == CNS_FALSE){
                        rowCntTab1 = model1.getRowCount();
                        //add a new row for both tabs when the add button is pressed while tab1 is selected.
                        //Add a new row for the tab1
                        strAdd1 = new String[8];
                        model1.addRow(strAdd1);
                        model1.fireTableChanged(null);
                        flgInsrtTab1 = CNS_TRUE;
                        //Add a new row for the tab2
                        strAdd2 = new String[4];
                        model2.addRow(strAdd2);
                        model2.fireTableChanged(null);
                        flgInsrtTab2 = CNS_TRUE;
                   }else{
                        lblStatus.setText("Save the Records and then Add New one");
              }else if(intSlctdTab == CNS_TAB2){
                   if ( flgInsrtTab2 = CNS_FALSE){
                        rowCntTab2 = model2.getRowCount();
                        //When a add button is pressed while selecting the 2nd tab add new row only to 2nd tab
                        strAdd2 = new String[4];
                        model2.addRow(strAdd2);
                        model2.fireTableChanged(null);
                        flgInsrtTab2 = CNS_TRUE;
                   }else{
                        lblStatus.setText("Save the Records and then Add New one");
         public void save()
              // Decalrion for varaibles in the TAB1
              String strCustId,
                   strDelFlg,
                   strPostCd,
                   strFaxNo,
                   strPhNo,
                   strRgnId,
                   strCntryId;
    boolean flag;                              
              //Assigning the values of the selected row to the corresponding fields
    strCustId = model1.getValueAt(rowCntTab1,1).toString();
    strPostCd = model1.getValueAt(rowCntTab1,2).toString();
    strFaxNo = model1.getValueAt(rowCntTab1,3).toString();
    strPhNo = model1.getValueAt(rowCntTab1,4).toString();
    strRgnId = model1.getValueAt(rowCntTab1,5).toString();
    strCntryId = model1.getValueAt(rowCntTab1,6).toString();
         strDelFlg = model1.getValueAt(rowCntTab1,7).toString();
         flgErr = CNS_FALSE;
         //Validation for mandatory field F_CUSTID
         flag = clsValidate.mandt(CNS_MANDT,strCustId);
    if (flag == CNS_FALSE){
              lblStatus.setText("Please Enter Values for Cust Id Field");
              flgErr = CNS_TRUE;
    //Validation for Mandatory field F_DELFLAG
    flag = clsValidate.mandt(CNS_MANDT,strDelFlg);
    if (flag == CNS_FALSE){
              lblStatus.setText("Please Enter Values for Delete Flag Field");
              flgErr = CNS_TRUE;
    // if no error occurs process the insert process
    if (flgErr == CNS_FALSE){
              String sqlInsrtT1;
              sqlInstrtT1 = "Insert into t_custmast'" + ( "'" +
                             " f_custid,f_delflag,f_postcd,f_faxno,f_phoneno," +
                                  "f_regionid,f_cntryid '" +) "'" +
                                  "(strCustId,strDelFlg,strPostCd,strFaxNo,strPhNo,strRgnId,strCntryId)";
              strTableName = "t_custmast";
         //     sqlInsrtT1 = "insert into t_custmast*/
         /*     StringBuffer InsertSQLT1 = new StringBuffer();
              strTableName = "t_custmast";
              InsertSQLT1.append("INSERT INTO " + strTableName );
              InsertSQLT1.append(" VALUES (");
                   int colCntTab1 = model1.getColumnCount();
                   System.out.println(colCntTab1);
              // for (int i=0; i < colCntTab1-1; i++) {
                   int i = 0;
                   System.out.println("Value at 2,1 " + model1.getValueAt(2,7));
                   /* while(i < colCntTab1){
                   System.out.println(" "+ i);
                   //System.out.print( model1.getValueAt(2,i));
              //     InsertSQLT1.append(model1.getValueAt(rowCntTab1,i));
                   InsertSQLT1.append(model1.getValueAt(2,i));
                   if ( i != colCntTab1-1) {
                        InsertSQLT1.append(",");     
                   }else{
                        InsertSQLT1.append(");");
                   i++;
              //InsertSQLT1.append(");");
              // System.out.println( model1.getValueAt(rowCntTab1,7));
    System.out.println(InsertSQLT1.toString());*/
    public void delete(){}
    public void cancel(){}
    public void goTran(){}
    public void Search(){
         intSlctdTab = tabbedPane.getSelectedIndex();
         if (intSlctdTab == CNS_TAB1 ){
              System.out.println(intSlctdTab);
    querySrch1 = "select a.f_custid,a.f_postcd,a.f_faxno,a.f_phoneno,a.f_regionid,"
         + " a.f_cntryid, a.f_delflag from t_custmast a,t_custtran b"
                        + " where a.f_custid = b.f_custid"
                        + " and b.f_langid = 'EN'"
                        + " and a.f_custid between '" + strCmbFrom + "'"
                        + " and '" + strCmbTo + "'";
         searchCondnTab1(querySrch1);
         intSlctdTab = 3;
    if ( intSlctdTab == CNS_TAB2 ){      
    querySrch2 = "select f_langid, b.f_custname, f_city, f_address"
                        + " from t_custmast a ,T_custtran b "
                        + " where a.f_custid = b.f_custid"
                        + " and b.f_langid = 'EN'"
                        + " and a.f_custid between '" + strCmbFrom + "'"
                        + " and '" + strCmbTo + "'";                     
              searchCondnTab2(querySrch2);
              intSlctdTab = 3;
    public void cmbFromSrch(){
         strCmbFrom = ((String)cmbFrom.getSelectedItem()).trim();
         System.out.println("Combo1 : " + strCmbFrom);
    public void cmbToSrch(){
         strCmbTo = ((String)cmbTo.getSelectedItem()).trim();
         System.out.println("Combo2 : "+ strCmbTo);
         public void searchCondnTab1(String querySrch){
              System.out.println("Tab1 : " + querySrch);
    ResultSet rsSrchTab1 = prcQuery(querySrch);
    try{
         ResultSetMetaData rmdSrchTab1 = rsSrchTab1.getMetaData();
         intCol = rmdSrchTab1.getColumnCount();
         //increase the column count by one for the button
         ++intCol;
         //remove all datas before fetching records according to the conditions
         model1.vctData.removeAllElements();
         //adding records to the vector after fetching the records
         while (rsSrchTab1.next()){
              String [] record1 = new String[intCol];
              record1[0] = new JButton("B").toString();
              for(int i=1; i<intCol;i++)
    record1[i]= rsSrchTab1.getString(i);     
    model1.addRow(record1);
    model1.fireTableChanged(null);      
    catch(SQLException ex)
         System.out.println("Error3");
    ex.printStackTrace();
         public void searchCondnTab2(String querySrch){
              System.out.println("Tab2 : " + querySrch);
              ResultSet rsSrchTab2 = prcQuery(querySrch);
         try{
         ResultSetMetaData rmdSrchTab2 = rsSrchTab2.getMetaData();
         intCol = rmdSrchTab2.getColumnCount();
         //remove all datas before fetching records according to the conditions     
         model2.vctData.removeAllElements();
         //adding records to the vector after fetching the records
         while (rsSrchTab2.next()){
         String [] record2 = new String[intCol];
         for(int i=0; i<intCol;i++)
         record2[i]= rsSrchTab2.getString(i+1);
         model2.addRow(record2);
         model2.fireTableChanged(null);     
         catch(SQLException ex)
              System.out.println("Error4");
         ex.printStackTrace();
         public static void main(String args[]){
         clsCustMast objCust = new clsCustMast();
         objCust.strUserid = "SIVAGURU";
         objCust.strTab1Name = "Basic";
         objCust.strTab2Name = "Details";
         objCust.strTitle = "Customer Maintenance";
              objCust.Tran_code = "XD01";
              objCust.strClsId = "clsCustMast";
              objCust.strLangid = "EN";
         objCust.connectDbase();
         objCust.disp();

  • Combobox in jtable

    suppose you are editing a combobox in a jtable.
    in the combobox, there are items like
    A0
    A20
    C0
    C20
    E0
    E20
    my main goal is traverse and edit the table by keyboard.
    when i go to a jcombobox, e.g. i hit the button C, it only focus the combo, not selecting item.
    JComboBox comboBox = new JComboBox(arr){
                   protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                        int condition, boolean pressed) {
                    boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
                    if (!retValue && isStartingCellEdit() && editor != null) {
                        //editor.setItem(String.valueOf(ks.getKeyChar()));
                        JComponent editorComponent = (JComponent) getEditor().getEditorComponent();
                        InputMap map = editorComponent.getInputMap(condition);
                        ActionMap am = editorComponent.getActionMap();
                        if(map!=null && am!=null && isEnabled()){
                            Object binding = map.get(ks);
                            Action action = (binding==null) ? null : am.get(binding);
                            if(action!=null){
                                 SwingUtilities.notifyAction(action, ks, e, editorComponent,
                                        e.getModifiers());
                    return retValue;
                private boolean isStartingCellEdit() {
                    JTable table = (JTable) SwingUtilities.getAncestorOfClass(
                            JTable.class, this);
                    return table != null
                            && table.isFocusOwner()
                            && !Boolean.FALSE.equals((Boolean) table
                                    .getClientProperty("JTable.autoStartsEdit"));
    };so if i want to write C20,
    when i pressed C, it selects the combo, so after pressing 2 and 0, it searches for 20.
    how can i do this not to lose the first char?

    suppose you are editing a combobox in a jtable.
    in the combobox, there are items like
    A0
    A20
    C0
    C20
    E0
    E20
    my main goal is traverse and edit the table by keyboard.
    when i go to a jcombobox, e.g. i hit the button C, it only focus the combo, not selecting item.
    JComboBox comboBox = new JComboBox(arr){
                   protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                        int condition, boolean pressed) {
                    boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
                    if (!retValue && isStartingCellEdit() && editor != null) {
                        //editor.setItem(String.valueOf(ks.getKeyChar()));
                        JComponent editorComponent = (JComponent) getEditor().getEditorComponent();
                        InputMap map = editorComponent.getInputMap(condition);
                        ActionMap am = editorComponent.getActionMap();
                        if(map!=null && am!=null && isEnabled()){
                            Object binding = map.get(ks);
                            Action action = (binding==null) ? null : am.get(binding);
                            if(action!=null){
                                 SwingUtilities.notifyAction(action, ks, e, editorComponent,
                                        e.getModifiers());
                    return retValue;
                private boolean isStartingCellEdit() {
                    JTable table = (JTable) SwingUtilities.getAncestorOfClass(
                            JTable.class, this);
                    return table != null
                            && table.isFocusOwner()
                            && !Boolean.FALSE.equals((Boolean) table
                                    .getClientProperty("JTable.autoStartsEdit"));
    };so if i want to write C20,
    when i pressed C, it selects the combo, so after pressing 2 and 0, it searches for 20.
    how can i do this not to lose the first char?

  • Combobox in jtable two tab problem

    Hi all,
    If i am using combobox for one of the columns of jtable with custom editor and renderer, it needs two tab for navigation between the cells.
    How can i make it as 'one tab navigation'. Even i tried with 'isManagingfocus() return true' but...no effect.
    thanx in advance.
    S.A.Radha.

    here I'm giving a simple sample code. Refer this..
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    public class Class1 extends JFrame {
    JScrollPane jScrollPane1 = new JScrollPane();
    JTable editableTable1 = new JTable(3, 3);     
    public Class1() {
    try {          
    JComboBox c = new JComboBox();
    c.setEditable(true);
    c.addItem("a");
    c.addItem("b");
    DefaultCellEditor cellEditor = new DefaultCellEditor(c);
    TableColumn tc = editableTable1.getColumnModel().getColumn(0);
    tc.setCellEditor(cellEditor);
    this.getContentPane().setLayout(null);
    jScrollPane1.setBounds(new Rectangle(25, 19, 330, 180));
    this.getContentPane().add(jScrollPane1, null);
    jScrollPane1.getViewport().add(editableTable1, null);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    } catch(Exception e) {
    System.out.println("Exception in Class1:"+e);
    public static void main(String[] args) {
    Class1 class1 = new Class1();
    class1.setSize(400, 400);
    class1.setVisible(true);

  • Size of combobox in JTable with custom cell editor

    Hi All -
    I have a JTable that displays a combobox in certain cells. I have a custom table model, renderer, and editor. All of that works fine. I render the combobox with the renderer, and then return the combobox as an editor in the editor so that it can drop down and actually be of use. My problem is - I set the size of the combobox with a setBounds call in the renderer, I add it to a panel, and return the panel - because I dont want the combobox to take up the entire space of the cell. This approach fails in the editor. The setBounds and setSize calls have no effect. As soon as you click the combobox, the editor takes over and all of a sudden the combobox resizes to the entire area of the cell. I assume this is because in the editor you arent actually placing anything - your simply returning the "editing form" of the component.
    So - anybody know of a way to work around this? Worst case, I could just allow the combobox to use the entire area of the cell - but it makes it uglier so I figured I would run it by the forums.
    Eric

    Rather than just redirect you to my previous answer from ages ago, I'll just give it again. :-)
    You can actually do this, but you have to get tricky. By default, the dropdown's width will be the same width as the cell... but it doesn't have to be that way. Essentially what you have to do is override the UI (MetalComboBoxUI) for the combo component. In your new customized UI component subclass (that you set the combo to use), modify the the createPopup() method of this UI class, and add your own logic to set the size of the popup before you return it.
    Ideally the size would be based on the computed max width of a rendered item shown in the combo, but really you could set it to whatever just to see how it works.

  • Rephrasing of JTable question

    Ok, I'm going to rephrase a question I put up pretty poorly about JTables. This is what how I see it. I wanted to create a JTable with a button as the last column, a delete button that will allow you to delete that row. Sounds simple enough - I figured out how to add that last column, and how to create my own TableCellRenderers such that it rendered the last column as a button representation.
    Now my design question relates to the fact that the actual data, doesn't reside on the table...the actual data sits in another data object (a data array), and the table merely renders that information in a specific way. So when I hit the delete button, I really don't have a handle to the data, I need to somehow have an actionListener listening to that button which then sends a message to something else that is holding that data, and informs it to delete that item. The only way I see that is to pass a handle in the constructor of the TableCellRenderer of the actionListener which has a handle to the actual data. Is that how things are done? All this just so that an action performed on the Jtable looks like it's affecting the data itself?
    Correct me if I'm wrong, but it seems like the implementation of this JTable has it such that even though when I addRows to the JTable I am passing an actual object to the JTable. The JTable will just convert the object into textual information, and the handle of that actual object will be lost. In some ways it seems like it would have been better if that JTable kept a handle to the object passed into it from addRow(), so that if I ever said delete this row, I don't have to jump through hoops to find which data object is represented by that particular row and then have something else delete. Instead it would say "Ok, delete this row, which is really this object." Or maybe there is a reason that isn't done.
    Message was edited by:
    deadseasquirrels

    I read the post where you used the removeColumn method of the columnModel to remove the columns that you do not want to display. The way I understand it is that it is implementation of the MVC model, where the data is still there, but the Viewer aspect of the table just isn't displaying the data - and as you showed in your example, that gives more flexibility when you want to share a certain data table, but have it displayed differently.
    But it seems to me that the lines of code:
    columnModel1.removeColumn( columnModel1.getColumn( 4 ) );should really be sitting in either the tableModel class, or the renderer class. At this point that line of code, which defines which columns table1 or table2 should display just sits in the main object class. It seems to me that to be more robust in your tableModel definition, somewhere it should say "any table that uses this table model will have columns x, y, z removed from the columnModel." Instead by having that line of code just sitting outside of either a renderer class or a tableModel class that line could be anywhere, and it doesn't seem too robust. I guess I'm mentioning it, because I would like to put it in either the renderer class or my tableModel class (shown below), but I don't see how I can do that. If I can't do that perhaps you can shed some light as to why my understanding is flawed, and why they designed it in such a way that you can't - right now it seems like the tableModel class would be a great place to put a line of code like that.
    private DefaultTableModel filledTableModel = new DefaultTableModel(data, transactionCols){
    // Only allow button column to be editable, if there is an actual
    // button in that row          
        public boolean isCellEditable(int row, int col){
            return (col == CANCEL_COL && getValueAt(row, col) != "") ? true : false;
        // Overriden getColumnClass method that will return the object
        // class type of the first instance of the data type otherwise
        // returns the Object.class
        public Class getColumnClass(int column){
            for (int row = 0; row < getRowCount(); row++){
                Object o = getValueAt(row, column);
                if (o != null){ return o.getClass();
            return Object.class;
    };

  • Escape key "dies" in combobox and JTable

    I have set in my JDialog the default key ESCAPE as this standard code:
              KeyStroke escKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
              int param = JComponent.WHEN_IN_FOCUSED_WINDOW;
              root.getInputMap(param).put(escKey, "close");
              root.getActionMap().put("close", actionCancel);
         this.btCancel.setAction(actionCancel);
    The problem is when I have JComboBoxs and JTables. All key events seem to be consumed
    In this components (and maybe more components). So, if I press ESCAPE and my focus
    in a combobox, the dialog won't close.
    How could I work around this?
    thank you

    I've got the solution!
    I have a javaBean (JPanel) that has only one JComboBox. I trigger key pressed (don't know
    if should be key released in this case) on comboBox. Then I check if...
    this.comboBox.isPopupVisible().
    Simple. If popup is not visible and dispatch the event to this.
    I just wonder how the event goes to my javaBean, my javabean is in a dialog and this
    dialog of mine ends up to catch the event. ???
    Ok, this stays has a solution for future developers to found - in case they guess that
    right keywords :)

  • Click ComboBox in JTable to times before editing ?

    Hi,
    I have a JComboBox in a JTable.
    Now I want to open the ComboBox when
    you click the cell to times.
    There is a method in DefaultCellEditor called
    setClickCountToStart(int).
    But how can I get the reference to the DefaultCellEditor
    from my JTable. There is only a method theTable.getDefaultEditor
    which returns TableCellEditor ?
    Thanx Stephan

    I made it run right in jdk1.3.1 throgh chage the setSelectedItem Method, code is follow:
    public void setSelectedItem(Object item) {
        this.insertItemAt(item, 0);
        if(getItemCount() > 1) {
          this.removeItemAt(1);
        super.setSelectedItem(item);
    }

  • 2 JTable question

    1) In a default model JTable how can I deselect all selected rows or cancel any selection, since a table.deselectAll() method does not exist.
    2) How can I move selection. For example when I press a down arrow button the selection should move down with one row.
    Any help is highly appreciated.

    Next time make use of the correct forum for the specifyed question, in this cause the swing forum.
    Anyhow.
    1) In a default model JTable how can I deselect all selected rows or cancel any selection, since a table.deselectAll() method does not exist.Use JTables clearSelection(); ??
    2) How can I move selection. For example when I press a down arrow button the selection should move down with one row.Add an keylistener to the arrow button? And when its pushed, get the currently selected row, and set the new selected row to be current row + 1?
    getSelectedRow() And setRowSelectionInterval() perhaps?
    Use the Java api: http://java.sun.com/javase/6/docs/api/

  • JTable question/problem

    I am extracting data from 3 different database tables and I want to display the contents in seperate JTables, I am developing a table model class as a subclass of AbstractTableModel to be passed to the constructor of my JTable but because I will be creating 3 different JTable objects, does this mean that I must create 3 different table model classes as well? or is there an easier way of creating more than one table model in a class and selecting when to use them.

    I need to create a seperate model because the tables in the database do not have any shared columns Then I don't understand your original question. It appears you've answered your own question. Yes, you need a separate TableModel for each table.
    and some of the tables have data in a boolean and date format which I'm not sure are displayed properly with the default model. The TableModel is used to store data. You can control how the data is displayed at the JTable level. Check out this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=419688]thread.

  • How to have a combobox in JTable column header?

    Any simple ways for doing this? I am trying to get a filter to a JTable, so that only the rows containing the selected value in that column would be shown.
    I first need to get this combobox into the header of a column.

    Thanks.
    I have already tried with this way, but it was too long and complicated to implement into my file.
    Could someone post the principles here.
    Like this:
    // create my combobox
    JComboBox myBox = new JComboBox();
    myBox.addItem("Cat");
    myBox.addItem("Dog");
    // put the combobox to column header
    ??? ANY CODE HERE ???
    Tnx ahead!
    OK!
    AUlo

  • JTable question regarding Index/ID's from a VB guy

    Greets!
    So i am coming from VB6 where i use an ActiveX object table to display data from a SQL database table. When populating the table i include the 'ID' field from the database table as a hidden column. So when a user selects a row, i pull the hidden column's ID# and use that to do whatever (bring up another edit form, etc)
    So here i am in Java now, i've been playing with jTable for a while now and seem to be getting the hang of the basics, but when i replicated the above scenario, hiding the ID column had weird results (cursor would dissappear when i scroll over with the arrow keys). I also saw another post where another person said that along with populating the jTable i should also have an array that stores the ID that matches the RowIndex from the jTable itself.
    This is the table model that i am using:
    public class jTableModel extends AbstractTableModel {
        private double xTotal;
        private int colnum;
        private int rownum;
        private String[] colNames;
        private  ArrayList<Object[]> ResultSets;
        private Icon zIcon;
        /** Creates a new instance of FoodTableModel */
        public jTableModel(ResultSet rs,frmMain frm) {
          ResultSets=new ArrayList<Object[]>(); 
          Icon icon1 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_blue.png"));
          Icon icon2 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_red.png"));
          Icon icon3 = new ImageIcon(getClass().getResource("/main/images/bullet_ball_glass_green.png"));
          try{
            while(rs.next()){
                switch (rs.getInt("Type")) {
                    case 1: zIcon = icon1; break;
                    case 2: zIcon = icon2; break;
                    case 3: zIcon = icon3; break;
                Object[] row={zIcon,rs.getString("Name"),rs.getString("Description"),rs.getString("ID")};
                ResultSets.add(row);
            String[] zNames={
                "","Name","Description","ID"
            colNames = zNames;
            colnum=4;
          catch(Exception e){
              System.out.println("(jTableModel: There was an error: " + e);
        public Object getValueAt(int rowindex, int columnindex) {
           Object[] row=ResultSets.get(rowindex);
           return row[columnindex];
        public int getRowCount() {
            return ResultSets.size();
        public int getColumnCount() {
            return colnum;
        @Override
        public String getColumnName(int param) {
           return colNames[param];
        public double getTotal() {
            return xTotal;
        @Override
        public Class getColumnClass(int column) {
         return getValueAt(0, column).getClass();
        }Can anyone give me any tips in this area or point me in the right direction?
    Any help would be appreciated.

    Dear Poster,
    As no response has been provided to the thread in some time I must assume the issue is resolved, if the question is still valid please create a new thread rephrasing the query and providing as much data as possible to promote response from the community.
    Best Regards,
    SDN SRM Moderation Team

  • JList to JTable questions

    Hi, from looking at discussion groups and forums it appears that JList does not support the editability function; therefore, people suggest using a one column table instead.
    In changing the code around, I have a few questions
    Originally, I have the following for JList so that I can detect whenever
    an item has been deleted or added to the list
    activeModelList.getModel()
    .addListDataListener(new ListDataListener() {
    Now, the activeModelList is actually a JTable with a model that is a DefaultTableModel instead of DefaultListModel. How can I still be able to detect changes? what type of Listener can I use?
    Then, originally I had indicated default selections in the JList using the following activeModelList.setSelectedIndex(1); The only thing that I could think of to do the same for the table was activeModelList.setRowSelectionInterval(1,0); Is this good programming practice? Is this correct?
    Thank you very much for your inputs and advice.

    I think i figured out the .addListDataListener(new ListDataListener() equivalent... anyone know how to convert activeModelList.addListSelectionListener(new ListSelectionListener() {
    to one that would work the same in JTable
    someJTableFormerActiveModelList.add?

  • A few JTable questions

    Hi,
    I'm doing a bit of experimentation with JTables and have a few questions. What I am trying to do
    is create a JTable in a horizontal format, so that the headings appear as columns on the left hand side, and only the non-headers are editable.
    Is it possible to create a JTable with no column headers? I've looked up some of the examples on the web about having row headings, but the code seems very convoluted and difficult for me to understand, most involving JScrollPanels.
    If this is possible,
    What will happen when the values edited? eg. if I edit a value on the first row, will setValueAt (extended from AbstractTableModel's method) assume row=1 rather than 0 because it is expecting a column header?
    Also, the data for the table is held in another class, for instance:
         double timeStep[] = {0,40,80,120,160,200,240,280,320};
         double trim[] = { 26.2, 23.0, 23.0, 23.0, 23.0, 29.1, 45.0, 75.4, 90.0 };
         double list[] = { 20.2, 20.7, 26.6, 17.7, 16.5, 46.7, 67.6, 90.0, 90.0 };
         double rot[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0};
         double z[] = { 0, 0, 0, 12, 46, 150, 169, 337, 400 };
    is it possible to initialise the data, not as is customarily done using something like this, with a 2x2 matrix:
    private Object[][] data = {
         {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
         {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
         {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
         {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
         {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
    (Data taken from another website btw!)
    but by looping through the rows one by one and setting each one to the relevant array, eg. row 0 is timestep, row 1 is trim etc.?
    Many thanks
    Paul
    Edited by: 799615 on 09-Jan-2011 03:54

    I've tried something like this. See the pivot table mode here
    http://java-sl.com/envelope.html

Maybe you are looking for

  • Error when export report to PDF with a none standard Windows font

    Hi, I got this error when trying to export PDF under VS2008 with an special true type font in the code behind. The error says: ...temp_9550ab94-02fc-4362-b259-cc6de8d6c04b {32E546F5-C6A3-44FC-B8EF-D5E37A1118FA}.rpt:\nOperation not yet implemented. In

  • How to update the table when change list item in classic report

    hi , i worked with apex 4.2 and i create normal classic report with one select list(named loved)Column ,now i want to update table when user change the list with new value ,i can't create dynamic action to do this,i create check box with primary key

  • I have 2 iTunes accounts.. i would like to merge them into 1- any help??

    i have 2 itunes accounts and would like to merge them into 1 account... any help??

  • Bridge will not open in CS6

    I'm using win7 with plenty of memory. I had PS CS and upgraded to a complete new version of cs6 extended. I loaded it and the ps program works fine. However the Bridge program will not start. I've tried both programs even from the exe file and nothin

  • Transaction Handling

    Hi, Can someone please point me to documentation on how transactions are handled or should be implemented? Specifically, I am developing an application that uses Java function activities and want to understand what my responsibilities are when develo