Jtable with MultiRowHeader and multiCell

Dear Developers,
I saw there is a sample code:
http://www2.gol.com/users/tame/swing/examples/JTableExamples7.html
about the Multiple Row Hearder example, however I can't change the rowHeight nor the column width.
I want to create like the following complex table:
http://www.geocities.com/javaxml8/complextable.htm
I tried to overwrite the SetRowHeight, but the row height still the same.
Thanks in advance

After struggling with the examples like you I finally made it by doing as follows:
DefaultTableModel() dm = new DefaultTableModel() {
public Class getColumnClass(int columnIndex) {
return String.class;
dm.addRow(new Object[]{"\n\n"});
AND YOU'RE DONE !!!!!!!!!!!!!!!!!!!

Similar Messages

  • How to keep the first row fixed in a JTable, with sorting, and bellow the headers ?

    I am trying to change the following code so then the fixed rows will stay on top(but below the headers!), but when I change getContentPane().add(fixedScroll, BorderLayout.SOUTH); to getContentPane().add(fixedScroll, BorderLayout.NORTH); it stays above the headers. How can I put the first rows on top, but below the headers ? Thanks.
    import java.awt.*; 
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    * @version 1.0 03/05/99
    public class FixedRowExample extends JFrame {
      Object[][] data;
      Object[] column;
      JTable fixedTable,table;
      private int FIXED_NUM = 2;
      public FixedRowExample() {
        super( "Fixed Row Example" );
        data =  new Object[][]{
            {      "a","","","","",""},
            {      "","b","","","",""},
            {      "","","c","","",""},
            {      "","","","d","",""},
            {      "","","","","e",""},
            {      "","","","","","f"},
            {"fixed1","","","","","","",""},
            {"fixed2","","","","","","",""}};
        column = new Object[]{"A","B","C","D","E","F"};
        AbstractTableModel    model = new AbstractTableModel() {
          public int getColumnCount() { return column.length; }
          public int getRowCount() { return data.length - FIXED_NUM; }
          public String getColumnName(int col) {
           return (String)column[col];
          public Object getValueAt(int row, int col) {
            return data[row][col];
          public void setValueAt(Object obj, int row, int col) {
            data[row][col] = obj;
          public boolean CellEditable(int row, int col) {
            return true;
        AbstractTableModel fixedModel = new AbstractTableModel() {     
          public int getColumnCount() { return column.length; }
          public int getRowCount() { return FIXED_NUM; }
          public Object getValueAt(int row, int col) {
            return data[row + (data.length - FIXED_NUM)][col];
        table = new JTable( model );
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setAutoCreateRowSorter(true);
        fixedTable = new JTable( fixedModel );
        fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll      = new JScrollPane( table );
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
          public void setColumnHeaderView(Component view) {} // work around
                                                 // fixedScroll.setColumnHeader(null);
        fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        JScrollBar bar = fixedScroll.getVerticalScrollBar();
        JScrollBar dummyBar = new JScrollBar() {
          public void paint(Graphics g) {}
        dummyBar.setPreferredSize(bar.getPreferredSize());
        fixedScroll.setVerticalScrollBar(dummyBar);
        final JScrollBar bar1 = scroll.getHorizontalScrollBar();
        JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
        bar2.addAdjustmentListener(new AdjustmentListener() {
          public void adjustmentValueChanged(AdjustmentEvent e) {
            bar1.setValue(e.getValue());
        scroll.setPreferredSize(new Dimension(400, 100));
        fixedScroll.setPreferredSize(new Dimension(400, 52));  // Hmm...
        getContentPane().add(     scroll, BorderLayout.CENTER);
        getContentPane().add(fixedScroll, BorderLayout.SOUTH);   
      public static void main(String[] args) {
        FixedRowExample frame = new FixedRowExample();
        frame.addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent e ) {
            System.exit(0);
        frame.pack();
        frame.setVisible(true);

    Sorry, this code missed a very important line:
    table.setAutoCreateRowSorter(true);
    So you meant:
    Object[][] header;//class atribute
    header=new Object[][]{//in the constructor
                { "h","i","j","k","l","m"},
                { "h","i","j","k","l","m"}
    public Object getValueAt(int row, int col) {//in the TableModel
            if (row==0){
                return header[row][col];
            else {
                return data[row][col];
    I tried, but when I sort, the first row get sorted with the rest.

  • Mouse motion listener for JTable with JScrollpane

    Hi All,
    I have added mouse motion listener for JTable which is added in JScrollPane. But if i move the mouse, over the vertical/horizontal scroll bars, mouse motion listener doesn't works.
    So it it required to add mousemotionlistener for JTable, JScrollPane, JScrollBar and etc.
    Thanks in advance.
    Regards,
    Tamizhan

    I am having one popup window which shows address information. This window contains JTable with JScrollPane and JButton components to show the details. While showing this information window, if the mouse cursor is over popupwindow, it should show the window otherwise it should hide the window after 30 seconds.
    To achieve this, i have added mouse listener to JPanel, JTable, JButton and JScrollPane. so if the cursor is in any one of the component, it will not hide the window.
    but for this i need to add listener to all the components in the JPanel. For JScrollPane i have to add horizontal, vertical and all the top corner buttons of Scroll bar.
    Is this the only way to do this?

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

  • How to print jTable with custom header and footer....

    Hello all,
    I'm trying to print a jTable with custom header and footer.But
    jTable1.print(PrintMode,headerFormat,footerFormat,showPrintDialog,attr,interactive)
    does not allow multi line header and footer. I read in a chat that we can make custom header and footer and wrap the printable with that of the jTable. How can we do that..
    Here's the instruction on the chat...
    Shannon Hickey: While the default Header and Footer support in the JTable printing won't do exactly what you're looking for, there is a straight-forward approach. You can turn off the default header/footer and then wrap JTable's printable inside another Printable. This wrapper printable would then render your custom data, and then adjust the size given to the wrapped printable
    But how can i wrap the jTable's Printable with the custom header and footer.
    Thanks in advance,

    I also once hoped for an easy way to modify a table's header and footer, but found no way.
    Yet it is possible.

  • Creating a JTable with resizeable columns and Horizontal Scrollbar

    Hi,
    I would like to create a JTable with about 24 columns in it. The problem is, my ViewPort in my JScrollPane is about 3-400pixels wide, and the JTable tries to cram itself into the ViewPort. This makes the columns too tiny to read. I'd like it to do something a little more sensible, like use the PreferredSize of the columns. Can anyone point me in the right direction to keep JTable from creating scrunched up little columns, so that it creates columns that are at least partially readable? Thanks.
    BTW, I suppose I could set NO_AUTO_RESIZE but I would rather not do that. I like being able to resize columns. Basically what I want to do is control the JTable's width and not worry about the ViewPort's width.

    This made it impossible to resize columns. Works fine for me:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableHorizontal extends JFrame
        public TableHorizontal()
            JTable table = new JTable(5, 10);
            table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            table.getColumnModel().getColumn(0).setPreferredWidth(10);
            table.getColumnModel().getColumn(1).setPreferredWidth(20);
            table.getColumnModel().getColumn(2).setPreferredWidth(30);
            table.getColumnModel().getColumn(3).setPreferredWidth(40);
            table.getColumnModel().getColumn(4).setPreferredWidth(50);
        public static void main(String[] args)
            TableHorizontal frame = new TableHorizontal();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • How to get the data from a jtable with random order??

    hi everyone,
    i have a jtable i filled with Strring and Float data, i put this data to a MySQL database, and i use vectors and iterators to filled the database. the problem is there are some cells that are empty, and the Floats' columns throws me nullpointerexceptions.
    please if anyone know how to avoid that exception i'd would be great.
    thanks for your time.

    HI Siggi,
    Thank you for your reply..
    I am also planning to do FM to get the data. But it is saying that the Cluster table ZES does not exist (ZES is the the standard table, in SE11 also).
    How can I use the Fields from the that table.?
    What can I do now, can you please explain me about this point.
    Waiting for your reply.
    Thanks and Regards
    Rajesh
    Message was edited by:
            rajesh

  • JTable with JCheckbox problems

    Ok so I have a couple of questions. I have a JTable with a column represented as a checkbox.
    1. If I put the checkbox column as the first in the table, the rest of the cells are blank/null. Any idea what the reason is?
    2. What is the best workaround to having draggable columns, meaning icons/checkboxes don't render if you move the columns around?
    3. Does anyone have some links to good resources on JTables and things like custom components in them. I have googled but don't get many good links so would appreciate any help
    Code snippet as follows:
    public class ClobberTableCellRenderer implements TableCellRenderer
    private JPanel renderPanel = new JPanel(new BorderLayout());
    private JLabel renderLbl = new JLabel("");
    private JCheckBox checked = new JCheckBox();
    private Icon successIcon;
    private Icon errorIcon;
    public Component getTableCellRendererComponent(JTable table,
    Object value,
    boolean isSelected,
    boolean hasFocus,
    int row,
    int column)
    String columnName = table.getModel().getColumnName(column);
    if (value == null)
    return null;
    else if ("Status".equals(columnName) && "ok".equals(value))
    renderLbl.setIcon(successIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Status".equals(columnName) && "error".equals(value))
    renderLbl.setIcon(errorIcon);
    renderLbl.setText("");
    renderPanel.remove(checked);
    else if ("Active".equals(columnName))
    renderLbl.setText("");
    renderPanel.add(checked);
    renderPanel.setBackground(Color.white);
    else
    renderLbl.setHorizontalAlignment(value instanceof Date || value instanceof Number ? JLabel.RIGHT : JLabel.LEFT);
    renderLbl.setIcon(null);
    renderLbl.setText(value instanceof Date ? df.format((Date)value) : value.toString());
    renderLbl.setToolTipText(null);
    renderPanel.setToolTipText(null);
    renderPanel.remove(checked);
    if (isSelected)
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.selectionBackground"));
    else
    renderPanel.setBackground((Color)UIManager.getDefaults().get("Table.background"));
    return renderPanel;
    }

    Hi :) I have also worked on JTables and JCheckBoxes before. This article
    helped me a lot: http://www-128.ibm.com/developerworks/java/library/j-jtable/

  • 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]

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • How do I create a jtable with horizontalScroll bar,plz help me!

    I created a jtable component,Because my table's columns has 50 items,I must need a horizontalScroll Bar.
    but I find the horizontalScroll don't display,when I add record to the jtable,the verticalScroll Bar is showed.How do I create a jtable with horizontalScroll bar,can u help me!
    thank you in advance!

    Hi,
    This piece of code will help :
         //Get the Component Adapter for taking action against resizing of
    //of Panel
    ComponentListenerAdapter componentAdapter =
    new ComponentListenerAdapter()
    //Get the scrollbar or remove the scrollbar upon resizing
    protected void resizingAction()
    Container tableParent = table.getParent();
    if (tableParent instanceof JViewport)
    //Check if the width of the Table Parent Container
    //is less than the Preferred Size of the Table
    if (tableParent.getSize().getWidth() <
    table.getPreferredSize().getWidth())
    //Yes it is
    //Remove the Auton Resize Function and get the
    //Scrollbar
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    else
    //No it is not
    //Get the Auto Resize functionality back in place
    table.setAutoResizeMode(
    JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    //Add the component Adapter to the Table Header
    table.getTableHeader().addComponentListener(componentAdapter);
    private abstract class ComponentListenerAdapter
    implements ComponentListener
              * The <code>componentHidden<code> method has no implementation
              * @param event The Event occured whenever the Component is Hidden
              public void componentHidden(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentShown</code> method has no implementation
              * @param event The Event occured whenever the Component is Shown
              public void componentShown(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentMoved</code> method has no implementation
              * @param event The Event occured whenever the Component is Moved
              public void componentMoved(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentResized</code> method is invoked whenever the
              * component is resized. The resizing action will set the columns and
              * scrollbar to act properly
              * @param event The Event occured whenever the Component is Resized
              public void componentResized(ComponentEvent event)
                   resizingAction();
    * Subclasses of this override this method to determine what is to be
    * done once the Component has been Resized
    protected abstract void resizingAction();
    Hope this will solve all your JTable horizontal resizing problems
    --j                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • JTable with JPanel form as cell renderer/editor

    I have a JTable that uses a custom cell editor/renderer. The cell editor/renderer is a JPanel form with labels and text panes. As the user edits the information, I adjust the table row height (setRowHeight) and the JPanel layout manager updates the layout on the cell editor. This all seems to work fine. However, when the user exists the cell and the cell renderer is shown, it has the correct new row height but has not been correctly layed-out for the new row height. How do I force my cell renderer to be re-layout after the editor closes?

    That does not seem to work. I have done the following:
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int r, int c)
    this.table = (EditorTable) table;
    row = r;
    column = c;
    if (isSelected)
    setBackground (Preferences.selectedRowBgColor);
    else
    setBackground (formBg);
    // constructs the panel components
    setCellValue (value);
    revalidate();
    return (this);

  • Custom JTable cell editors and persistence

    I have a JTable with an underlying data model (an extension of AbstractTableModel) that uses custom cell editors in the last column. The cell editor in that column, for a given row, depends on the value selected in another column of the same row. The cell editors include text, date, list, and tree editors (the last one in a separate dialogue). The number of rows is changeable.
    I have need to persist the data for a populated table from time to time, for restoration later on. I've achieved that, such that the data model is recreated, the table appears correct, and the appropriate cell editors activated (by creating new instances of the editors' classes).
    However, my problem is that the (custom) cell editors do not reflect the data in the model when editing mode is begun the first time after restoration. Eg. the text editor is always empty, the list editor shows the first item, and no node is selected in the tree editor.
    If I've restored the model correctly, should the editors properly reflect the underlying data when they are set to editing mode?
    I suspected not, and thus tried to explicitly 'set' the correct values immediately after each editor is recreated ... but to no avail.
    Does anyone have any thoughts, or experience with something similar? I'm happy to supply code.

    You can use html tags within Swing, so I think you can do the following:
    * MyRenderer.java
    * Created on 26 April 2007, 10:27
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package newpackage;
    import java.awt.Component;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.SwingConstants;
    import javax.swing.table.TableCellRenderer;
    * @author CS781RJ
    public class MyRenderer extends JLabel implements TableCellRenderer
        public MyRenderer()
            setHorizontalTextPosition(SwingConstants.RIGHT);
            setIconTextGap(3);
            setOpaque(true);
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean cellHasFocus, int row, int column)
            if (isSelected)
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            else
                setBackground(table.getBackground());
                setForeground(table.getForeground());
            if (value instanceof String)
                if ((value != null) && (value.toString().length() > 0))
                    System.out.println("Value: " + value.toString());
                    setFont(new java.awt.Font("Tahoma", 0, 11));
                    setText("<html>" + value.toString().replaceAll("\n", "<br>") + "</html>");
            return this;
    }In the class that has the JTable, use the code AFTER declaring the values, columns, etc:
    jTable1.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
    jTable1.setValueAt("Riz\nJavaid", 0, 0);One thing I haven't done is to resize the cell heights, make sure this is done.
    Hope this helps
    Riz

  • Need help serializing an AbstractTableModel for a JTable with cell editing.

    Fun times are ahead. Here we go!
    I have a JTable that contains data I'd like to serialize out to a file to be restored and viewed later.
    So I tried saving the AbstractTableModel subclass out to a file. Whenever I do this, I get the following error message:
    java.io.NotSerializableException: javax.swing.JTable$CellEditorRemover
    Now I know for fact that serializing an AbstractTableModel that was installed in a JTable without cell editing works just fine (my old code did exactly that). As a result, I think that the code that handles events in the AbstractTableModel contains references back out to the JTable, which causes the JTable to be saved no matter what (even though I'm just interested in saving the TableModel only). It causes a bigger file than normal, but file size is not an issue. The only issue I have is that CellEditorRemover (an undocumented inner class of JTable), which is automatically installed for JTables with editable cells, is not serializable.
    This leads to the following questions:
    1. Is there a way to avoid serialization/deserialization of the CellEditorRemover inner class of JTable?
    2. Is there a way to save an AbstractTableModel without saving all of the event listeners associated with it?
    I think an answer to either of these questions would go a long way towards solving my problem. Otherwise, I'll resign myself to weeping silently in the corner of my office.
    Thanks!

    I would suggest that if you can you only save the
    data... but i would do this by using the
    externalizable interface.
    What you will need to do is have the
    writeExternal(ObjectOutputStream out) and
    readExternal(ObjectOutputStream out) methods in your
    class. These will be responsiable for saving the
    data.
    Here's an example of what you can do in these
    methods... this is just a little tidbit from a program
    i've written.public void writeExternal(ObjectOutput out) throws
    IOException {
              out.writeInt(size);
              out.writeObject(drawName);
              out.writeInt(playersLength);
    for(int i = 0; i < playersLength; i++)
    ) out.writeObject(players);
              out.writeInt(seedsLength);
    for(int i = 0; i < seedsLength; i++)
    ) out.writeObject(seeds[i]);
              out.writeInt(drawLength);
    for(int i = 0; i < drawLength; i++)
    ) out.writeObject(draw[i]);
    public void readExternal(ObjectInput in) throws
    IOException, ClassNotFoundException {
              size = in.readInt();
              drawName = (String)in.readObject();
              playersLength = in.readInt();
    for(int i = 0; i < playersLength; i++) players[i] =
    = (String)in.readObject();
              seedsLength = in.readInt();
    for(int i = 0; i < seedsLength; i++) seeds[i] =
    = (String)in.readObject();
              drawLength = in.readInt();
    for(int i = 0; i < drawLength; i++) draw[i] =
    = (String)in.readObject();
    You can now use your class as you would a Serializable
    class, but it will only save the data
    Hope this helped
    webaf409java
    I forgot to add some critical information in my original post. My apologies. :(
    I've thought about using Externalizable, but am hesitant to use it because the application would no longer be able to read in files using the old save format (ie, AbstractTableModels for JTables without CellEditorRemovers ).  I want to preserve the ability to read the old saved AbstractTableModel formats if possible. 
    Do you know of a way to revert to the default deserialization mechanism from readExternal?  This way, during deserialization, I could do a quick test on the object being read and have the ability to default to the regular deserialization mechanism if the object is of the old type or continue with the new Externalizable stuff if the object is one of the new type.  Maintaining file compatibility is key.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Maybe you are looking for

  • Report data binding error

    I have created a banded report split into departments. Each recore has a value associated with it. The report runs fine if I dont try to sub-total each departments vale, but if I add a calculated field to the banding, I get the following error: Repor

  • How to use a usb with bootcamp on a computer with a cd drive

    I have a macbook pro late 2011 and I want to install windows on it. I dont have any cds or dvds that I can burn and I want to be able to use a usb instead. I found another post which lets me make a bootable windows 8 usb but when I try to install it

  • HP OJ Pro 8600-N911a, W-7 USB, lost natural Scan and Ink Level displays and/or capabilities

    HP Officejet Pro 8600 e-All-in-One Printer - N911a printer connection = USB (no wireless) operating system = Windows 7 64 bit Windows 7 64-bit OS laptop computer = HP Pavilion DV7-6187CL no recent hardware/software changes by me that I am aware of »H

  • Files are on an external drive and Itunes not finding them...

    not sure why, as the files have been on this drive for a few years. How can I point Itunes to the extnernal? And as importantly: how can I restore my playlists and itunes data? A "Previous itunes librarty" folder exists on the external, and I have an

  • Move schema to a diff.tablespace

    Dear all, How can I move a particular shcema objects or the complete schema from his default tablespace to other tablespace ? Kai