Go to an Item in a JTable

Hey
When I press a button (for example NEXT) I want the JTable to go to that field . How can I do that cause I can't find it :D

You need to explain something more.

Similar Messages

  • JTable moving items strangeness (desperate now)...

    Hi there,
    I've got a major problem that I just can't figure out. I've got two JTables, each with an instance of the
    below datamodel. I've got two buttons. I want to highlight certain rows on the left JTable and use one of
    the buttons to move across the selected items to the JTable on the right.
    Two problems - the first is that the selected items are copied across fine, but instead of removing the
    selected rows from the left JTable after copying to the right JTable, it leaves a random one. The other
    problem is that if I highlight rows from near the bottom of the lefthand JTable, I get an
    ArrayIndexOutOfBoundsException.
    What the hell is going wrong here? I'm at a total loss.
    This is my datamodel for both JTables...
    import javax.swing.table.AbstractTableModel;
    import java.util.Collection;
    import java.util.ArrayList;
    import java.util.Vector;
    import java.util.Map;
    import java.util.List;
    import java.util.Iterator;
    import java.util.Set;
    import commonfiles.Utility;
    public class ListDataModel extends AbstractTableModel implements Cloneable {
        private final int NUM_COLUMNS = 3;
        private Vector theRowData;
        private String[] columnNames = {"USERS_REFNO", "CODE", "USER_NAME"};
        // Constructor : Create empty data model.
        public ListDataModel() {
            theRowData = new Vector();
        // Constructor : Create data model from another collection.
        public ListDataModel(Collection someCollection) {
            theRowData = new Vector();
            theRowData.addAll(someCollection);
        public ListDataModel(List arrayCollection) {
            ArrayList theColumnArray;
            Map rowMap;
            theRowData = new Vector();
            for (int i = 0; i < arrayCollection.size(); i++) {
                rowMap = (Map)arrayCollection.get(i);
                theColumnArray = new ArrayList();
                theColumnArray.add((Object)rowMap.get(columnNames[0]));
                theColumnArray.add((Object)rowMap.get(columnNames[1]));
                theColumnArray.add((Object)rowMap.get(columnNames[2]));
                theRowData.add(theColumnArray);
        public Object clone() {
            try {
                return super.clone();
            } catch (CloneNotSupportedException cnse) {
                throw new RuntimeException(cnse.toString());
        public Object getValueAt(int rowIndex, int columnIndex) {
            ArrayList theColumnArray;
            theColumnArray = (ArrayList)theRowData.get(rowIndex);
            return(Object)theColumnArray.get(columnIndex);
        public List getRowAt(int rowIndex) {
            return (ArrayList)theRowData.get(rowIndex);
        public void removeRowAt(int rowIndex) {                       // <- Exception thrown here.
            theRowData.removeElementAt(rowIndex);
        public void addRow(List rowObject) {
            theRowData.addElement(rowObject);
        // Check to see if a particular Table cell is editable.
        // In this model, none of the cells are directly editable.
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        public int getColumnCount() {
            return columnNames.length;
        // Return the column headers.
        public String[] returnColumnNames() {
            return columnNames;
        // Return the name of a specific column.
        public String getColumnName(int col) {
            return columnNames[col].toString();
        public int getRowCount() {
            return theRowData.size();
        public Vector returnAllData() {
            return theRowData;
    }...and this is the code I'm using when I press the button to move the selected rows from the left JTable to
    the right JTable.
    public void actionPerformed(ActionEvent e) {
            int[] selectedRows;
            List listItem;
            // Event that happens when the List Add (>>) button is pressed.
            if (e.getSource() == btnListAdd) {
                // Get the number of selected (hightlighted) rows.
                selectedRows = this.tableUserList.getSelectedRows();
                if (selectedRows.length > 0) {
                    for (int row = 0; row < selectedRows.length; row++) {
                        listItem = ((ListDataModel)tableUserList.getModel()).getRowAt(selectedRows[row]);
                        ((ListDataModel)tableExcludeList.getModel()).addRow(listItem);
                    for (int row = 0; row < selectedRows.length; row++) {
                        ((ListDataModel)tableUserList.getModel()).removeRowAt(selectedRows[row]);
                    tableUserList.clearSelection();
                    tableUserList.revalidate();
                    tableUserList.repaint();
                    tableExcludeList.revalidate();
                    tableExcludeList.repaint();
        }Here is the stacktrace for the IndexArrayOutOfBoundsException...
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 22 >= 22
    at java.util.Vector.removeElementAt(Vector.java:517)
    at ListDataModel.removeRowAt(ListDataModel.java:66)
    at ExcludeListFrame.actionPerformed(ExcludeListFrame.java:177)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    86)
    I'm in desperate need of help with this. The errors just don't make logical sense to me. Little help folks?
    Thanks.

    Here's your problem :
    When you remove an element from your Vector, its size decreses.
    Let's say you have 10 objects in your Vector :
    the first time you remove an element, its size will become 9 (from 0 to 8)... and imagine that the second index of your int array is 9 !! you are out of bounds!!
    what you should do is pass the entire indexes array to your data model, then create a new Vector (let's call it vect2) that you will feed with the objects pointed by your indexes.
    then you remove the whole vector :
    myData.removeAll(vect2);

  • JComboBox rendering issue in JTable

    I use a JComboBox to render certain items in my JTable.
    When I use jdk1.3, the items render perfectly.
    The problem is that when I use jdk1.4, the combobox is rendered with larger insets, clipping the bottom of the text.
    Has anyone else had this problem?

    Okay - I can get the JComboBox and define an empty border for it. This means it renders okay.
    What I don't like is stupid things like this creeping into jdk1.4 which weren't there in jdk1.3.
    Thanks for the reply Rommie.

  • JTable: Custom Table Model (pII)

    As was explained in pI, I'm creating a custom table model to overcome a few pitfalls I came across using the DefaultTableModel class, such as aligning cells, and getting certain columns to return only numeric type data. However, I've come upon a few roadblocks myself.
    How do I create each of the following methods:
    insertRow(int ow, int column)
    remove row(int row)
    addRow(Object[] rowData)Assuming that I decide to allow the user to add a column to the table, how would I create the methodaddColumn(Object columnName, Object[] columnData)And also, as I'm creating a custom table model, would I need to replicate DefaultTableModel's methods that inform the listeners that a change has been made to the table?
    Thanks!

    Thanks!
    I just got this response. Anyways, I found another solution that was, interestingly, from one of your threads written in 2005.
    This is what I did:
    // Letting the JTable know what each column stores and should return by
       // overloading the getColumnClass() method
       public Class getColumnClass(int column)
            if(recordsTable.getColumnName(column) == "Ranking")
              return Integer.class;
         /* Why do I keep ketting an IllegalArgumentException here? *
           * It keeps saying it cannot format given object as a Number */            
            else if(recordsTable.getColumnName(column) == "Price (�) ")
              return Float.class;
         else
           return getValueAt(0, column).getClass();         
       }However, another problem has arisen.
    The if method for the int column (Ranking column) works okay, and is even right-aligned. The else if arguments for the Price (�) column however is returning an IllegalArgumentException. This I just cannot figure out.
    Here's the code:package Practice;
      import java.awt.BorderLayout;
      import java.awt.Frame;
      import java.awt.Menu;
      import java.awt.MenuBar;
      import java.awt.MenuItem;
      import java.awt.MenuShortcut;
      import java.awt.event.ActionEvent;
      import java.awt.event.ActionListener;
      import java.awt.event.KeyEvent; // for MenuItem shortcuts
      import java.awt.event.WindowAdapter;
      import java.awt.event.WindowEvent;
      import java.awt.event.WindowListener;
      import javax.swing.JOptionPane;
      import javax.swing.JScrollPane; // JTable added to it, aiding flexibility
      import javax.swing.JTable; // The personally preferred GUI for this purpose
            // Provides a basic implementation of TableModel
      import javax.swing.table.DefaultTableModel;
              // This class uses Vector to store the rows and columns of data, though
              // programmer will be using LinkedLists
      import java.util.LinkedList;
      // User-defined classes
      import Practice.MusicDatabase;
      public class MusicBank extends Frame implements ActionListener
         MusicDatabase mDBase;
         Frame frame;
         String title = "",      // Frame's title
                file = "";           // pathname of the file to be opened
          // Declaring Menu and MenuItem variables
         Menu recordM; // ...
         // recordM
         MenuItem newRecordR_MI, deleteRecordR_MI;
         // Other irrelevant menus and sub items
        DefaultTableModel recordDetails;
        JTable recordsTable;
        LinkedList musicList;
        public MusicBank()
            musicList = new LinkedList();
            frame = new Frame(title);
            frame.setMenuBar(menuSystem());
            // Should user seek to close window externally
            frame.addWindowListener(new WindowAdapter()
                 public void windowClosing(WindowEvent we)
                     frame.dispose();
                     System.exit(0);
         recordDetails = new DefaultTableModel();
         // Creating the relevant columns
         recordDetails.addColumn("Title");
         recordDetails.addColumn("Identity");
         recordDetails.addColumn("Music Company");
         recordDetails.addColumn("Ranking");
         recordDetails.addColumn("Price (�) ");
         // Ensuring the table has at least one visible record (empty)
         recordDetails.addRow(populateRow("", "", "", 0, 0.00f));
         // Creating the table to display the data files (music record details)
         recordsTable = new JTable(recordDetails)
             // Letting the JTable know what each column stores and should return by
             // overloading the getColumnClass() method
            public Class getColumnClass(int column)
               if(recordsTable.getColumnName(column) == "Ranking")
                   return Integer.class;
                /* Why do I keep ketting an IllegalArgumentException here? *
                 * It keeps saying it cannot format given object as a Number */            
                else if(recordsTable.getColumnName(column) == "Price (�) ")
                    return Float.class;
                else
                    return getValueAt(0, column).getClass();         
      // Creating the menus
      public MenuBar menuSystem()
          MenuBar bar = new MenuBar();
          // Record menu and related items
          recordM = new Menu("Record");
          recordM.setShortcut(new MenuShortcut(KeyEvent.VK_R, false));        
          newRecordR_MI = new MenuItem("New record");
          newRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_N, false));
          deleteRecordR_MI = new MenuItem("Delete record");
          deleteRecordR_MI.setShortcut(new MenuShortcut(KeyEvent.VK_D, false));
           recordM.add(newRecordR_MI);
           recordM.addSeparator();
           recordM.add(deleteRecordR_MI);
            // Enabling menus with functionality
           newRecordR_MI.addActionListener(this);
           deleteRecordR_MI.addActionListener(this);
           // Adding menus and items to menu bar
           bar.add(recordM);
           return bar;        
      public void actionPerformed(ActionEvent ae)
          if(ae.getSource() == newRecordR_MI)
             newRecord();
          else if(ae.getSource() == deleteRecordR_MI)
             deleteRecord();       
      // Object that will be used, in conjunction with MusicDatabase's, to 
      // populate the JTable
      // A record in a JTable is equivalent to an element in a LinkedList
      public Object[] populateRow(String title, String name, String comp, int rank, float price)
          // First, update the LinkedList
          mDBase = new MusicDatabase(title, name, comp, rank, price);
          musicList.add(mDBase);
           // Then, update the table
           // As the parameters of Object tableDetails can only take a String or
           // object, rank and price will have to be cast as a String and later
           // parsed to their original form before use.
           String rankPT = ""+rank, pricePT = ""+price;        
           Object rowDetails[] = {title, name, comp, rankPT, pricePT};
           return rowDetails;
      public static void main(String args[])
          MusicBank app = new MusicBank();
           // Using the platform's L&F (if Win32,  Windows L&F; Mac OS, Mac OS L&F,
           // Sun, CDE/Motif L&F)
           // For more on this, refer to the WinHelp Java tutorial by F. Allimont
           try
               UIManager.getSystemLookAndFeelClassName();
           catch(Exception e)
               JOptionPane.showMessageDialog(app,
                    "Failed to create the Windows Look and Feel for this program",
                    "Look and Feel (L&F) error",
                    JOptionPane.ERROR_MESSAGE);
           app.frame.setSize(500, 500);
           app.frame.setVisible(true);
            // Placing frame in the centre of the screen on-loading
           app.frame.setLocationRelativeTo(null);
      // action methods per menu items
      // Also, why do I keep getting an ArrayIndexOutOfBoundsException
      // here? I do know what this exception is, and how it works, but just cannot
      // understand what is causing it
      public void newRecord()
          // Before adding a new record, check if previous record has complete
          // entries. If not, either display a message (JOptionPane) or disallow
          // request (simply do nothing)        
          // Proceed based on assesment
          if(queryState() == true)
              // Inform user that all entries need to be filled in before a new
              // record can be created
              JOptionPane.showMessageDialog(this, // current frame
                       "There are incomplete cells in the table."+
                       "\nPlease fill these in before proceeding",       // Message to user
                       "Incomplete entries",                                // Title
                       JOptionPane.ERROR_MESSAGE);                           // Relevant icon
          else
               // To ensure that both the linked list & the table are simultaneously
               // updated, JOptionPane's input dialogs are used to temporarily store
               // the data which is then inputted into both (linked list and JTable)
              String titleN, identityN, companyN; int rankN; float priceN;
              titleN = JOptionPane.showInputDialog(this, "Enter song title");
              identityN = JOptionPane.showInputDialog(this,                                      "Enter name of singer/band");
             companyN = JOptionPane.showInputDialog(this,                                 "Enter signed/unsigned company");
             rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "Enter rank (a number)") );
            System.out.println("\n JTable rows = "+recordDetails.getRowCount());
             // Ensuring that the chosen rank is not already entered
             /* Problem lies here */
             for(int row = 1; row <= recordDetails.getRowCount(); ++row)
                 if((recordDetails.getValueAt(row, 4)).equals(""+rankN))
                     rankN = Integer.parseInt( JOptionPane.showInputDialog(this,
                             "That number's already chosen.\nPlease enter a rank ") );
             priceN = Float.parseFloat( JOptionPane.showInputDialog(this,                                 "Finally, enter price �") );
             mDBase = new MusicDatabase(titleN, identityN, companyN, rankN, priceN);
             musicList.add(mDBase);
             recordDetails.addRow(populateRow(titleN, identityN, companyN, rankN,
         priceN));
             System.out.println("JTable rows after creation = "+
                   recordDetails.getRowCount());
         // Enabling the delete record menu item (as necessary)
         if((recordsTable.getRowCount()) > 0)
              deleteRecordR_MI.setEnabled(true);
      } // newRecord()
      public void deleteRecord()
         int selectedRow = recordsTable.getSelectedRow();
         recordDetails.removeRow(selectedRow);
          // Removing the element from the LinkedList's corresponding index
          musicList.remove(selectedRow);
          System.out.println("Existing rows = "+recordsTable.getRowCount());
           // If there are no more rows, disallow user from trying to delete rows
           if(selectedRow <= 0)
              deleteRecordR_MI.setEnabled(false);
      } // deleteRecord()
      // Method to query if all cells have changed their states (empty or not)
      public boolean queryState()
          // Obtaining number of rows
          int rows = recordDetails.getRowCount();
          int columns = recordDetails.getColumnCount();
          boolean isEmpty = false; // cell
          System.out.println("Rows = "+rows);
          System.out.println("Columns = "+columns);
          try{
              // Assessing all cells for complete entries
              // This approach is flexible, rather than hardcoding the rows available,
              // making it more reusable (assuming it will always be 5 columns)
              for (int rowIndex = 0; rowIndex<=rows; ++rowIndex)
                  if((recordDetails.getValueAt(rowIndex, 1)).equals(""))
                 isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 2)).equals(""))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 3)).equals(""))
               isEmpty = true;                
                  else if((recordDetails.getValueAt(rowIndex, 4)).equals("0"))
               isEmpty = true;
                  else if((recordDetails.getValueAt(rowIndex, 5)).equals("0.00"))
               isEmpty = true;
          catch(Exception e)
             System.out.println(e.getMessage());
          return isEmpty;
      Now here is the code for the MusicDatabase class
    package Practice;
    class MusicDatabase
        private String songTitle, identity, musicCompany;
        private int rank;
        private float priceF;
        // Defining the constructor
        public MusicDatabase(String title, String name, String company,                                int rankingInt, float price)
           songTitle = title;
           identity = name;
           musicCompany = company;
           rank = rankingInt;
           priceF = price;
        } // constructor
       // Other methods
    } // class MusicDatabaseSorry, but am not sure if these codes are executable, as where I am (a general library), JVM is not on the machine I am using. (Remember, i don't have ready acess to the Internet, so I could not use my machine, nor the facilities that had the JVM - unavailable to me at the time).
    Thanks!
    Reformer...
    PS I do hope the code pasted was not too much. Kind regards....

  • How to keep the focus in a table cell as long as it is invalid?

    Hello,
    if you run the following code and enter some alphabetic characters in the Integer column,
    you can't get out of the cell as long as focus transfer is within the table. But if you click in the textfield,
    the cell is left invalid. (If you click in the textfield immediately after the false edit, the cell even doesn't
    show the red border)
    I tried to attach a focusListener to the table, but that makes editing the table impossible.
    I also could attach a focusListener to each and every other component of the form,
    and checking the table there in focusGained - but that looks rather awkward.
    How would you proceed?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class InvalidInput extends JFrame {
      public InvalidInput() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        setSize(200, 200);
        setTitle("InvalidInput");
        final String HEADER[] = {"Integer", "String"};
        DefaultTableModel dtm= createTableModel(HEADER);
        dtm.addRow(new Object[] {new Integer(100), "Item 1"});
        dtm.addRow(new Object[] {new Integer(200), "Item 2"});
        final JTable table= new JTable(dtm);
        table.addFocusListener(new FocusAdapter() {
          public void focusLost(FocusEvent e) {
         System.out.println(table.isEditing());
         if (table.isEditing()) {
           boolean b= table.getCellEditor().stopCellEditing();
           System.out.println(b);
    //       if (!b) table.requestFocusInWindow();
    //       if (!b) table.changeSelection(table.getEditingRow(),
    //                         table.getEditingColumn(), false, false);
           if (!b) {
             DefaultCellEditor editor= (DefaultCellEditor)table.getCellEditor();
             editor.getComponent().requestFocusInWindow();
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setPreferredSize(new Dimension(195,55));
        add(scrollPane);
        JTextField tf= new JTextField(10);
        add(tf);
        setVisible(true);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
         new InvalidInput();
      private DefaultTableModel createTableModel(Object[] columnNames) {
        DefaultTableModel tblModel= new DefaultTableModel(columnNames, 0) {
          public Class getColumnClass(int column) {
         return getValueAt(0, column)==null ? Object.class :
                                   getValueAt(0, column).getClass();
        return tblModel;
    }Edited by: Jörg on 04.03.2012 14:52
    A big improvement is to apply
    table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);for this at least reverts the erroneous input to the last valid value.
    Still I would prefer either to inform the user of this reversion or to red-border the erroneous cell;
    for sometimes the [OK] button is at the bottom of a long form and putting one's eyes there for
    clicking, one doesn't necessarily notice the reversion which happens at the top.

    Thanks to both of you!
    @Jeanette
    In my real application I use a JFormattedTextField as editor. Checking my overridden stopCellEditing() method I become aware that the contents of JFormattedTextField (getText() or super.getCellEditorValue()) arrives there already reverted. Thus it's no wonder that I cannot return false.
    simply removes the editor on column resizingYikes! - Fortunately the table in question is not resizable.
    SwingX has a NumberEditorExHow would you proceed if you didn't know that class and were looking for it? I still don't manage to navigate successfully on java.net.
    @Walter
    Never thought of this. Seeing that someone is checking for me (red border), I'd rather lazily let him continue doing the job. But a DocumentListener looks like being a way out.

  • Intermediary bean causing NullPointerException

    Hi all,
    I wonder if someone could help me with an issue I'm having.
    I've got a JTable bound to database fields, and when the user selects a field and clicks an "Edit" button, I'm generating an object using ConvertRowIndexToModel() method, and passing the Object to a JDialog form, using an intermediary bean object called currentPigment.
    The currentPigment object is bound to various fields in the JDialog, and the bound properties are showing up correctly in the JTextField boxes. If I try to access the bean properties from the JFrame class where my JTable exists, everything is fine. However If I try to access the intermediary bean from within the JDialog, I'm getting a NullPointerException.
    Here is the code from the JFrame holding the JTable linked to the database:
    @Action(enabledProperty = "recordSelected")
        public void editPigment()
            PigmentEditor pe = new PigmentEditor(this, false);
            pe.setCurrentPigment(pigmentList.get(pigmentTable.convertRowIndexToModel(pigmentTable.getSelectedRow())));
            pe.setVisible(true);and here is the bean code in the JDialog class:
        protected Pigment currentPigment;
        public Pigment getCurrentPigment()
            return currentPigment;
        public void setCurrentPigment(Pigment currentPigment)
            Pigment oldCurrentPigment = this.currentPigment;
            this.currentPigment = currentPigment;
            propertyChangeSupport.firePropertyChange("currentPigment", oldCurrentPigment, currentPigment);
        }I need to access the properties of the currentPigment object so I can automatically select an item from a JTable, however if I try to access the objects getters/setters, I get a NullPointerException.
    If someone could explain why this is, or how I can get round it, I'd be greatful.
    Thanks in Advance.

    Okay I figured out what the problem was / is - When the JTable is bound to the nested entity class, because no item is selected, it's removing the nested entity class creating a null value. I also tried changing to a JList and this does the same thing. However if I use a JComboBox, my item renders correctly and the nested entity class displays the correct value without being erased.
    Is it possible to make a JTable select an item, before the bean binding removes the value making it null?
    Many thanks,

  • What is this none sense !!!!!!!!!!!!!!!!!!!!!!!!!!!!

    i wrote the following code to connect to an accessdb:
    package SSDB;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.print.*;
    import java.util.*;
    public class ViewAll extends JPanel implements Printable
         JFrame jf;
         JPanel jp;
         JPanel north;
         JComboBox columns;
         JComboBox items;
         JButton butn;
         JTable table;
         Connection con;
         Statement state;
         ResultSet rs;
         ResultSetMetaData rsmd;
         String [][] rowdata;
         String [] columnNames;
         Printable prnt;
         JMenuBar mb ;
         JMenu m;
         JMenuItem mi1;
         Container c;
         String cb;
         int rows ;
         int col;
         public int x;
         ViewAll()
         jf = new JFrame("����� ��������");     
         jp = new JPanel();
         north = new JPanel();
         butn = new JButton("��� ��������");
         mb = new JMenuBar();
         m = new JMenu("�������");
    mi1 = new JMenuItem("�����");
         int j,i=0;
         try{     
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   con = DriverManager.getConnection("jdbc:odbc:ssdb","","");
                   state = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
                   rs = state.executeQuery("Select * from SSDB");
                   rsmd = rs.getMetaData();
                   col = rsmd.getColumnCount();
                   columnNames = new String[col];
                   for (int c = 0;c<col;c++)
                   columnNames [c] = rsmd.getColumnName(c+1);
              while (rs.next())
              rows++;
              rs.beforeFirst();
              rowdata = new String[rows][col];
         j=0;     
              outer: while(rs.next())
              inner:for(i = 0 ; i<col ; i++)
                   String type = rsmd.getColumnTypeName(i+1);
              String colName = rsmd.getColumnName(i+1);
              if (type.equalsIgnoreCase("COUNTER"))
              String nocell = rs.getString(colName);
              rowdata[j] = nocell;
              if (type.equalsIgnoreCase("VARCHAR"))
              String cell = rs.getString(colName);
              rowdata[j][i] = cell;
              j++;
         }catch (ClassNotFoundException cnfe){cnfe.printStackTrace();}
         catch (SQLException sqle){
         sqle.printStackTrace();
         System.out.println(sqle.getSQLState());
         columns = new JComboBox(columnNames);
         items = new JComboBox();
         public int print(Graphics graphics,PageFormat pageFormat,int pageIndex) throws PrinterException
              Graphics2D g2 = (Graphics2D) graphics;
              g2.translate(pageFormat.getImageableX(),pageFormat.getImageableY());
              paint(g2);
              return Printable.PAGE_EXISTS;
    public void gui()
              actionLis al = new actionLis();
              actionLis2 al2 = new actionLis2();
              table = new JTable(rowdata,columnNames);
              c = jf.getContentPane();
              c.setLayout(new BorderLayout());
              m.add(mi1);
              mi1.addActionListener(al);
              mb.setAlignmentX(JFrame.RIGHT_ALIGNMENT);
              mb.add(m);
              jf.setJMenuBar(mb);
              jp.setLayout(new BorderLayout());
              columns.addActionListener(al2);
              north.add(butn);
              north.add(items);
              north.add(columns);
              jp.add(north,BorderLayout.NORTH);
              jp.add(new JScrollPane(table),BorderLayout.CENTER);
              c.add(new JScrollPane(jp),BorderLayout.CENTER);
              jf.setBounds(0,0,(int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(),(int)Toolkit.getDefaultToolkit().getScreenSize().getHeight());
              jf.setIconImage(Toolkit.getDefaultToolkit().getImage("cross1.gif"));
              jf.setVisible(true);
         public static void main(String[]args)
         ViewAll g = new ViewAll();
         g.gui();
         class actionLis implements ActionListener
         public void actionPerformed(ActionEvent ae)
              JMenuItem jmi = (JMenuItem)ae.getSource();
              if (jmi.equals(mi1))
              ViewAll a = new ViewAll();
              PrinterJob pr = PrinterJob.getPrinterJob();
              PageFormat LandS = pr.defaultPage();
              LandS.setOrientation(PageFormat.LANDSCAPE);
              Book b = new Book();
              b.append((Printable)a,LandS);
              pr.setPageable(b);
              try{
                   pr.print();
    }catch (PrinterException pe) {System.out.println(pe.getMessage() );}
    class actionLis2 implements ActionListener
         public void actionPerformed(ActionEvent ae)
         cb = (String)columns.getSelectedItem();
    try{
         state = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
         rs= state.executeQuery("Select'"+cb+"' from SSDB");
    while(rs.next())
              items.addItem(rs.getString(cb));
                   }catch(SQLException sqle){System.out.println("sqle2");sqle.printStackTrace();}     
    in the class actionLis2 i fill a jcombobox by getting the content of a column of the table.
    this causes runtime error (too much code to realize).I DO NOT WHY?
    can anyone help????????????????????????????????

    which runtime exception do you get? try posting code within "code" blocks so it's easier to read. when you hit reply there is a link at the top of the reply page called "special tokens" that tells you how to use this.

  • JInternalFrame, auto activate when mouse enters the frame

    Hi, is there a simple way to make the JInternalFrames automatically get activated as soon as the mouse enters them?
    I would like this in general, but specifically I need it for a drag'n drop operation. I want to drag an item from a JTable in one frame to another JTable in another frame. This works perfectly, even if the recepient frame is not active, what doesn't work is to scroll the recepient JTable using the mouse scrollwheel before dropping the item. This would work if the frame was active. (I tested this by temporarily placing the two JTables in the same internal frame)

    Thanks, this looks promising, unfortunately I read the stuff about glass panes but I can't seem to make it work anyway. As I understand it the default glass panes should block all events. This does not happen, even when I turn the glass panes visible on all JInternalFrames and the main JFrame. Everything is just like it was before... With this I mean that mouse events were sent to the mouse listener I added to the glass pane, but the mouse events also went to the underlying JInternalFrames. And when a drag'n drop was active, no mouse events are reported. What glass pane should I make visible for it to intercept all events?

  • Different JCombobox items in JTable for the same column

    Hello Everyone,
    I am reading from a file and displaying in a JTable. I want all cells in a specific column to be JComboBoxes but the items in the JComboBox differ from one cell to another, how can this be achieved?
    The following is a snippet from the Sun tutorials,
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    And hence every cell in the sportColumn has the exact same set of options in the JComboBox which is not what I want since I read from an external file.
    Any help or sample code would be highly appreciated.
    Thank you in advance

    Override getCellEditor(int row, int column) in JTable to control which editor gets used for which cell.

  • DefaultListModel  & JTable; how to sync the items in the DefaultListModel

    I have a jtable with items in it
    example
    name date age
    Peter 01-jan-43 62
    Ron 03-nov-73 32
    when double clicking the name( eg peter), a new window pops up contains all relevent info of the user.
    I added a sorter and when sorting the table it comes in the correct-wanted order, however, when double clicking the item - the wrong window pops up.
    I take it the DefaultListModel is not synchronized with the tables elements.
    Q: how to correct the DefaultListModel once the table has been sorted so it will be in sync with the jtable.
    thanks
    peter

    thank you camicker for replying.
    I have been trying for the past 4 hours to dig in the code (as well as google) to find where to implement a sync with the DefaultListModel. Nothing.
    any input?
    package com.shared.model;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    public class TableSorter extends AbstractTableModel
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
            public int compare(Object o1, Object o2)
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator()
            public int compare(Object o1, Object o2)
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter()
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel)
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader)
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState()
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel()
            return tableModel;
        public void setTableModel(TableModel tableModel)
            if (this.tableModel != null)
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null)
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader()
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader)
            if (this.tableHeader != null)
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer)
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null)
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())
        public boolean isSorting()
            return sortingColumns.size() != 0;
        private Directive getDirective(int column)
            for (int i = 0; i < sortingColumns.size(); i++)
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column)
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column)
            return getDirective(column).direction;
        private void sortingStatusChanged()
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null)
                tableHeader.repaint();
        public void setSortingStatus(int column, int status)
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE)
                sortingColumns.remove(directive);
            if (status != NOT_SORTED)
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size)
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE)
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting()
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator)
            if (comparator == null)
                columnComparators.remove(type);
            else
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column)
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null)
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType))
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel()
            if (viewToModel == null)
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++)
                    viewToModel[row] = new Row(row);
                if (isSorting())
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
            return getViewToModel()[viewIndex].modelIndex;
        private int[] getModelToView()
            if (modelToView == null)
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++)
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount()
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount()
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column)
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column)
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column)
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column)
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column)
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable
            private int modelIndex;
            public Row(int index)
                this.modelIndex = index;
            public int compareTo(Object o)
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();)
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null)
                        comparison = 0;
                    } else if (o1 == null)
                        comparison = -1;
                    } else if (o2 == null)
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0)
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener
            public void tableChanged(TableModelEvent e)
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting())
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null)
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter
            public void mouseClicked(MouseEvent e)
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1)
                    int status = getSortingStatus(column);
                    if (!e.isControlDown())
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority)
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y)
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth()
                return size;
            public int getIconHeight()
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column)
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive
            private int column;
            private int direction;
            public Directive(int column, int direction)
                this.column = column;
                this.direction = direction;
    }

  • Setting color of an item in a Jcombobox in a JTable when editing

    Hello,
    I have a situation where I have a JCombobox in a JTable . The JCombobox is non-editable. The items within the combobox are colored in pink or blue in order to help the user differentiate between the two categories that are in the list.
    But the problem is that when the user is on that cell and is just typing the first letter(s) in the combobox, he does see the item starting with that letter(s) but that item is not shown as colored. However, if the user clicks on the combobox with a mouse, the list pops-up and the items are shown as colored. I want the first part to work where the user can just use keyboard and see the items as colored in that cell itself. By default, currently when the row is selected the foreground is white and background is black. I want that particularly when this combobox has focus and an item is selected, the foreground should be of the same color as the color of the item.
    Can someone help?
    Thanks a lot in advance.

    Additional information on above:
    I associate a customized renderer with the column of my table for which i want to set the colors.
    TableColumn tc6 = jTableDRS.getColumnModel().getColumn(myDRSModel.FINANCECODE_COLUMN);
    tc6.setCellRenderer(new ColorRenderer());
    here is the renderer that I am using...
    public class ColorRenderer extends JLabel implements TableCellRenderer {
    protected Border noFocusBorder;
    public ColorRenderer() {
    noFocusBorder = new EmptyBorder(1, 2, 1, 2);
    setOpaque(true);
    setBorder(noFocusBorder);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    Color foreground = null;
    Color background = null;
    Font font = null;
    if(column == myDRSModel.FINANCECODE_COLUMN)
    setFont((font != null) ? font : table.getFont());
    String str = (String)value.toString();
    if (!str.equalsIgnoreCase("SELECT ONE")) {
    int y = financedesc.indexOf(str);
    if((payreceiveind.get(y).toString()).equals("R")){
    setForeground(Color.RED);
    } else if((payreceiveind.get(y).toString()).equals("P")){
    setForeground(new Color(147,112,240));
    if(isSelected)
    if((payreceiveind.get(y).toString()).equals("R")){
    setForeground(Color.RED);
    } else if((payreceiveind.get(y).toString()).equals("P")){
    setForeground(new Color(147,112,240));
    setBackground(table.getSelectionBackground());
    else{
    setBackground(table.getBackground());
    else
    if(isSelected)
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else
    setForeground(table.getForeground());
    setBackground(table.getBackground());
    setValue(value);
    return this;
    protected void setValue(Object value) {
    setText((value == null) ? "" : value.toString());
    }

  • Update JTable when an item is selected in a JComboBox inside the same JTabl

    I created a JTable with a lookup JComboBox. I want to update values from the table when an item is selected in the ComboBox.
    I tried all the events posible in JComboBox, but I can not fire to update the JTable.
    Please if you have a how-to, (source) will help. Thanks.
    Regards,
    -Rory

    I tried that. But it only fires when the JComboxBox, lost the focus. And not in the "itemChange" event. How to do it width that event?
    I want something like "intemChange" event, to fire the JTable.fireTableChangeUpdate(); ... I send the code.
    * @author rory
    public class PeriodenDauerGrid extends JPortSimTable implements Serializable, ActionListener {
         * generated id
        private static final long serialVersionUID = -5270969898251578932L;
        public PeriodenDauerGrid() {
            super();
        @Override
        protected void initComponent() {
            super.initComponent();
            setModel(new PeriodenDauerGridTableModel());
            setDefaultEditor(String.class, new PeriodenCellEditor(this));
            setDefaultRenderer(String.class, new PeriodenCellRenderer());
        public void actionPerformed(ActionEvent e) {
            // HERE should fire the table update.
            // JOptionPane.showMessageDialog(null, "HOLITA!");
            PeriodenDauerGridTableModel model = (PeriodenDauerGridTableModel) getModel();
            model.fireTableDataChanged();
            updateUI();
    class PeriodenCellRenderer extends JLabel implements TableCellRenderer {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            setHorizontalTextPosition(SwingConstants.CENTER);
            setHorizontalAlignment(SwingConstants.CENTER);
            if (row == 1) {
                setOpaque(true);
                setBackground(GuiConstants.PANEL_COLOR);
            } else {
                setOpaque(false);
                setBackground(GuiConstants.CELL_EDITOR_COLOR);
            if (value instanceof Date) {
                Date n = (Date) value;
                // String.format(format, args)
                String s = String.format("%1$td.%1$tm.%1$tY", (Date) value);
                setText(s);
            } else {
                setText(value == null ? "" : value.toString());
            return this;
    class PeriodenCellEditor extends AbstractCellEditor implements TableCellEditor {
        private JComboBox combo = new JComboBox(new String[] { "7", "84", "182", "364" });
        private JTable table = null;
        public PeriodenCellEditor(PeriodenDauerGrid table) {
            combo.addActionListener(table);
            this.table = table;
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            combo.setSelectedItem(value.toString());
            return combo;
        public Object getCellEditorValue() {
            return combo.getSelectedItem();
    }

  • Different jpopup menus items depending on content in a Jtable cell

    Hi,
    Is it possible if a popup menu have different items in it, depending on the content of a jtable cell??
    I would be greatful if any one could point me in the right direction.
    Thanks
    Venus

    In the mouse listener where you are displaying the popup, change it as appropriate before displaying it.

  • Hi :remove item in Jtable

    hi
    i use JTable which extends The Abstract table model , in that i didn't find method for remove item from the table , is there any way to remov the item from table.
    why i extends the Abstract table model my table should be uneditable, if i use the default table model it is not possible the table become uneditable
    help me plz
    reg
    vino

    hi camickr
    here is my code i overrirde the isCellEditable method with return value false , but table is still editable, plz tell me what is a error in my code
    thanks in advance , its very urgent to me
    reg
    vino
    import java.awt.BorderLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    public class SimpleTableSample {
      static  Object rows[][] = { { "one", "ichi - \u4E00" },
            { "two", "ni - \u4E8C" }, { "three", "san - \u4E09" },
            { "four", "shi - \u56DB" }, { "five", "go - \u4E94" },
            { "six", "roku - \u516D" }, { "seven", "shichi - \u4E03" },
            { "eight", "hachi - \u516B" }, { "nine", "kyu - \u4E5D" },
            { "ten", "ju - \u5341" } };
        static Object headers[] = { "English", "Japanese" };
      public static void main(String args[]) {
        String title = (args.length == 0 ? "JTable Sample" : args[0]);
        JFrame frame = new JFrame(title);
        DefaultTableModel model = new DefaultTableModel(rows,headers);
        JTable table = new JTable(model);
        table.remove(0);
        JScrollPane scrollPane = new JScrollPane(table);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
        frame.setSize(300, 150);
        frame.setVisible(true);
    public int getColumnCount()
    return headers.length;
    public int getRowCount()
    return rows.length;
    public String getColumnName(int c)
            return headers[c];
    public Object getValueAt(int rowIndex, int colIndex)
    return rows[rowIndex][colIndex];
      public boolean isCellEditable(int rowIndex, int colIndex)
             return false;
    }

  • How do you set new items within a JComboBox that is within a JTable

    I have searched and searched for the answer to this and do not thing there is one. I have a JTable that has 5 columns. 2 of the columns use DefaultCellRenderers where a JComboBox is used. One of the columns has a value of different football positions. The other has a value of the different players. When a user enters a particular position such as Kickers I want all the Kickers to be showin within the Players JComboBox within the table.
    The problem is that I ONLY want the cell to be modified within that row and column that the position was changed. I have found ways to modify the component but it modifies it for the whole Column. I only want it to be modified for the player cell within the row that the Position was modified. Bottom line is that I just want to modify the JComboBox's components.
    If anyone has had this challenge before please advise.

    I'm not sure I fully understood what you wanted. Does the following little program help you?import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumnModel;
    import java.awt.*;
    * User: weebib
    * Date: 29 janv. 2005
    * Time: 23:37:57
    public class FootballTable extends JPanel {
         private static final String[] COLUMN_NAMES = {"Position", "Name"};
         private static final String[] POSITIONS = {"goal", "arriere", "milieu", "avant"};
         private static final String[] GOALS = {"goal1", "goal2", "goal3"};
         private static final String[] ARRIERES = {"arriere1", "arriere2", "arriere3"};
         private static final String[] MILIEUX = {"milieu1", "milieu2", "milieu3"};
         private static final String[] AVANTS = {"avant1", "avant2", "avant3"};
         public FootballTable() {
              super(new BorderLayout());
              DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 10);
              final JTable table = new JTable(model);
              TableColumnModel columnModel = table.getColumnModel();
              columnModel.getColumn(0).setCellEditor(new DefaultCellEditor(new JComboBox(POSITIONS)));
              columnModel.getColumn(1).setCellEditor(new DefaultCellEditor(new JComboBox()) {
                   public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                        JComboBox nameComboBox = (JComboBox)super.getTableCellEditorComponent(table, value, isSelected, row, column);
                        Object position = table.getValueAt(row, 0);
                        if (position == null) {
                             nameComboBox.setModel(new DefaultComboBoxModel());
                        } else if (position.equals("goal")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(GOALS));
                        } else if (position.equals("arriere")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(ARRIERES));
                        } else if (position.equals("milieu")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(MILIEUX));
                        } else if (position.equals("avant")) {
                             nameComboBox.setModel(new DefaultComboBoxModel(AVANTS));
                        } else {
                             nameComboBox.setModel(new DefaultComboBoxModel());
                        return nameComboBox;
              add(new JScrollPane(table), BorderLayout.CENTER);
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              final JFrame frame = new JFrame(FootballTable.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setContentPane(new FootballTable());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.setSize(400, 300);
                        frame.show();
    }Sorry for the French words, I have no idea how they are called in english (and too lazy to search).
    There is another solution. You also can override the table's prepareEditor method and add the relevant code before returning the Component.

Maybe you are looking for

  • Image in a JFrame

    I want to display an image (.jpg) in a JFrame. How? I'm using Containers and setBounds for the JButtons in the JFrame.

  • Dual displays, one to sleep?

    I have a dual monitor configuration with my new Mac Pro cylinder.  One display is Thunderbolt, the other a Cinema Display (mini connector). I don't always use the second display, and I have it set to it's own space.   But I'm wondering if there is so

  • SAP Order-to-Cash

    Hi, I want more about SAP Order-to-Cash and configuration steps. Plz help out of this problem. Regards Shruthi

  • Photoshop Elements 12 Problem

    I am trying to open the Editor from the Organizer in Elements 12.  Adobe will not allow - Tells me that either I am not connected to the internet or that my computer date and time are wrong,  I am connected and the date and time are correct.  Any sug

  • Can Edge Web Fonts be used for Photoshop website mockups?

    I'm keen to know if Edge Web Fonts can be used within Photoshop as an extension (to make the website mockup process smoother). I know Edge Web Fonts plays well with Muse and other Edge Tools, but I don't want to use Muse to build my sites - I just wa