JTable customization

Hi..
I am using a jtable, there is a need to perform many operation on the jtable, as given below
1). sort the jtable
2). rearrange the column
3). Get a perticular column value and display another dialog box based on its value.(should also work when the columns are rearranged).
4). varying number of columns based on the inputs from the user
5). pagination performed (if the number of records are more that twenty), this time too the sorting should happen correctly.
6). display tool tip. the tool tip backgournd requires to be white with foreground in black.
7). Need to provide filters on the column header based on which records should be sorted(like in MS EXCEL) this should also work when pagination is done.....
I have a custom created table model as shown below... please suggest what requires to be done, whether this table model should be rewritten or modified to achive all the functionality.
* InstActSummTableModel.java
* Created on June 23, 2006, 10:05 AM
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
package action.vector.bam;
import java.awt.Color;
import javax.swing.table.AbstractTableModel;
import java.util.Vector;
* @author serjith
public class InstActSummTableModel extends AbstractTableModel {
protected static int IA_NUM_COLUMNS = 5;
protected static int IA_START_NUM_ROWS = 0;
protected int iIA_nextEmptyRow = 0;
protected int iIAnumRows = 0;
static final public String szInst_Status_Col ="";
static final public String szInst_ID = "Instance Tokens";
static final public String szInst_Start_Time = "Status";
static final public String szInst_End_Time = "Start Time";
static final public String szInst_Correlation_Det = "Instance ID";
protected Vector instActdata = null;
/** Creates a new instance of InstActSummTableModel */
public InstActSummTableModel() {
instActdata = new Vector();
public String getColumnName(int column) {
     switch (column) {
     case 0:
     return szInst_Status_Col;
     case 1:
     return szInst_ID;
     case 2:
     return szInst_Start_Time;
     case 3:
     return szInst_End_Time;
case 4:
return szInst_Correlation_Det;
     return "";
public synchronized int getColumnCount() {
return IA_NUM_COLUMNS;
public synchronized int getRowCount() {
if (iIAnumRows < IA_START_NUM_ROWS) {
return IA_START_NUM_ROWS;
} else {
return iIAnumRows;
public synchronized Object getValueAt(int row, int column) {
     try {
Object[] IA_w = (Object[])instActdata.elementAt(row);
switch (column) {
case 0:
return IA_w[0];
case 1:
return IA_w[1];
case 2:
return IA_w[2];
case 3:
return IA_w[3];
case 4:
return IA_w[4];
     } catch (Exception e) {
     return "";
public Class getColumnClass(int col) {
return getValueAt(0, col).getClass();
public synchronized void clear() {
     int oldNumRows = iIAnumRows;
iIAnumRows = IA_START_NUM_ROWS;
     instActdata.removeAllElements();
iIA_nextEmptyRow = 0;
     if (oldNumRows > IA_START_NUM_ROWS) {
     fireTableRowsDeleted(IA_START_NUM_ROWS, oldNumRows - 1);
     fireTableRowsUpdated(0, IA_START_NUM_ROWS - 1);
public synchronized void updateInstActSumm(Object[] InstActRecord){
String InstActRec_ID = (String)InstActRecord[1]; //find the Name
Object[] p = null;
int index = -1;
boolean found = false;
     boolean addedRow = false;
int i = 0;
int vecsize = instActdata.size();
if (vecsize == 0){ System.out.println( " The data vector is null");}
else{
System.out.println(" The data vector is not null "+vecsize);
for (int l=0;l<vecsize;l++){
Object[] q = (Object[])instActdata.elementAt(l);
for(int m=0;m<q.length;m++){
System.out.println("Vector Content "+ q[m]+" at position "+l);
System.out.println("numRows "+iIAnumRows);
System.out.println("nextEmptyRow "+iIA_nextEmptyRow);
System.out.println("index "+index);
System.out.println("data.size() "+instActdata.size());
while (!found && (i < iIA_nextEmptyRow)) {
p = (Object[])instActdata.elementAt(i);
System.out.println("value of p[1] -- "+(String)p[1]);
System.out.println("value of PTypeName is -- "+InstActRec_ID);
String pofOne = (String)p[1];
if ( InstActRec_ID.equals(pofOne)==true) {
found = true;
index = i;
} else {
i++;
if (found) { //update old player
     instActdata.setElementAt(InstActRecord, index);
System.out.println("Updating the old player");
} else { //add new player
     if (iIAnumRows <= iIA_nextEmptyRow) {
          //add a row
iIAnumRows++;
          addedRow = true;
index = iIA_nextEmptyRow;
     instActdata.addElement(InstActRecord);
System.out.println("Entering a new player");
iIA_nextEmptyRow++;
     //Notify listeners that the data changed.
     if (addedRow) {
     fireTableRowsInserted(index,index);
     } else {
     fireTableRowsUpdated(index, index);
System.out.println("//////////////////Start in the end//////////////////////////////");
for (int l=1;l<instActdata.size();l++){
Object[] q = (Object[])instActdata.elementAt(l);
for(int m=1;m<q.length;m++){
System.out.println("Vector Content "+ (String)q[m] );
System.out.println("numRows "+iIAnumRows);
System.out.println("nextEmptyRow "+iIA_nextEmptyRow);
System.out.println("index "+index);
System.out.println("data.size() "+instActdata.size());
System.out.println("///////////////////END////////////////////////////////////////////");
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col == 2) {
return true;
} else {
return false;
Message was edited by:
serjith

1) You can sort your data before creating your JTable with a SortMap
2) You can drag and drop the colum like you want
3) You can add a mouse listener on a cell and do a specific action with the value
4) You can add column to a JTable with the addColumn method
5) You will have to create a pagination system. Like with a start indew and an end index and the index change when you press 'next' or 'previous'
6) You can add tooltip with the model
7) You can add what you want in headers so if your data are stored in a map you can use your filters and recreate the JTable content
Please have a look of the examples in the java tutorial. You will find many answers to your questions (with the Color Chooser exemple)

Similar Messages

  • Exported the JTable to excel  but to customize the excel file

    Hi,
    I have exported the JTable to excel through CSV file. But I want to customize the excel file, by setting border, color and cell styles. How to implement this? Can you please help me out?
    Thanks,
    public class CalculateUsers extends JPanel implements     ActionListener,     TableModelListener {
         JFrame frame;
         JTable table;
         public CalculateUsers(JPanel mainPanel) {
                    rows = new Vector();
              columns = new Vector();
              String[] columnNames = {"BP","users","Avg","time"};
              addColumns(columnNames);
              tabModel = new DefaultTableModel();
              tabModel.setDataVector(rows, columns);
              table = new JTable(tabModel);
              table.getModel().addTableModelListener(this);
              lblMessage = new JLabel("");
                 label1 = new JLabel("Textbox 1");
                    label2 = new JLabel("Textbox 2");
                    text1 = new JTextField(5);
              text2 = new JTextField(5);
              buttonPanel = new JPanel();
                        cmdAdd = new JButton("add");
                        cmdCalculate = new JButton("Calculate");
              cmdExportToExcel = new JButton("ExportToExcel");
                    buttonPanel.add(label1);
              buttonPanel.add(text1);
              buttonPanel.add(label2);
              buttonPanel.add(text2);
              buttonPanel.add(cmdCalculate);
              buttonPanel.add(cmdExportToExcel);
              buttonPanel.add(cmdAdd);
         public void addRow() { // Add Row
              Vector r = new Vector();
              r = createBlankElement();
              rows.addElement(r);
                    table.addNotify();
         public Vector createBlankElement() {
              Vector t = new Vector();
              t.addElement((String) " ");
              t.addElement((String) " ");
              t.addElement((String) " ");
              t.addElement((String) " ");
              t.addElement((String) " ");
              t.addElement((String) " ");
              t.addElement((String) " ");
                 return t;
         public void calculate() throws Exception {
                int i = table.getRowCount();
                int firstCellVal, secondCellVal, thirdCellVal, fourthCellVal, fifthCell, sixthCell, sevenCell, eightCell,jtext1,jtext2;
               try{ 
                     tabModel.addColumn("Time taken");
                 tabModel.addColumn("Pse");
                 tabModel.addColumn("Users %");
                 tabModel.setColumnCount(7);
                    jtext1 = Integer.parseInt(text1.getText().toString().trim());
                    jtext2 = Integer.parseInt(text2.getText().toString().trim());
                  for (i = 0; i < table.getRowCount(); i++) {
                        String cell1 = table.getValueAt(i, 0).toString();
                        String cell2 = table.getValueAt(i, 1).toString();
                        String cell3 = table.getValueAt(i, 2).toString();
                        String cell4 = table.getValueAt(i, 3).toString();
                        sixthCell = secondCellVal * thirdCellVal * fourthCellVal;
                        sevenCell = ((jtext1 - (fourthCellVal * thirdCellVal))/(fourthCellVal - 1));
                        eightCell = (secondCellVal * 100)/jtext2;
                        table.setValueAt(result2, i, 4);
                        table.setValueAt(result3, i, 5);
                        table.setValueAt(result4, i, 6);
                } catch(Exception ae) {
                        ae.printStackTrace();
         public void actionPerformed(ActionEvent source) throws ArithmeticException { // ActionList
              if (source.getSource() == (JButton) cmdAdd) {
                        addRow();
              if (source.getSource() == (JButton) cmdCalculate) {
                          calculate();
              if (source.getSource() == (JButton) cmdExportToExcel) {
                         exportToExcel();
          private void exportToExcel() throws Exception{
                   exportTable();
         *public void exportTable() { // export Table*
    *          try {*
    *               System.out.println("Exporting Table ");*
    *               String filename = "ScenarioAutomation" + System.currentTimeMillis()+ ".CSV";*
    *               File file = new File(filename);*
    *               String data;*
    *               String columnNames[] = null;*
    *               columnNames = new String[table.getColumnCount()];*
    *               if (file != null) {*
                                *try {*
    *                    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));*
    *                    PrintWriter fileWriter = new PrintWriter(bufferedWriter);*
    *                    System.out.println("Column Headers ");*
    *                    firstRowInExcel(fileWriter);*
    *                    for (int j = 0; j < columnNames.length; j = j + 1) {*
    *                        columnNames[j] = table.getColumnModel().getColumn(j).getHeaderValue().toString();*
    *                        data = columnNames[j];*
    *                        System.out.println("data " + data);*
    *                        fileWriter.print(data + ",");*
                                   *     System.out.println("Done.... ");*
                                   *     fileWriter.println("");*
                                   *     System.out.println("Exporting Data ");*
    *                    for (int k = 0; k < table.getRowCount(); ++k) {*
                                        *for (int l = 0; l < table.getColumnCount(); ++l) {*
    *                         data = table.getValueAt(k, l).toString();*
    *                         fileWriter.print(data + ",");*
                                        *fileWriter.println("");*
    *                    fileWriter.close();*
    *                    System.out.println("Done.... ");*
    *                    System.out.println("File Name " + filename);*
    *                    open(file);*
    *                    } catch (Exception e) {*
                                        *JOptionPane.showMessageDialog(null, "Error " + e);*
    *          } catch (Exception E) {*
    *               System.out.println("Error While Exporting Table " + E);*
    *     private void firstRowInExcel(PrintWriter fileWriter) {*
                    *fileWriter.println("");*
    *          String jtext1label = ("Textbox 1");*
    *          fileWriter.print(jtext1label);*
    *          fileWriter.print(",");*
    *          String jtext1Value = text1.getText();*
    *          fileWriter.print(jtext1Value);*
    *          fileWriter.print(",");*
    *          fileWriter.print(" ");*
          *private void open(File f) {*
           *     String[] commands = {*
    *          "rundll32",*
    *          "url.dll,FileProtocolHandler",*
    *          f.getAbsolutePath()*
    *          try {*
                        *System.out.println("****OPEN file ****");*
                        *Runtime.getRuntime().exec(commands);*
    *          } catch (IOException e) {*
                        *e.printStackTrace();*
    *}*

    for this purpose you need to took help of the third party APIs.
    try POI from Apache
    http://poi.apache.org/hssf/index.html
    this is easy and efficent. and Free also.
    one more i found is
    http://es.actuate.com/xlsjbook/apibasics.html (Not sure about this one.)
    good luck go ahead

  • How to customize the JTable (fonts, colors)

    Hi,
    I wonder how to customize the font, font style and color of a JTable? Shell I make my own renderer for it, or even the Look&Feel? I hope there is an easier way to do it... Something like CSS for HTML.
    I would appreciate some links to the sample code or tutorial as well.
    Best regards,
    Martin

    Try making your own cell renderer.
    MyCellRenderer implements javax.swing.table.TableCellRenderer{
    public MyCellRenderer() {
    public java.awt.Component getTableCellRendererComponent(javax.swing.JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
    //make a JLabel (you can use html just by setting it as text for the JLabel)
    return JLabel;
    then just call
    myJTable.setDefaultCellRenderer(new MyCellRenderer());

  • Help!How do a customizer about array in JTable?

    I do a class that extend JTable and i do a customizer,
    it is right when i set a property of String type,but some property are array(for example :int[] or String[];),
    how set array property?thanks!

    in a word,my problem is : if a property is array how
    to do a customizer and raise(make) source code ?Hi again,
    if only you would use java-terms sigh - I guess, with a property you mean data in a tablecell and a customizer is a TableCellRenderer resp. a TableCellEditor, right?
    The Java-Online-Tutorial available here has good examples for creating cellrenderer and celleditors - it is a good idea to read this and work on the examples - it is too much for a topic in the forum if you are not familiar with it.
    Perhaps you mean that a row in the table is expressed by an array - in this case you had to create your own TableDataModel and implement the methods the JTable uses to communicate with this model - e.g. the getValueAt(row,column)-method to get a value - in such a method you can pass the value of an element of your array-structure for example.
    All these things are explained in the tutorial that is available from the Docs & Training link left-up. It would be a good idea to read and work on it.
    greetings Marsian

  • How do I customize the look of my JTable in a scrollable pane

    When I have a JTable in a scrollable pane, there is an annoying blue border that I want to get rid of. I would also like it if, even if there are no entries in the table, the column heads would still show up. Finally, I want to change the background of the table so it is not the grey-ish color that it defaults to. Do you know how to do any of these things?
    thanks,
    Eric

    Read through the relevant sections of the [javax.swing API|http://java.sun.com/javase/6/docs/api/javax/swing/package-summary.html], specifically the page for JTable .

  • Customize jtable rows

    Hi:
    I have been trying to make my table rows display different colors. Basically, it works already. But there is a weird aspect I don't quite understand; here is what I did:
    I wrote a CellRenderer by extending JLabel and implementing TableCellRenderer; in the CellRenderer, I override the getTableCellRendererComponent method; in this method, I did all my row updating stuff; I also assigned this CellRenderer to each of my table's columns;
    The weird part is, everytime I update my table (such as adding rows), I must RE-assign the CellRenderers to my columns; otherwise, the rows do not get customized like the way i want them to. Since the CellRenderers are assigned to each column , why does it matter when new rows are added? I don't quite understand that.
    Thanks

    You have to modify the underlying TableModel and implement the listener mechanism necessary for that. AFAIK, the default JTable is quite dumb and can't do anything,

  • How to customize a JTextField as CellEditor for a JTable?

    Hi, I want select all the text (for overwriting) which is already in the table cell.
    I had tried to extend AbstractCellEditor (or DefaultTableCellRenderer) and implemented TableCellEditor .
    In the method:
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    I tried to call selectAll() on my JTextField but nothing had happen.
    I also tried to set the value before (instanceof Stirng).
    Any help appreciated.
    Greetings Michael

    This posting shows one possible solution:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=580410

  • Customize a JTable cell

    Dear members,
    I want to insert a custom component such as a JPanel to a cell in a JTable.Is it possible to do this.Plz tell me how to do this.
    Thanks a lot,
    Chamal De Silva.

    http://onesearch.sun.com/search/developers/index.jsp?col=devforums&qp_name=Swing&qp=forum%3A57&qt=%2Btitle%3Ajtable+%2Brenderer+%2Bjpanel

  • To change the font of a selected row in a Jtable

    Hello,
    Is it possible to change the font of a selected row in a jtable?
    i.e. if all the table is set to a bold font, how would you change the font of the row selected to a normal (not bold) font?
    thank you.

    String will be left justified
    Integer will be right justified
    Date will be a simple date without the time.
    As it will with this renderer.Only if your custom renderer duplicates the code
    found in each of the above renderers. This is a waste
    of time to duplicate code. The idea is to reuse code
    not duplicate and debug again.
    No, no, no there will be NO duplicated code.
    A single renderer class can handle all types ofdata.
    Sure you can fit a square peg into a round hole if
    you work hard enough. Why does the JDK come with
    separate renderers for Date, Integer, Double, Icon,
    Boolean? So that, by default the rendering for common classes is done correctly.
    Because its a better design then having code
    with a bunch of "instanceof" checks and nested
    if...else code.This is only required for customization BEYOND what the default renderers provide
    >
    And you would only have to use instanceof checkswhen you required custom
    rendering for a particular classAgreed, but as soon as you do require custom
    renderering you need to customize your renderer.
    which you would also have to do with theprepareRenderer calls too
    Not true. The code is the same whether you treat
    every cell as a String or whether you use a custom
    renderer for every cell. Here is the code to make the
    text of the selected line(s) bold:
    public Component prepareRenderer(TableCellRenderer
    renderer, int row, int column)
    Component c = super.prepareRenderer(renderer, row,
    , column);
         if (isRowSelected(row))
              c.setFont( c.getFont().deriveFont(Font.BOLD) );
         return c;
    }It will work for any renderer used by the table since
    the prepareRenderer(...) method returns a Component.
    There is no need to do any kind of "instanceof"
    checking. It doesn't matter whether the cell is
    renderered with the "Object" renderer or the
    "Integer" renderer.
    If the user wants to treat all columns as Strings or
    treat individual columns as String, Integer, Data...,
    then they only need to override the getColumnClass()
    method. There is no change to the prepareRenderer()
    code.
    Have you actually tried the code to see how simple it
    is?
    I've posted my code. Why don't you post your solution
    that will allow the user to bold the text of a Date,
    Integer, and String data in separate column and then
    let the poster decide.Well, I don't see a compilable, runnable demo anywhere in this thread. So here's one
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.Vector;
    public class TableRendererDemo extends JFrame{
        String[] headers = {"String","Integer","Float","Boolean","Date"};
        private JTable table;
        public TableRendererDemo() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            Vector headerVector = new Vector(Arrays.asList(headers));
             Vector data = createDataVector();
            DefaultTableModel tableModel = new DefaultTableModel(data, headerVector){
                public Class getColumnClass(int columnIndex) {
                    return getValueAt(0,columnIndex).getClass();
            table = new JTable(tableModel);
    //        table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
            table.setDefaultRenderer(String.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Integer.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Float.class, new MyTableCellRenderer());
            table.setDefaultRenderer(Date.class, new MyTableCellRenderer());
            JScrollPane jsp = new JScrollPane(table);
            mainPanel.add(jsp, BorderLayout.CENTER);
            pack();
            setLocationRelativeTo(null);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        private Vector createDataVector(){
            Vector dataVector = new Vector();
            for ( int i = 0 ; i < 10; i++){
                Vector rowVector = new Vector();
                rowVector.add(new String("String "+i));
                rowVector.add(new Integer(i));
                rowVector.add(new Float(1.23));
                rowVector.add( (i % 2 == 0 ? Boolean.TRUE : Boolean.FALSE));
                rowVector.add(new Date());
                dataVector.add(rowVector);
            return dataVector;
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    TableRendererDemo tableRendererDemo = new TableRendererDemo();
                    tableRendererDemo.setVisible(true);
            SwingUtilities.invokeLater(runnable);
        class MyTableCellRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                 super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                if ( isSelected){
                    setFont(getFont().deriveFont(Font.BOLD));
                else{
                    setFont(getFont().deriveFont(Font.PLAIN));
                if ( value instanceof Date){
                    SimpleDateFormat formatter =(SimpleDateFormat) SimpleDateFormat.getDateInstance(DateFormat.MEDIUM);
                    setText(formatter.format((Date)value));
                if(value instanceof Number){
                   setText(((Number)value).toString());
                return this;
    }Hardly a "bunch of instanceof or nested loops. I only used the Date instanceof to allow date format to be specified/ modified. If it was left out the Date column would be "18 Apr 2005" ( DateFormat.MEDIUM, which is default).
    Cheers
    DB

  • How do i change the color of a JTable's column names

    hai,
    i'm very new to java and trying to customize the look of a JTable.
    how do i change the color of a JTable's Column names. i know its very simple, i just couldn't figure out how to do it!!
    thanx in advance

    table.getTableHeader().setForeground(Color.RED);

  • JTable with JToolBar inegrated

    Hello.
    My requirement: A swing component (JPanel, JTable...) consisting of a table and a tool bar with buttons for inserting/removing rows in the table. This component must be visually configurable in NetBeans v&iacute;a 'Table contents...' dialog.
    If I extend JPanel I won't be able to visually edit the table inside; if I extend JTable I don't know how to integrate the toolbar inside of it.
    Any hint?
    Thank you.
    Antonio.

    Solution:
    1. Extend JPanel, e.g. JTablePanel, with BorderLayout, and add a tool bar (north) and a container (center) where the table will be placed, e.g., private JPanel tablePanel;.
    2. Create a public method that returns that container where the table will be placed, e.g.: public JPanel getTablePanel();3. Create a BeanInfo for your table panel: JTablePanelBeanInfo. You can return the defaults for all of the methods but getBeanDescriptor should look like this:
        @Override
        public BeanDescriptor getBeanDescriptor() {
            BeanDescriptor beanDescriptor = new BeanDescriptor(com.yourpackage.JTablePanel.class, null );
            beanDescriptor.setValue("containerDelegate", "getTablePanel");
            return beanDescriptor;
        }The point here is setting the value "containerDelegate".
    4. Compile everything and create a new BeanForm based on JTablePanel and put your table instance inside the form by dragging it from the palette.
    5. Now you can visually customize your table, improving reusability and productivity in your project.
    Reference:
    [How do I create a custom container bean?|http://wiki.netbeans.org/FaqFormCustomContainerBean]

  • How can I add custom right-click-menu to column headers in JTable?

    Can anyone point me to a topic on how to customize a popup menu for column headers in JTable? Specifically, I want to add things like "auto-size column" and "hide column".
    Thanks,
    Matt

    Right-click on your table.  Then go to Advanced->Runtime Shortcut Menu->Edit.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to use/populate JTable in Jdev 3.0 ?

    Is there any tutorial or examples available
    on how to use JTable in JDeveloper 3.0 ?
    After creating business objects project
    and application, what steps do I take to
    a) put a jtable class object into my application ? I have tried creating a
    frame (JFrame) using new\objects\frame, and
    then dragging JTable into the UI, but don't
    know how to connect things from there.
    b). manipulate/populate the grid from there
    using the business objects created
    earlier in the project ?
    The html documentation included with JDev 3 provides some clues on individual key word searches, but does not at all connect the dots. What is needed
    here is a tutorial like some of the others
    included.
    null

    You may find the following steps useful.
    Create an InfoBus form by:
    Select menu File | New...
    Select "InfoBus Data Form" and press OK
    Go through the wizard and create a
    Detail or Master Detail form.
    Be sure to place the detail in a GRID control (last few pages of wizard).
    Then look at the generated code. This form will contain a useful class GridControl which contains a JTable element. Most noteworthy is that the JTable is already hooked up to the data source.
    In particular, the GridControl that is in
    your source has a public method:
    public final JTable getTable()
    This gives you access to the JTable to further customize the way you need.
    Ofcourse there are other tutorials that touch
    on the above, but you won't find a tutorial
    on how to hook up a JTable to a database because we have many more advanced classes
    (InfoSwing: GridControl,...) that do that
    and much more for you. You will be much more
    productive if you rely on the additional InfoSwing components.
    I hope this helps,
    John@Oracle JDeveloper Team http://technet.oracle.com
    null

  • Scrollbar problem with JTable.

    Hi,
    I have 45 columns in a JTable. Please remember this is customize, we can change the number of columns dynamically, at max they can be 2 columns.
    i was having a problem with display the columns names in my Frame. I posted at http://forum.java.sun.com/thread.jspa?threadID=5167358&messageID=9641265#9641265
    I got the solution. Thanks for that.
    But as i said these columns are customized.
    when i am having 2 columns in my JTable, table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); is behaving differently, it's not occupying the complete JFrame. Lots of space is left out beside these 2 columns.
    When i comment this line, then those 2 columns are occupying my complete Frame.
    these two colmns should occupy my complete Frame and if i select 45 columns i should get scroll bar at botton with complete column NAMES.
    Hope i am clear.
    My Snippet
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    public class SimpleTable extends JPanel {
        private boolean DEBUG = false;
        public SimpleTable() {
            super(new BorderLayout());
                        String[][] values = new String[10][];
            String[] columnNames = {
                                                                                    "First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian"
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
                        DefaultTableModel defaulttablemodel = new DefaultTableModel(data,columnNames);
            final JTable table = new JTable(defaulttablemodel)
                 public boolean isCellEditable(int row,int column)
                                  return false;
                        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                        //table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
                        JScrollPane scrollPane = new JScrollPane(table);
                        add(scrollPane);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("SimpleTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            SimpleTable newContentPane = new SimpleTable();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thank You camickr, it's serving my purpose.
    Just for a clarrification :
    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    table.setAutoscrolls(false);without using these lines also my purpose is serving.....then y do we need above two lines of code. r they necessary
    i mean, this snippet is sufficient.
    public boolean getScrollableTracksViewportWidth()
         return getPreferredSize().width < getParent().getWidth();
    }

  • 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 );

Maybe you are looking for