JTable in 1.2.2 and 1.3

I am using JTable in 1.2.2 and it works perfectly . My table has column group. But when I compile the same code by 1.3 and run in 1.3 I get the NULLPOINTER exception a line marked by =>:
TableColumn aColumn = columnModel.getColumn(column);
TableCellRenderer renderer = aColumn.getHeaderRenderer();
=>Component comp = renderer. getTableCellRendererComponent(header.getTable(), aColumn.getHeaderValue(), false, false,-1, column);
That is renderer object is NULL.
What I need to do to solve this exception in 1.3.

With 2 duke dollars... I don't know.

Similar Messages

  • F2 Edit in JTable -- standard for all look and feel ?

    hi,
    I use a robot to simulate a F2 when a column is in focus in a JTABLE so that user can just type without having to type the <F2> key.
    My question is:
    Is F2 (to get a column in edit mode) for JTABLE standard for all look and feel (metal, X-windows ..) ?
    Thanks.
    Tony

    Read the JTable API. There is a link the gives the
    standard key assignments for the standard LAF's.thanks. got it.

  • JTable - Help with column names and rowselection

    Hi,
    Is there anyone that can help me. I have successfully been able to load a JTable from an MS access database using vectors. I am now trying to find out how to hardcode the column names into the JTable as a string.
    Can anyone please also show me some code on how to be able update a value in a cell (from ''N'' to ''Y'') by double clicking on that row.
    How can I make all the other columns non-editable.
    Here is my code:
         private JTable getJTable() {
              Vector columnNames = new Vector();
    Vector data = new Vector();
    try
    // Connect to the Database
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // String url = "jdbc:odbc:Teenergy"; // if using ODBC Data Source name
    String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=C:/Documents " +
              "and Settings/Administrator/My Documents/mdbTEST.mdb";
    String userid = "";
    String password = "";
    Class.forName( driver );
    Connection connection = DriverManager.getConnection( url, userid, password );
    // Read data from a table
    String sql = "select * from PurchaseOrderView";
    Statement stmt = connection.createStatement();
    ResultSet rs = stmt.executeQuery( sql );
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();
    // Get column names
    for (int i = 1; i <= columns; i++)
    columnNames.addElement( md.getColumnName(i) );
    // Get row data
    while (rs.next())
    Vector row = new Vector(columns);
    for (int i = 1; i <= columns; i++)
    row.addElement( rs.getObject(i) );
    data.addElement( row );
    rs.close();
    stmt.close();
    catch(Exception e)
    System.out.println( e );
              if (jTable == null) {
                   jTable = new JTable(data, columnNames);
                   jTable.setAutoCreateColumnsFromModel(false);
                   jTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
                   jTable.setShowHorizontalLines(false);
                   jTable.setGridColor(java.awt.SystemColor.control);
                   jTable.setRowSelectionAllowed(true);
                   jTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
                   jTable.setShowGrid(true);     
              return jTable;
         }

    this method has a default behavior to supply exactly what you're seeing: column names consisting of the capitalized letters, "A", "B", "C".Thanks Pete, had seen that but never really thought about it... about 10 days ago somebody needed to obtain Excel column names, I'd offered a rigorous solution and now see it would have been shorter and simpler (if a little heavier) to extend DefaultTableModel and provide the two additional methods needed (getOffsetCol and getColIndex).
    Not much of a difference in LOC but certainly more elegant ;-)
    Darryl

  • JTable with custom column model and table model not showing table header

    Hello,
    I am creating a JTable with a custom table model and a custom column model. However the table header is not being displayed (yes, it is in a JScrollPane). I've shrunk the problem down into a single compileable example:
    Thanks for your help.
    import javax.swing.*;
    import javax.swing.table.*;
    public class Test1 extends JFrame
         public static void main(String args[])
              JTable table;
              TableColumnModel colModel=createTestColumnModel();
              TestTableModel tableModel=new TestTableModel();
              Test1 frame=new Test1();
              table=new JTable(tableModel, colModel);
              frame.getContentPane().add(new JScrollPane(table));
              frame.setSize(200,200);
              frame.setVisible(true);
         private static DefaultTableColumnModel createTestColumnModel()
              DefaultTableColumnModel columnModel=new DefaultTableColumnModel();
              columnModel.addColumn(new TableColumn(0));
              return columnModel;
         static class TestTableModel extends AbstractTableModel
              public int getColumnCount()
                   return 1;
              public Class<?> getColumnClass(int columnIndex)
                   return String.class;
              public String getColumnName(int column)
                   return "col";
              public int getRowCount()
                   return 1;
              public Object getValueAt(int row, int col)
                   return "test";
              public void setValueAt(Object aValue, int rowIndex, int columnIndex)
    }Edited by: 802416 on 14-Oct-2010 04:29
    added                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Kleopatra wrote:
    jduprez wrote:
    See http://download.oracle.com/javase/6/docs/api/javax/swing/table/TableColumn.html#setHeaderValue(java.lang.Object)
    When the TableColumn is created, the default headerValue  is null
    So, the header ends up rendered as an empty label (probably of size 0 if the JTable computes its header size based on the renderer's preferred size).nitpicking (can't resist - the alternative is a cleanup round in some not so nice code I produced recently <g>):
    - it's not the JTable's business to compute its headers size (and it doesn't, the header's the culprit.) *> - the header should never come up with a zero (or near-to) height: even if there is no title shown, it's still needed as grab to resize/move the columns. So I would consider this sizing behaviour a bug.*
    - furthermore, the "really zero" height is a longstanding issue with MetalBorder.TableHeaderBorder (other LAFs size with the top/bottom of their default header cell border) which extends AbstractBorder incorrectly. That's easy to do because AbstractBorder itself is badly implemented
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459419
    Thanks for the opportunity to have some fun :-)
    JeanetteNo problem, thanks for the insight :)

  • JTable help:- Setting Table Header and scrollbar

    hi
    everybody.
    i have create a table which is getting the data from URL Connection by parsing the XML file.
    All is working fine but the only problem is that i am not able to set the column headers.
    and also want to set scrollbars to my table because the data in my table is long.
    i have tried with JTableHeader and TableModel, but i am confused with it.
    so can anybody solve my problem.
    i am sending my code for creating table, and also sending the file from which the data is retrieved.
    please go through the code and reply me.
    If u are not able to parse the xml file than simply removed that part and using the QUERYResp.txt which i have attached, because i think the URL which i am using will not be accessed other than my network
    waiting for reply.
    //SelectPrivilege.java
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.w3c.dom.*;
    import java.net.*;
    import java.util.*;
    public class SelectPrivilege extends JFrame implements ActionListener
         JFrame frame;
         JTable table;
         JPanel buttonpanel;
         JButton openbutton,donebutton;
         String strclassname,strmembertype,strpasswordduration,strclassdescription;
        private boolean ALLOW_ROW_SELECTION = true;
        ListSelectionModel rowSM;
         Document document;
         Node node;
         NodeList employees,children;
         Element employee;
         String inputline,strSuccess;
         URL url;
         URLConnection connection;
         FileInputStream fis;
         DataInputStream dis;
         String objid,classname,membertype,passwordexp,description,finalstring;
         StringTokenizer st;
         String strurl = "<CLFAPP><CLFYAPP_MSG_TYPE_MSG_TYPE>QUERY</CLFYAPP_MSG_TYPE_MSG_TYPE><TABLE>PRIVCLASS</TABLE><FIELDS>OBJID,CLASS_NAME,MEMBER_TYPE,PSWRD_EXP_PER,DESCRIPTION</FIELDS><FILTER></FILTER></CLFYAPP>";
         public SelectPrivilege()
              JFrame.setDefaultLookAndFeelDecorated(true);
              frame = new JFrame("Select Privilege Class");
              try
                   url = new URL("http://10.8.54.55:7002/RILClarifyAppRequest?XML=" + strurl);
                   connection = url.openConnection();
                   BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                   FileOutputStream out = new FileOutputStream("QUERYResp.xml");
                   PrintStream p = new PrintStream(out);
                   while ((inputline = reader.readLine()) != null)
                        System.out.println("Response Received......");
                        p.println(inputline);
                   p.close();
                   reader.close();
              catch(MalformedURLException e)
                   System.out.println(e.getCause());
              catch(IOException e)
                   System.out.println(e.getCause());
              //Parsing XML
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              try
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   document = builder.parse(new File("QUERYResp.xml"));
                   node = document.getDocumentElement();
                   employees = document.getElementsByTagName("RECORD");
                   FileOutputStream out = new FileOutputStream("QUERYResp.txt");
                   PrintStream p = new PrintStream(out);
                   for(int i = 0; i < employees.getLength(); i++)
                        final Element employee = (Element)employees.item(i);
                        p.print(getValueOf(employee,"OBJID"));
                        p.print("#");
                        p.print(getValueOf(employee,"CLASS_NAME"));
                        p.print("#");
                        p.print(getValueOf(employee,"MEMBER_TYPE"));
                        p.print("#");
                        p.print(getValueOf(employee,"PSWRD_EXP_PER"));
                        p.print("#");
                        p.print(getValueOf(employee,"DESCRIPTION"));
                        p.print("#@");
                        //p.close();
                        objid = getValueOf(employee,"OBJID");
                        classname = getValueOf(employee,"CLASS_NAME");
                        membertype = getValueOf(employee,"MEMBER_TYPE");
                        passwordexp = getValueOf(employee,"PSWRD_EXP_PER");
                        description = getValueOf(employee,"DESCRIPTION");
              catch(SAXException sxe)
                   Exception x = sxe;
                   if(sxe.getException() != null)
                        x = sxe.getException();
                   x.printStackTrace();
              catch(ParserConfigurationException pce)
                   pce.printStackTrace();
              catch(IOException ioe)
                   ioe.printStackTrace();
              catch(NullPointerException npe)
                   System.out.println(npe.getCause());
              table();
              buttonpanel = new JPanel();
              buttonpanel.setLayout(new FlowLayout());
              openbutton = new JButton("Open");
              donebutton = new JButton("Done");
              donebutton.setMnemonic('d');
              buttonpanel.add(openbutton);
              buttonpanel.add(donebutton);
              openbutton.addActionListener(this);
              donebutton.addActionListener(this);
              Container contentpane = getContentPane();
              frame.setContentPane(contentpane);
              contentpane.setLayout(new BorderLayout());
              contentpane.add(table.getTableHeader(),BorderLayout.PAGE_START);
              contentpane.add(table,BorderLayout.CENTER);
              contentpane.add(buttonpanel,BorderLayout.SOUTH);
              frame.setSize(500,400);
              frame.setVisible(true);
         static String getValueOf (Element element, String tagname)
              final NodeList children = element.getElementsByTagName(tagname);
              if (children.getLength() == 0) { return null; }
                   return concat(children, new StringBuffer()).toString();
         static StringBuffer concat (NodeList nodelist, StringBuffer buffer)
              for (int index = 0, length = nodelist.getLength(); index < length; index++)
                   final Node node = nodelist.item(index);
                   switch (node.getNodeType())
                        case Node.CDATA_SECTION_NODE: buffer.append(node.getNodeValue()); break;
                        case Node.ELEMENT_NODE: concat(node.getChildNodes(), buffer); break;
                        case Node.TEXT_NODE : buffer.append(node.getNodeValue()); break;
              return buffer;
         public void table()
              try
                   fis = new FileInputStream("QUERYResp.txt");
                   dis = new DataInputStream(fis);
                   finalstring = dis.readLine();
              catch(IOException e)
              st = new StringTokenizer(finalstring, "@");
              table = new JTable(st.countTokens() + 1,5);
              table.setValueAt("OBJID",0,0);
              table.setValueAt("CLASS NAME",0,1);
              table.setValueAt("MEMBER TYPE",0,2);
              table.setValueAt("PASSWORD DURATION",0,3);
              table.setValueAt("DESCRIPTION",0,4);
              int count = 0,cnt=0;
              StringTokenizer st1 = null;
              try
                   while(st.hasMoreTokens())
                        st1 = new StringTokenizer(st.nextToken(),"#");
                        cnt=0;
                        while(st1.hasMoreTokens())
                             table.setValueAt(st1.nextToken(),count,cnt++);
                        count++;
                        st1=null;
              catch(Exception e)
                   e.printStackTrace();
              //JTableHeader header = table.getTableHeader();
              table.setPreferredScrollableViewportSize(new Dimension(200,500));
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            if(ALLOW_ROW_SELECTION)
                 rowSM = table.getSelectionModel();
                 rowSM.addListSelectionListener(new ListSelectionListener(){
                            public void valueChanged(ListSelectionEvent e)
                                 ListSelectionModel row = (ListSelectionModel)e.getSource();
                                 if (row.isSelectionEmpty() == true)
                                    System.out.println("No rows are selected.");
                                else
                                     if (e.getValueIsAdjusting())
                                          return;
                                         int selectedRow = row.getMinSelectionIndex();
                                         System.out.println("Row " + selectedRow + " is now selected.");
                 JScrollPane scrollpane = new JScrollPane(table);
         public void createprivilegeclassdetails()
              PrivilegeClassDetails privilegeclassdetailsobj = new PrivilegeClassDetails();
              privilegeclassdetailsobj.frame.setSize(400,400);
              privilegeclassdetailsobj.frame.setVisible(true);
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equalsIgnoreCase("done"))
                   System.out.println("SelectPrivilege Window Closed");
                   frame.dispose();
              if(str.equalsIgnoreCase("open"))
                   System.out.println("here");
                   createprivilegeclassdetails();
         public static void main(String a[])
              new SelectPrivilege();
    Copy the whole line if ur saving this in a file, as it is a string
    //QUERYResp.txt
    268435457#CSR#Employees#0#Customer Support Representative#@268435458#Hotline Engineer#Employees#0#Hotline Engineer#@268435459#Product Specialist#Employees#0#Product Specialist#@268435460#Senior Product Specialist#Employees#0#Senior Product Specialist#@268435461#Field Engineer#Employees#0#Field Engineer#@268435462#Support Manager I#Employees#0#Support Manager I#@268435463#Support Manager II#Employees#0#Support Manager II#@268435464#Development Engineer#Employees#0#Development Engineer#@268435465#Development Manager#Employees#0#Development Manager#@268435466#QA Engineer#Employees#0#QA Engineer#@268435467#QA Manager#Employees#0#QA Manager#@268435468#Technical Writer#Employees#0#Technical Writer#@268435469#Technical Publications Manager#Employees#0#Technical Publications Manager#@268435470#Site Configuration Manager#Employees#0#Site Configuration Manager#@268435471#Product Administrator#Employees#0#Product Administrator#@268435472#Technical Product Administrator#Employees#0#Technical Product Administrator#@268435473#Contract Specialist#Employees#0#Contract Specialist#@268435474#System Administrator#Employees#90#System Administrator#@268435475#Submitter#Contacts#0#Submitter#@268435476#Viewer#Contacts#0#Viewer#@268435477#Inventory Specialist#Employees#0#Inventory Specialist#@268435478#Logistics Manager#Employees#0#Logistics Manager#@268435479#Sales Representative#Employees#0#Sales Representative#@268435480#Marketing Representative#Employees#0#Marketing Representative#@268435481#Sales Manager#Employees#0#Sales Manager#@268435482#Offline User#Employees#0#Privilege Class for use with ClearEnterprise Traveler#@268435483#Call Center Agent#Employees#30#Call Center Agent#@268435484#Call Center Manager#Employees#0#Call Center Manager#@268435485#Customer Service Agent#Employees#0#Customer Service Agent#@268435486#Telemarketing Agent#Employees#0#Telemarketing Agent#@268435487#Telesales Agent#Employees#0#Telesales Agent#@268435488#Telesales Manager#Employees#0#Telesales Manager#@268435489#Avaya_Users#Employees#0#Privilege Class for Avaya. Only Clear Call Center Application Enabled.#@268435490#Account Manager#Employees#0#Account Manager for Accounts#@268435491#Account Executive#Employees#30#Account Executive for Accounts#@268435492#Pre Sales Tech Executive#Employees#0#Pre Sales Technical Executive#@268435493#Pre Sales Tech Team Lead#Employees#0#Pre Sales Technical Team Leader#@268435494#Post Sales Tech Executive#Employees#0#Post sales technical executive#@268435495#Post Sales Commercial Executive#Employees#0#Post sales commercial executive#@268435496#Vertical Domain Expert#Employees#0#Vertical Domain Expert#@268435497#Supervisor#Employees#0#Supervior who approves the billing adjustments#@268435498#RA#Employees#0##@268435499#Configuration#Employees#90#Privilege Class for Clarify Configurators#@268435500#FO Online Agent#Employees#0#Testing#@268435501#OTAF Remote Funcionality#Employees#0##@268435502#Sr.Manager CC#Employees#0#Customization for phase1 RUNS (1a).#@268435503#FO Online Unit - Agent #Employees#0#Customization for phase1 RUNS (1).#@268435504#FO Online - Agent (outbound)#Employees#0#Customization for phase1 RUNS (1b).#@268435505#Incoming mail unit manager#Employees#0#Customization for phase1 RUNS (2).#@268435506#Save team agent#Employees#0#Customization for phase1 RUNS (3).#@268435507#Save team supervisor#Employees#0#Customization for phase1 RUNS (4).#@268435508#Technical suport agent#Employees#0#Customization for phase1 RUNS (5).#@268435509#Technical suport supervisor#Employees#0#Customization for phase1 RUNS (6).#@268435510#Webstore Agents#Employees#0#Customization for phase1 RUNS (7).#@268435511#FO Offline Unit (Reg)- Supervisor#Employees#0#Customization for phase1 RUNS (8).#@268435512#Head C. Service (Circles)#Employees#0#Customization for phase1 RUNS (8a).#@268435513#Revenue Assurance#Employees#0#Customization for phase1 RUNS (9).#@268435514#Manager CC#Employees#0#Customization for phase1 RUNS (1a).#@268435515#FO Offline Unit - Agent at Contact Centre#Employees#0#Customization for phase1 RUNS (1).#@268435516#Telesales unit agent#Employees#0#Customization for phase1 RUNS (1).#@268435517#Incoming mail unit agent#Employees#0#Customization for phase1 RUNS (1).#@268435518#Telesales supervisor#Employees#0#Customization for phase1 RUNS (2).#@268435519#FO Online Unit - Supervisor#Employees#0#Customization for phase1 RUNS (2).#@268435520#FO Offline Unit (CC) - Supervisor#Employees#0#Customization for phase1 RUNS (2).#@268435521#TT unit agent#Employees#0#Customization for phase1 RUNS (5).#@268435522#TT unit supervisor#Employees#0#Customization for phase1 RUNS (6).#@268435523#Pos Agents#Employees#0#Customization for phase1 RUNS (7).#@268435524#FO Offline Unit - Regions#Employees#0#Customization for phase1 RUNS (7).#@268435525#Service fulfillment unit agent#Employees#0#Customization for phase1 RUNS (7).#@268435526#Sales Executives (Regions)#Employees#0#Customization for phase1 RUNS (7).#@268435527#Webstore Manager#Employees#0#Customization for phase1 RUNS (8).#@268435528#Service fulfillment unit manager#Employees#0#Customization for phase1 RUNS (8).#@268435529#Network#Employees#0#Customization for phase1 RUNS (9).#@268435530#After Sales#Employees#0#Customization for phase1 RUNS (9).#@268435531#Handsets#Employees#0#Customization for phase1 RUNS (9).#@268435532#Portal#Employees#0#Customization for phase1 RUNS (9).#@268435533#GIS#Employees#0#Customization for phase1 RUNS (9).#@268435534#Logistics#Employees#0#Customization for phase1 RUNS (9).#@268435535#Data Services#Employees#0#Customization for phase1 RUNS (9).#@268435536#Production Support#Employees#0#Since it is possible to temper the data form the Clarify GUI , restrict all access to users except for the minimal in order to control the env.#@268435537#Webstore Users#Employees#0##@268435539#IN_CSR#Employees#0#Privilege Class for Prepaid CSR's#@268435540#Configuration_Maha#Employees#0#Privilege Class for Clarify Configurators#@268435541#test privilege class#Employees#0##@268435542#PS_TEST#Employees#0##@268435543#TEST SACHIN#Employees#0#SACHIN TEST#@268435544#Supervisor1#Employees#300#Supervise and monitor agents#@268435545#Call Center Adminstrator#Employees#0#Call Center Admin Priv#@268435546#siva_test#Employees#0#new privilege class for test purpose#@268435547#PREPAID PCO#Employees#0#For PREPAID PCO#@268435548#santo_test#Employees#0#new privilage class for test#@

    Don't start by writing a 100 line program to test a component you don't know how to use. Start by writing a 10 line program. This is all you need:
              String[] columnNames = {"Date", "String", "Centered", "Integer", "Boolean"};
              Object[][] data =
                   {new Date(), "A", "A", new Integer(1), new Boolean(true)},
                   {new Date(), "B", "B", new Integer(2), new Boolean(false)},
                   {new Date(), "C", "C", new Integer(10), null},
                   {new Date(), "D", "D", new Integer(4), new Boolean(false)}
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              model.addTableModelListener( this );
              table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );

  • JTable methods worked in JDK5 and no more in JDK6

    Hi,
    I have a JTable child class, with an override method editCellAt. The main goal of this method is to allow select all the cell value and when the user types some char, it changes all the old value. This is very important for users, to easy typing new values in any cell.
    These worked very well until JDK5, and it doesn't work in JDK6. Now in JDK6 this code puts the 1st char after other old chars, and then for 2nd char it starts to work fine.
    The code for test is here:
    package gestor.princ;
    import java.util.EventObject;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import javax.swing.text.*;
    public class testJTable extends JFrame {
      public static void main(String[] args) {
        testJTable frame = new testJTable();
        Object[][] data =
          {"TesteAAAAAA1","1.2"},
          {"TesteBBBBBB2","3.4"},
          {"TesteCCCCCC3","5.6"},
          {"TesteDDDDDD4","7.8"},
        Object[] columnNames = {"Text","Value"};
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        selectallJTable table = new selectallJTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        frame.getContentPane().add(scrollPane);
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    class selectallJTable extends JTable {
      public selectallJTable(AbstractTableModel dataModel) {
        super(dataModel);
        TableCellRenderer highlightRenderer = new SelectAll();
        setDefaultRenderer(Object.class, highlightRenderer);
      //  Select the text when the cell starts editing
      //  a) text will be replaced when you start typing in a cell
      //  b) text will be selected when you use F2 to start editing
      //  c) text will be selected when double clicking to start editing
      public boolean editCellAt(int row, int column, EventObject e) {
        boolean result = super.editCellAt(row, column, e);
        Component editor = getEditorComponent();
        if (editor != null) {
          if (editor instanceof JComboBox)
            editor = ((JComboBox) editor).getEditor().getEditorComponent();
          if (editor instanceof JTextComponent) {
            if (e == null) {
              ((JTextComponent)editor).selectAll();
            } else {
              final Component editor1 = editor;
              SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                  ((JTextComponent)editor1).selectAll();
        return result;
      class SelectAll extends DefaultTableCellRenderer {
        private Color selectionBackground = UIManager.getColor("TextField.selectionBackground");
        private Border editBorder = BorderFactory.createLineBorder(Color.BLACK);
        private boolean cellHasFocus;
        public Component getTableCellRendererComponent(
          JTable table, Object value, boolean isSelected,
          boolean hasFocus, int row, int column) {
          super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
          cellHasFocus = hasFocus;
          return this;
        protected void paintComponent(Graphics g) {
          if (cellHasFocus && !getText().equals("")) {
            setBorder( editBorder );
            g.setColor( selectionBackground );
            g.fillRect(0, 0, getPreferredSize().width, getSize().height);
          super.paintComponent(g);
    }

    I have changed this part of code:
            if (e == null) {
              ((JTextComponent)editor).selectAll();
            } else {
              final Component editor1 = editor;
              SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                  ((JTextComponent)editor1).selectAll();
           }by simply:
    ((JTextComponent)editor).selectAll();Now typing new value works fine. However, selectAll doesn't work anymore. I would like to select all cell value (with blue mark), it's better for user to know what cell is actually selected.

  • JTable: HOW TO INSERT ROWS AND DATA?

    I have one JFrame on screen and inside of this i have a JTable, the question is how to insert rows and data into the JTable?

    [http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]
    In future, please post Swing questions to the [Swing Forum.|http://forums.sun.com/forum.jspa?forumID=57]
    In short, your TableModel is probably a DefaultTableModel . Study its API.

  • (URGENT) problem with JTable: can't catch ENTER and control focus in JTable

    I hava a JTable and a AbstractTableModel.
    Here is what i want to DO.
    When I press the ENTER or TAB I want to set focus to cell wich is 2 position away from the the sell I am editing
    on the same row in the JTable. How can I do this.
    in fact, that is my real question HOW to ?
    When I press the ENTER or TAB in JTABLE I want to tell to JTable which cell to grab the focus

    In the UI is defined the InputMap/ActionMap pair to respond to keys. There is defined an action for ENTER. I have had the same problem, and the only thing that worked for me was to clear the actionMap, and reassign some keys to their original action, and some (e.g. ENTER, TAB) to my actions. This worked. With TAB is harder beacuse i guess it's deeper in the JVM implemented, but after a while i've managed to overwrite that too.

  • How to get JTable's default TAB behavior and apply it to another key ?

    Is there any way to get Table's default behavior of one key say TAB & apply it to the another key say ENTER?
    Means I want to disable JTable's default behavior of ENTER key & I want ENTER key should act like TAB.

    Take a look at this.
    [http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html]

  • One model for JTree and JTable

    Hi.
    Is it possible for a JTree and a JTable to share one model?
    Thank you

    Hope u r not using Comonent TreeTable
    If u have Tree & Table different components, just want to have a common model then u can try this,
    It is nothing but default implementation given in DefaultTableModel
    public class MyTreeTableModel extends DefaultTreeModel implements TableModel, Serializable {
    protected Vector dataVector;
    /** List of listeners */
    protected EventListenerList listenerList = new EventListenerList();
    /** The <code>Vector</code> of column identifiers. */
    protected Vector columnIdentifiers;
    public MyTreeTableModel(TreeNode root) {
    this(root, false);
    // constructor for TreeModel only
    public MyTreeTableModel(TreeNode root, boolean asksAllowsChildren) {
    super(root, asksAllowsChildren);
    // constructor for TableModel only
    public MyTreeTableModel() {
    this(0, 0);
    private static Vector newVector(int size) {
    Vector v = new Vector(size);
    v.setSize(size);
    return v;
    // constructor for TableModel only
    public MyTreeTableModel(int rowCount, int columnCount) {
    this(newVector(columnCount), rowCount);
    // constructor for TableModel only
    public MyTreeTableModel(Vector columnNames, int rowCount) {
    super(null);
    setDataVector(newVector(rowCount), columnNames);
    // constructor for TableModel only
    public MyTreeTableModel(Object[] columnNames, int rowCount) {
    this(convertToVector(columnNames), rowCount);
    // constructor for TableModel only
    public MyTreeTableModel(Vector data, Vector columnNames) {
    super(null);
    setDataVector(data, columnNames);
    // constructor for TableModel only
    public MyTreeTableModel(Object[][] data, Object[] columnNames) {
    super(null);
    setDataVector(data, columnNames);
    * Returns a default name for the column using spreadsheet conventions:
    * A, B, C, ... Z, AA, AB, etc. If <code>column</code> cannot be found,
    * returns an empty string.
    * @param column the column being queried
    * @return a string containing the default name of <code>column</code>
    private String getDefaultColumnName(int column) {
    String result = "";
    for (; column >= 0; column = column / 26 - 1) {
    result = (char)((char)(column%26)+'A') + result;
    return result;
    * Returns a column given its name.
    * Implementation is naive so this should be overridden if
    * this method is to be called often. This method is not
    * in the <code>TableModel</code> interface and is not used by the
    * <code>JTable</code>.
    * @param columnName string containing name of column to be located
    * @return the column with <code>columnName</code>, or -1 if not found
    public int findColumn(String columnName) {
    for (int i = 0; i < getColumnCount(); i++) {
    if (columnName.equals(getColumnName(i))) {
    return i;
    return -1;
    * Returns <code>Object.class</code> regardless of <code>columnIndex</code>.
    * @param columnIndex the column being queried
    * @return the Object.class
    public Class getColumnClass(int columnIndex) {
    return Object.class;
    // Managing Listeners
    * Adds a listener to the list that's notified each time a change
    * to the data model occurs.
    * @param     l          the TableModelListener
    public void addTableModelListener(TableModelListener l) {
    listenerList.add(TableModelListener.class, l);
    * Removes a listener from the list that's notified each time a
    * change to the data model occurs.
    * @param     l          the TableModelListener
    public void removeTableModelListener(TableModelListener l) {
    listenerList.remove(TableModelListener.class, l);
    * Returns an array of all the table model listeners
    * registered on this model.
    * @return all of this model's <code>TableModelListener</code>s
    * or an empty
    * array if no table model listeners are currently registered
    public TableModelListener[] getTableModelListeners() {
    return (TableModelListener[])listenerList.getListeners(
    TableModelListener.class);
    // Fire methods
    * Notifies all listeners that all cell values in the table's
    * rows may have changed. The number of rows may also have changed
    * and the <code>JTable</code> should redraw the
    * table from scratch. The structure of the table (as in the order of the
    * columns) is assumed to be the same.
    public void fireTableDataChanged() {
    fireTableChanged(new TableModelEvent(this));
    * Notifies all listeners that the table's structure has changed.
    * The number of columns in the table, and the names and types of
    * the new columns may be different from the previous state.
    * If the <code>JTable</code> receives this event and its
    * <code>autoCreateColumnsFromModel</code>
    * flag is set it discards any table columns that it had and reallocates
    * default columns in the order they appear in the model. This is the
    * same as calling <code>setModel(TableModel)</code> on the
    * <code>JTable</code>.
    public void fireTableStructureChanged() {
    fireTableChanged(new TableModelEvent(this, TableModelEvent.HEADER_ROW));
    * Notifies all listeners that rows in the range
    * <code>[firstRow, lastRow]</code>, inclusive, have been inserted.
    * @param firstRow the first row
    * @param lastRow the last row
    public void fireTableRowsInserted(int firstRow, int lastRow) {
    fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
    TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));
    * Notifies all listeners that rows in the range
    * <code>[firstRow, lastRow]</code>, inclusive, have been updated.
    * @param firstRow the first row
    * @param lastRow the last row
    public void fireTableRowsUpdated(int firstRow, int lastRow) {
    fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
    TableModelEvent.ALL_COLUMNS, TableModelEvent.UPDATE));
    * Notifies all listeners that rows in the range
    * <code>[firstRow, lastRow]</code>, inclusive, have been deleted.
    * @param firstRow the first row
    * @param lastRow the last row
    public void fireTableRowsDeleted(int firstRow, int lastRow) {
    fireTableChanged(new TableModelEvent(this, firstRow, lastRow,
    TableModelEvent.ALL_COLUMNS, TableModelEvent.DELETE));
    * Notifies all listeners that the value of the cell at
    * <code>[row, column]</code> has been updated.
    * @param row row of cell which has been updated
    * @param column column of cell which has been updated
    public void fireTableCellUpdated(int row, int column) {
    fireTableChanged(new TableModelEvent(this, row, row, column));
    * Forwards the given notification event to all
    * <code>TableModelListeners</code> that registered
    * themselves as listeners for this table model.
    * @param e the event to be forwarded
    public void fireTableChanged(TableModelEvent e) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners==TableModelListener.class) {
    ((TableModelListener)listeners[i+1]).tableChanged(e);
    * Returns an array of all the objects currently registered
    * as <code><em>Foo</em>Listener</code>s
    * upon this <code>AbstractTableModel</code>.
    * <code><em>Foo</em>Listener</code>s are registered using the
    * <code>add<em>Foo</em>Listener</code> method.
    * <p>
    * You can specify the <code>listenerType</code> argument
    * with a class literal,
    * such as
    * <code><em>Foo</em>Listener.class</code>.
    * For example, you can query a
    * model <code>m</code>
    * for its table model listeners with the following code:
    * <pre>TableModelListener[] tmls = (TableModelListener[])(m.getListeners(TableModelListener.class));</pre>
    * If no such listeners exist, this method returns an empty array.
    * @param listenerType the type of listeners requested; this parameter
    * should specify an interface that descends from
    * <code>java.util.EventListener</code>
    * @return an array of all objects registered as
    * <code><em>Foo</em>Listener</code>s on this component,
    * or an empty array if no such
    * listeners have been added
    * @exception ClassCastException if <code>listenerType</code>
    * doesn't specify a class or interface that implements
    * <code>java.util.EventListener</code>
    public EventListener[] getListeners(Class listenerType) {
    return listenerList.getListeners(listenerType);
    * Returns the <code>Vector</code> of <code>Vectors</code>
    * that contains the table's
    * data values. The vectors contained in the outer vector are
    * each a single row of values. In other words, to get to the cell
    * at row 1, column 5: <p>
    * <code>((Vector)getDataVector().elementAt(1)).elementAt(5);</code><p>
    * @return the vector of vectors containing the tables data values
    public Vector getDataVector() {
    return dataVector;
    private static Vector nonNullVector(Vector v) {
    return (v != null) ? v : new Vector();
    * Replaces the current <code>dataVector</code> instance variable
    * with the new Vector of rows, <code>dataVector</code>.
    * <code>columnIdentifiers</code> are the names of the new
    * columns. The first name in <code>columnIdentifiers</code> is
    * mapped to column 0 in <code>dataVector</code>. Each row in
    * <code>dataVector</code> is adjusted to match the number of
    * columns in <code>columnIdentifiers</code>
    * either by truncating the <code>Vector</code> if it is too long,
    * or adding <code>null</code> values if it is too short.
    * <p>Note that passing in a <code>null</code> value for
    * <code>dataVector</code> results in unspecified behavior,
    * an possibly an exception.
    * @param dataVector the new data vector
    * @param columnIdentifiers the names of the columns
    public void setDataVector(Vector dataVector, Vector columnIdentifiers) {
    this.dataVector = nonNullVector(dataVector);
    this.columnIdentifiers = nonNullVector(columnIdentifiers);
    justifyRows(0, getRowCount());
    fireTableStructureChanged();
    * Replaces the value in the <code>dataVector</code> instance
    * variable with the values in the array <code>dataVector</code>.
    * The first index in the <code>Object[][]</code>
    * array is the row index and the second is the column index.
    * <code>columnIdentifiers</code> are the names of the new columns.
    * @param dataVector          the new data vector
    * @param columnIdentifiers     the names of the columns
    public void setDataVector(Object[][] dataVector, Object[] columnIdentifiers) {
    setDataVector(convertToVector(dataVector), convertToVector(columnIdentifiers));
    * Equivalent to <code>fireTableChanged</code>.
    * @param event the change event
    public void newDataAvailable(TableModelEvent event) {
    fireTableChanged(event);
    // Manipulating rows
    private void justifyRows(int from, int to) {
    // Sometimes the MyTreeTableModel is subclassed
    // instead of the AbstractTableModel by mistake.
    // Set the number of rows for the case when getRowCount
    // is overridden.
    dataVector.setSize(getRowCount());
    for (int i = from; i < to; i++) {
    if (dataVector.elementAt(i) == null) {
    dataVector.setElementAt(new Vector(), i);
    ((Vector)dataVector.elementAt(i)).setSize(getColumnCount());
    * Ensures that the new rows have the correct number of columns.
    * This is accomplished by using the <code>setSize</code> method in
    * <code>Vector</code> which truncates vectors
    * which are too long, and appends <code>null</code>s if they
    * are too short.
    * This method also sends out a <code>tableChanged</code>
    * notification message to all the listeners.
    * @param e this <code>TableModelEvent</code> describes
    * where the rows were added.
    *                    If <code>null</code> it assumes
    * all the rows were newly added
    public void newRowsAdded(TableModelEvent e) {
    justifyRows(e.getFirstRow(), e.getLastRow() + 1);
    fireTableChanged(e);
    * Equivalent to <code>fireTableChanged</code>.
    * @param event the change event
    public void rowsRemoved(TableModelEvent event) {
    fireTableChanged(event);
    * Obsolete as of Java 2 platform v1.3. Please use <code>setRowCount</code> instead.
    * Sets the number of rows in the model. If the new size is greater
    * than the current size, new rows are added to the end of the model
    * If the new size is less than the current size, all
    * rows at index <code>rowCount</code> and greater are discarded. <p>
    * @param rowCount the new number of rows
    public void setNumRows(int rowCount) {
    int old = getRowCount();
    if (old == rowCount) {
    return;
    dataVector.setSize(rowCount);
    if (rowCount <= old) {
    fireTableRowsDeleted(rowCount, old-1);
    else {
    justifyRows(old, rowCount);
    fireTableRowsInserted(old, rowCount-1);
    * Sets the number of rows in the model. If the new size is greater
    * than the current size, new rows are added to the end of the model
    * If the new size is less than the current size, all
    * rows at index <code>rowCount</code> and greater are discarded. <p>
    public void setRowCount(int rowCount) {
    setNumRows(rowCount);
    * Adds a row to the end of the model. The new row will contain
    * <code>null</code> values unless <code>rowData</code> is specified.
    * Notification of the row being added will be generated.
    * @param rowData optional data of the row being added
    public void addRow(Vector rowData) {
    insertRow(getRowCount(), rowData);
    * Adds a row to the end of the model. The new row will contain
    * <code>null</code> values unless <code>rowData</code> is specified.
    * Notification of the row being added will be generated.
    * @param rowData optional data of the row being added
    public void addRow(Object[] rowData) {
    addRow(convertToVector(rowData));
    * Inserts a row at <code>row</code> in the model. The new row
    * will contain <code>null</code> values unless <code>rowData</code>
    * is specified. Notification of the row being added will be generated.
    * @param row the row index of the row to be inserted
    * @param rowData optional data of the row being added
    * @exception ArrayIndexOutOfBoundsException if the row was invalid
    public void insertRow(int row, Vector rowData) {
    dataVector.insertElementAt(rowData, row);
    justifyRows(row, row+1);
    fireTableRowsInserted(row, row);
    * Inserts a row at <code>row</code> in the model. The new row
    * will contain <code>null</code> values unless <code>rowData</code>
    * is specified. Notification of the row being added will be generated.
    * @param row the row index of the row to be inserted
    * @param rowData optional data of the row being added
    * @exception ArrayIndexOutOfBoundsException if the row was invalid
    public void insertRow(int row, Object[] rowData) {
    insertRow(row, convertToVector(rowData));
    private static int gcd(int i, int j) {
    return (j == 0) ? i : gcd(j, i%j);
    private static void rotate(Vector v, int a, int b, int shift) {
    int size = b - a;
    int r = size - shift;
    int g = gcd(size, r);
    for(int i = 0; i < g; i++) {
    int to = i;
    Object tmp = v.elementAt(a + to);
    for(int from = (to + r) % size; from != i; from = (to + r) % size) {
    v.setElementAt(v.elementAt(a + from), a + to);
    to = from;
    v.setElementAt(tmp, a + to);
    * Moves one or more rows from the inlcusive range <code>start</code> to
    * <code>end</code> to the <code>to</code> position in the model.
    * After the move, the row that was at index <code>start</code>
    * will be at index <code>to</code>.
    * This method will send a <code>tableChanged</code> notification
    * message to all the listeners. <p>
    * <pre>
    * Examples of moves:
    * <p>
    * 1. moveRow(1,3,5);
    * a|B|C|D|e|f|g|h|i|j|k - before
    * a|e|f|g|h|B|C|D|i|j|k - after
    * <p>
    * 2. moveRow(6,7,1);
    * a|b|c|d|e|f|G|H|i|j|k - before
    * a|G|H|b|c|d|e|f|i|j|k - after
    * <p>
    * </pre>
    * @param start the starting row index to be moved
    * @param end the ending row index to be moved
    * @param to the destination of the rows to be moved
    * @exception ArrayIndexOutOfBoundsException if any of the elements
    * would be moved out of the table's range
    public void moveRow(int start, int end, int to) {
    int shift = to - start;
    int first, last;
    if (shift < 0) {
    first = to;
    last = end;
    else {
    first = start;
    last = to + end - start;
    rotate(dataVector, first, last + 1, shift);
    fireTableRowsUpdated(first, last);
    * Removes the row at <code>row</code> from the model. Notification
    * of the row being removed will be sent to all the listeners.
    * @param row the row index of the row to be removed
    * @exception ArrayIndexOutOfBoundsException if the row was invalid
    public void removeRow(int row) {
    dataVector.removeElementAt(row);
    fireTableRowsDeleted(row, row);
    // Manipulating columns
    * Replaces the column identifiers in the model. If the number of
    * <code>newIdentifier</code>s is greater than the current number
    * of columns, new columns are added to the end of each row in the model.
    * If the number of <code>newIdentifier</code>s is less than the current
    * number of columns, all the extra columns at the end of a row are
    * discarded. <p>
    * @param newIdentifiers vector of column identifiers. If
    *                    <code>null</code>, set the model
    * to zero columns
    public void setColumnIdentifiers(Vector columnIdentifiers) {
    setDataVector(dataVector, columnIdentifiers);
    * Replaces the column identifiers in the model. If the number of
    * <code>newIdentifier</code>s is greater than the current number
    * of columns, new columns are added to the end of each row in the model.
    * If the number of <code>newIdentifier</code>s is less than the current
    * number of columns, all the extra columns at the end of a row are
    * discarded. <p>
    * @param newIdentifiers array of column identifiers.
    *                    If <code>null</code>, set
    * the model to zero columns
    public void setColumnIdentifiers(Object[] newIdentifiers) {
    setColumnIdentifiers(convertToVector(newIdentifiers));
    * Sets the number of columns in the model. If the new size is greater
    * than the current size, new columns are added to the end of the model
    * with <code>null</code> cell values.
    * If the new size is less than the current size, all columns at index
    * <code>columnCount</code> and greater are discarded.
    * @param columnCount the new number of columns in the model
    public void setColumnCount(int columnCount) {
    columnIdentifiers.setSize(columnCount);
    justifyRows(0, getRowCount());
    fireTableStructureChanged();
    * Adds a column to the model. The new column will have the
    * identifier <code>columnName</code>, which may be null. This method
    * will send a
    * <code>tableChanged</code> notification message to all the listeners.
    * This method is a cover for <code>addColumn(Object, Vector)</code> which
    * uses <code>null</code> as the data vector.
    * @param columnName the identifier of the column being added
    public void addColumn(Object columnName) {
    addColumn(columnName, (Vector)null);
    * Adds a column to the model. The new column will have the
    * identifier <code>columnName</code>, which may be null.
    * <code>columnData</code> is the
    * optional vector of data for the column. If it is <code>null</code>
    * the column is filled with <code>null</code> values. Otherwise,
    * the new data will be added to model starting with the first
    * element going to row 0, etc. This method will send a
    * <code>tableChanged</code> notification message to all the listeners.
    * @param columnName the identifier of the column being added
    * @param columnData optional data of the column being added
    public void addColumn(Object columnName, Vector columnData) {
    columnIdentifiers.addElement(columnName);
    if (columnData != null) {
    int columnSize = columnData.size();
    if (columnSize > getRowCount()) {
    dataVector.setSize(columnSize);
    justifyRows(0, getRowCount());
    int newColumn = getColumnCount() - 1;
    for(int i = 0; i < columnSize; i++) {
    Vector row = (Vector)dataVector.elementAt(i);
    row.setElementAt(columnData.elementAt(i), newColumn);
    else {
    justifyRows(0, getRowCount());
    fireTableStructureChanged();
    * Adds a column to the model. The new column will have the
    * identifier <code>columnName</code>. <code>columnData</code> is the
    * optional array of data for the column. If it is <code>null</code>
    * the column is filled with <code>null</code> values. Otherwise,
    * the new data will be added to model starting with the first
    * element going to row 0, etc. This method will send a
    * <code>tableChanged</code> notification message to all the listeners.
    public void addColumn(Object columnName, Object[] columnData) {
    addColumn(columnName, convertToVector(columnData));
    // Implementing the TableModel interface
    * Returns the number of rows in this data table.
    * @return the number of rows in the model
    public int getRowCount() {
    return dataVector.size();
    * Returns the number of columns in this data table.
    * @return the number of columns in the model
    public int getColumnCount() {
    return columnIdentifiers.size();
    * Returns the column name.
    * @return a name for this column using the string value of the
    * appropriate member in <code>columnIdentifiers</code>.
    * If <code>columnIdentifiers</code> does not have an entry
    * for this index, returns the default
    * name provided by the superclass
    public String getColumnName(int column) {
    Object id = null;
    // This test is to cover the case when
    // getColumnCount has been subclassed by mistake ...
    if (column < columnIdentifiers.size()) {
    id = columnIdentifiers.elementAt(column);
    return (id == null) ? getDefaultColumnName(column)
    : id.toString();
    * Returns true regardless of parameter values.
    * @param row the row whose value is to be queried
    * @param column the column whose value is to be queried
    * @return true
    public boolean isCellEditable(int row, int column) {
    return true;
    * Returns an attribute value for the cell at <code>row</code>
    * and <code>column</code>.
    * @param row the row whose value is to be queried
    * @param column the column whose value is to be queried
    * @return the value Object at the specified cell
    * @exception ArrayIndexOutOfBoundsException if an invalid row or
    * column was given
    public Object getValueAt(int row, int column) {
    Vector rowVector = (Vector)dataVector.elementAt(row);
    return rowVector.elementAt(column);
    * Sets the object value for the cell at <code>column</code> and
    * <code>row</code>. <code>aValue</code> is the new value. This method
    * will generate a <code>tableChanged</code> notification.
    * @param aValue the new value; this can be null
    * @param row the row whose value is to be changed
    * @param column the column whose value is to be changed
    * @exception ArrayIndexOutOfBoundsException if an invalid row or
    * column was given
    public void setValueAt(Object aValue, int row, int column) {
    Vector rowVector = (Vector)dataVector.elementAt(row);
    rowVector.setElementAt(aValue, column);
    fireTableCellUpdated(row, column);
    // Protected Methods
    * Returns a vector that contains the same objects as the array.
    * @param anArray the array to be converted
    * @return the new vector; if <code>anArray</code> is <code>null</code>,
    *                    returns <code>null</code>
    protected static Vector convertToVector(Object[] anArray) {
    if (anArray == null) {
    return null;
    Vector v = new Vector(anArray.length);
    for (int i=0; i < anArray.length; i++) {
    v.addElement(anArray[i]);
    return v;
    * Returns a vector of vectors that contains the same objects as the array.
    * @param anArray the double array to be converted
    * @return the new vector of vectors; if <code>anArray</code> is
    *                    <code>null</code>, returns <code>null</code>
    protected static Vector convertToVector(Object[][] anArray) {
    if (anArray == null) {
    return null;
    Vector v = new Vector(anArray.length);
    for (int i=0; i < anArray.length; i++) {
    v.addElement(convertToVector(anArray[i]));
    return v;

  • How to set the Selected row and Column in JTable

    Hi,
    i have a problem like the JTable having one Method getSelectedRow() and getSelectedColumn to know the Selected row and Column but if i want to explicitly set the Selected Row and Column,then there is no such type of Methods.If anybody has any solution then i will be thankful to him/her.
    Praveen K Saxena

    Is that what you're looking for? :myTable.getSelectionModel().setSelectionInterval(row, row);
    myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);

  • JTable, L&F and a TableCellRenderer

    hey guys :)
    i have a lil prob in my swing application. i use a JTable to display my data and i use custom CellEditors and CellRenderers - so far so good. the problem i have now, that the cell itself isnt highlighted (in any way) if it's row is currently selected.
    therefore i took my renderer and changed this method:
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    if(isSelected)
         setBackground(new Color(204,204,255));
         System.out.println("selected");
    else
         setBackground(Color.white);
    [...]that's in accordance with the metal L&F color scheme.
    it works - but it's not the right way to do that... and if the user changes the L&F it's obvious.
    my question is, how can i get the colors (foreground and background) wich i have to use?
    (i know it's an L&F method but i hadnt found it up to now)
    ta :)

    If the component you are producing is a JLabel then the easiest way to do this is to make your TableCellRenderer extend the DefaultTableCellRenderer and start your getTableCellRendererComponent method with a call to the same method in the superclass e.g.
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    // ... make your other changes to label
    return label;
    This is the easiest way to get all the selection, focus, etc. behaviour
    so long as you can use the JLabel.
    If you need to know how to do it for a different component ask.

  • Problem adding columns and rows in JTable

    hi, hope somebody can help me
    i have some problems when i add columns and later i try to set number of rows in JTable, ocurr some exceptions
    my code is something like thisJTable tabla = new JTable();
    TableColumn tc = new TableColumn();
    tc.setHeaderValue("col1");
    tc.setPreferredWidth(20);
    tabla.getColumnModel().addColumn(tc);up to here everything goes well, my table shows the column, but when i add this line((DefaultTableModel)tabla.getModel()).setNumRows(1);ocurrs the next exception
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException: 0 >= 0....
    any ideas????

    oks, that would work when the JTable is created, but now we say that I require a method which adds a new row to the JTable a some moment of execution
    Look some of my code
    i have this in a JFrame...
    JTable tabla = new JTable();
    DefaultTableModel tm = new DefaultTableModel();
    tabla.setModel(tm);
    agrCol("Col1", 80);
    agrCol("Col2", 160);
    agrFil();
    agrFil();
    agrCol(String col, int lon) {
      tm.addColumn(col);
      tabla.getColumn(col).setPreferedWith(lon);
    agrFil() {
      tm.setRowCount(tabla.getRowCount() + 1);
    the jtable shows the 2 columns and 2 rows, but the setPreferedWith work only in the last col, i'm confused

  • JTable selection and sorting

    hi,
    I have JTable with simple sorting method and i dont use the swing's example.
    I need to add a row in a sorted order and the row selection should remaim intact even after i sort and when i refresh the table the selection should not change.if anybody can help to solve this problem they are most welcome.
    thanks,
    SK

    You are on the right track. First get the rect of the row you want to make visible:Rectangle cellRect = aTable.getCellRect( row, 0, true );Then tell the table to scroll to that rect:aTable.scrollRectToVisible( cellRect );There used to be a bug if you tried to scroll to the last row. I haven't gotten around to seeing if it is fixed 1.4 yet. Here is the full method I use (that works around the bug), enjoy:/**
    * Make sure the passed row is visible in the table (in case it is in a
    * scroll view, and the view is currently viewing elsewhere)
    * @param aTable The table to work with
    * @param row The row number that should be visible
    public static void MakeRowVisible( JTable aTable, int row ) {
        Rectangle cellRect = aTable.getCellRect( row, 0, true );
        if( cellRect != null ) {
            // Have to tweak the height of the table so that if we are
            // scrolling to the bottom, it really shows the bottom (swing bug
            // I guess)
            aTable.setSize( aTable.getWidth(), Integer.MAX_VALUE );
            aTable.scrollRectToVisible( cellRect );

  • Help with TableRowSorter , JTable and JList

    Hello,
    I�m developing an application in which I�m using a Jtable and Jlist to display data from a database. Jtable and Jlist share the same model.
    public class DBSharedModel extends DefaultListModel implements TableModelFor the Jtable I set a sorter and an filter
    DBSharedModel dataModel = new DBSharedModel();
    Jtable jTable = new JTable(dataModel) ;
    jTable.createDefaultColumnsFromModel();
    jTable.setRowSelectionAllowed(true);
    TableRowSorter<DBSharedModel> sorter = new TableRowSorter <DBSharedModel> (dataModel);
    jTable.setRowSorter(sorter);From what I read until now JavaSE 6 has NOT a sorter for JList (like one for JTable).
    So, I am using one from a this article http://java.sun.com/developer/technicalArticles/J2SE/Desktop/sorted_jlist/index.html
    When I sort the data from the table, I need to sort the data from the list, too.
    My ideea is to make the Jlist an Observer for the Jtable.
    My questions are:
    1.     How can I find if the sorter makes an ASCENDING or DESCENDING ordering?
    2.     How can I find what the column that is ordered?
    Or if you have any idea on how can I do the ordering on Jlist to be simultaneous to Jtable .
    Please help!
    Thank you

    Oh what the hell:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.

Maybe you are looking for

  • Bought MA607LL/A Intel 1.66 2006 mac mini ubuntu pre install have question

    Hey guys. I bought this model and comes with usb pre installed to drive. Doesn't have OSX. My question is I have a net book with 320gb and that is esata so I'm going to install in the mac. Now  can I put the 60 gb hard drive that came with mac mini i

  • Photos blurry through email

    Whenever I try to email pictures from Iphoto 08, they show up blurry. They are perfectly clear in Iphoto before I attach them to an email. When given the option to choose the size of the picture to be sent, I have tried each one and it doesn't help w

  • Crystal report - Performance Information

    Hi, The performance of a report execution can be get calculated by the following 3 items of Performance Information dialog, Performance Timing node has: 1. Run the database query 2. Read database records 3. Format first page In that, i understand the

  • B2B Schema Password Retrieval

    Hi , Is there any way to retrieve the B2B Schema Password in Oracle AS 10g Release2. It was installed long back by another person. Now need the password to manually queue the messages. Can any one help? Regards, Rafeek.

  • How can I temporarily move some bookmarks from Bookmarks Toolbar

    I've got one folder on Bookmark Toolbar with many bookmarks in it. I don't need it now but don't want to delete it either. The best solution would it be to move this folder with bookmarks to e.g. the MyDocuments folder, which is residing on another p