Problem with JTable with JCheckBox as Header

Hi,
We have a JCheckBox as JTable Header. And respective data in that column also check boxes. For data check boxes, just i am sending Boolean object to object[][] data array. I am getting check Boxes as data components.
For Header, i have create a TableRender object which is returning JCheckBox.
Here my problem is,
1) When i select a Header check box, all the check boxes are getting selected.
2) Now we can reselect an data Check Box. When i reselect any data checkBox, Header CheckBox should be reselected. This is not happening. I was tried lot. Can any body give a solution to solve this problem.
Please .... Please ...
Thanks
Mohan

just call this method with null param on the JTable
table.setTableHeader(null);
cheers
krishna

Similar Messages

  • Problem sorting JTable with custom cell editor

    Greetings,
    I have created a JTable with a JComboBox as the cell editor for the first column. However, I couldn't simply set the default cell editor for the column to be a JComboBox, since the values within the list were different for each row. So instead, I implemented a custom cell editor that is basically just a hashtable of cell editors that allows you to have a different editor for each row in the table (based on the ideas in the EachRowEditor I've seen in some FAQs - see the code below). I also used a custom table model that is essentially like the JDBCAdapter in the Java examples that populates the table with a query to a database.
    The problem comes when I try to sort the table using the TableSorter and TableMap classes recommended in the Java Tutorials on JTables. All of the static (uneditable) columns in the JTable sort fine, but the custom cell editor column doesn't sort at all. I think that the problem is that the hashtable storing the cell editors never gets re-ordered, but I can't see a simple way to do that (how to know the old row index verses the new row index after a sort). I think that I could implement this manually, if I knew the old/new indexes...
    Here's the code I use to create the JTable:
    // Create the Table Model
    modelCRM = new ContactTableModel();
    // Create the Table Sorter
    sorterCRM = new TableSorter(modelCRM);
    // Create the table
    tblCRM = new JTable(sorterCRM);
    // Add the event listener for the sorter
    sorterCRM.addMouseListenerToHeaderInTable(tblCRM);
    Then, I populate the column for the custom cell editor like this:
    // Add the combo box for editing company
    TableColumn matchColumn = getTable().getColumn("Match");
    RowCellEditor rowEditor = new RowCellEditor();
    // loop through and build the combobox for each row
    for (int i = 0; i < getTable().getRowCount(); i++) {
    JComboBox cb = new JComboBox();
    cb.addItem("New");
    //... code to populate the combo box (removed for clarity)
    rowEditor.add(i,new DefaultCellEditor(cb, i))); //TF
    } // end for
    matchColumn.setCellEditor(rowEditor);
    Any ideas how to do this, or is there a better way to either sort the JTable or use a combobox with different values for each row? Please let me know if more code would help make this clearer...
    Thanks,
    Ted
    import java.util.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class RowCellEditor implements TableCellEditor
    protected Hashtable editors;
    protected TableCellEditor editor, defaultEditor;
    public RowCellEditor()
    editors = new Hashtable();
    defaultEditor = new DefaultCellEditor(new JTextField());
    public void add(int row, TableCellEditor editor)
    editors.put(new Integer(row), editor);
    public Component getTableCellEditorComponent(JTable table,
    Object value,
    boolean isSelected,
    int row,
    int column)
    editor = (TableCellEditor) editors.get(new Integer(row));
    if (editor == null)
    editor = defaultEditor;
    return editor.getTableCellEditorComponent(table,
    value,
    isSelected,
    row,
    column);
    public Object getCellEditorValue() {
    return editor.getCellEditorValue();
    public boolean stopCellEditing() {
    return editor.stopCellEditing();
    public void cancelCellEditing() {
    editor.cancelCellEditing();
    public boolean isCellEditable(EventObject anEvent) {
    return true; //TF
    //return editor.isCellEditable(anEvent);
    public void addCellEditorListener(CellEditorListener l) {
    editor.addCellEditorListener(l);
    public void removeCellEditorListener(CellEditorListener l) {
    editor.removeCellEditorListener(l);
    public boolean shouldSelectCell(EventObject anEvent) {
    return editor.shouldSelectCell(anEvent);
    -------------------

    Well, I found a solution in another post
    (see http://forum.java.sun.com/thread.jsp?forum=57&thread=175984&message=953833#955064 for more details).
    Basically, I use the table sorter to translate the row index for the hashtable of my custom cell editors. I did this by adding this method to the sorter:
    // This method is used to get the correct row for the custom cell
    // editor (after the table has been sorted)
    public int translateRow(int sortedRowIndex)
    checkModel();
    return indexes[sortedRowIndex];
    } // end translateRow()
    Then, when I create the custom cell editor, I pass in a reference to the sorter so that when the getTableCellEditorComponent() method is called I can translate the row to the newly sorted row before returning the editor from the hashtable.

  • Problem in JTable with a JComboBox cell editor

    Hi gurus,
    Please help! I am having a problem with a JTable that has a JComboBox cell editor. When the table is first loaded, the combo box column displays correct data. But whenever I click the combo box, the selection will be set to the first item in the combo box list once the popup menu pops up even before I make any new selection. It is very annoying.
    Here is how I set the cell editor:
    populateComboBoxModel(); // populate the combo box model.
    DefaultCellEditor cell_editor = new DefaultCellEditor(new JComboBox(
    combo_model));
    contrib_table.getColumnModel().getColumn(1).setCellEditor(
    cell_editor);
    I didn't set the cell renderer so I assume it is using the default cell renderer.
    Thanks !

    Not quite. The example doesn't have a different cell editor for each row of the table. I'm sure I must be missing something, bc I've found many references to the fact that this is possible to do. And I have most of it working. However, when I click on any given combobox, it automatically switches to the first value in the list, not the selected item. I've tried setting the selected item all over the code, but it has no effect on this behavior. Also, it only happens the first time I select a given cell. For example, suppose the first row has items A, B, and C, with B being the selected value. The table initially displays with B in this cell, but when I click on B, it switches to A when it brings up the list. If I select B, and move on to some other cell, and then go back and click on B again, it doesn't switch to A.
    There seems to be a disconnect between the values that I display initially, and the values that I set as selected in the comboboxes. Either that, or it behaves as though I never set the selected item for the combobox at all.
    Any help would be greatly appreciated.

  • JTable with a JCheckBox in a header column

    Hi everybody,
    I have implemented a JTable with a JCheckbox in one of the header columns. For this I have used the following code from the Internet for rendering the table cell:
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent;
         protected int column;
         protected boolean mousePressed = false;
         public CheckBoxColumnHeader(ItemListener itemListener) {   
              rendererComponent = this;
              rendererComponent.addItemListener(itemListener);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              if (table != null) {     
                   JTableHeader header = (ExtendedJTableHeader)table.getTableHeader();
                   if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());
                        rendererComponent.setBackground(header.getBackground());
                        rendererComponent.setFont(header.getFont());
                        header.addMouseListener(rendererComponent);
              setColumn(column);
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));
              return rendererComponent;
    From a technical point of view, the checkbox works as expected. However, I have problems with the graphical layout of the checkbox in the header column:
    1) The checkbox seems to be bigger than the height of the header column. It overlays the border lines of the table. When I increase the preferred size of the header row, the checkbox also increases its size and still overlays the table border lines.
    2) The checkbox has a diffferent background shading than the other columns in the header.
    Any help for solving these two layout problems are greatly appreciated.
    Thanks, Walter

    Hi,
    here is now the complete code
    package main;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Arrays;
    import java.util.Vector;
    import javax.swing.table.*;
    * <p>�berschrift: </p>
    * <p>Beschreibung: </p>
    * <p>Copyright: Copyright (c) 2007</p>
    * <p>Organisation: </p>
    * @author unbekannt
    * @version 1.0
    public class MainFrame extends JFrame {
         JTable table3;
         JScrollPane scp3; 
      //Den Frame konstruieren
      public MainFrame() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Initialisierung der Komponenten
      private void jbInit() throws Exception  {
        this.setSize(new Dimension(500, 320));
        this.setTitle("Action List");
        Vector<Object> rowData = new Vector<Object>();
        for (int i=0; i<3; i++) {
             Vector<Object> colData = new Vector<Object>(Arrays.asList("Data R" + i + "C0", "Data R" + i + "C1", "Data R" + i +"C2", (i%2 == 0) ? Boolean.TRUE : Boolean.FALSE));
             rowData.add(colData);
        Vector<Object> hdr = new Vector<Object>(Arrays.asList("Column 0", "Column 1", "Column 2 (MyO)", "Column 3"));
         DefaultTableModel tableM = new DefaultTableModel(rowData, hdr);
        table3 = new JTable(tableM);
        TableColumn tc = table3.getColumnModel().getColumn(3);   
        tc.setCellEditor(table3.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(table3.getDefaultRenderer(Boolean.class));
        tc.setHeaderRenderer(new CheckBoxColumnHeader(table3, new MyItemListener()));
        scp3 = new JScrollPane(table3);
         scp3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scp3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
         this.add(scp3);
      //�berschrieben, so dass eine Beendigung beim Schlie�en des Fensters m�glich ist
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
    public class CheckBoxColumnHeader extends JCheckBox implements TableCellRenderer, MouseListener {
         protected CheckBoxColumnHeader rendererComponent; 
         protected int column; 
         protected boolean mousePressed = false; 
         protected JTable myTable;
         public CheckBoxColumnHeader(JTable t, ItemListener itemListener) {   
              rendererComponent = this;   
              rendererComponent.addItemListener(itemListener);
              myTable = t;
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              JTableHeader header = null;
              if (table != null) {     
                   header = (JTableHeader)table.getTableHeader();     
                    if (header != null) {       
                        rendererComponent.setForeground(header.getForeground());       
                        rendererComponent.setBackground(header.getBackground());       
                        rendererComponent.setFont(header.getFont());       
                        header.addMouseListener(rendererComponent); 
              setColumn(column);   
              rendererComponent.setText(value.toString());
              setBorder(UIManager.getBorder("TableHeader.cellBorder"));   
              return rendererComponent; 
         protected void setColumn(int column) {this.column = column; } 
         public int getColumn() {return column; }
         protected void handleClickEvent(MouseEvent e) {
              if (mousePressed) {
                   mousePressed=false;     
                   JTableHeader header = (JTableHeader)(e.getSource());
                   JTable tableView = header.getTable();
                   TableColumnModel columnModel = tableView.getColumnModel();
                   int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                   int column = tableView.convertColumnIndexToModel(viewColumn);
                   if (viewColumn == this.column && e.getClickCount() == 1 && column != -1) {
                        doClick();
         public void mouseClicked(MouseEvent e) {   
              handleClickEvent(e);   
              ((JTableHeader)e.getSource()).repaint(); 
         public void mousePressed(MouseEvent e) {   
              mousePressed = true; 
         public void mouseReleased(MouseEvent e) {  }
         public void mouseEntered(MouseEvent e) {  }
         public void mouseExited(MouseEvent e) {  }
         public JTable getTable() {return myTable; }
    public class MyItemListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
             CheckBoxColumnHeader source = (CheckBoxColumnHeader)e.getSource();
             if (source instanceof AbstractButton == false) return;
             boolean checked = e.getStateChange() == ItemEvent.SELECTED;
             for (int x = 0, y = source.getTable().getRowCount(); x < y; x++) {
                  source.getTable().setValueAt(new Boolean(checked),x,3);     
    As originally said, the checkbox in the header column overlays the table borders and also has a different background shading than the other header columns.

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

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

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

  • Flipping problems with JTables

    I have a JTable (with scroll bar ) and a JButton inside a Jframe.
    When I push the JButton another JFrame appears with another JTable inside.
    The problem is that when I close the upper JFrame and I try to move the scroll bar of the JTable inside the father JFrame it starts to flip doing an horrible effect for the general lauyout.The solution it could be overwrite the paint method....but actually for my Java knowledges is impossibe. Help !

    Sorry I mean flashing problems (not flipping.)
    The code is:
    JPanel p1=new JPanel();
    Label lab1=new Label(" LABORATORIO ANALISI CLINICHE");
    Label lab2=new Label(" Dr.ssa xxxxxxxxxxxx ");
         Label lab3=new Label(" C/o xxxxxxxxxxxxx ");
         Label lab4=new Label(" Via xxxxxxxxxxx nr 5/7");
         Label lab5=new Label(" 86100 xxxxxxxxxx");
    Label lab6=new Label(" tel. xxxxxxxxxx");
         p1.setLayout(new GridLayout(6,1));
    p1.add(lab1);
    p1.add(lab2);
    p1.add(lab3);
    p1.add(lab4);
    p1.add(lab5);
    p1.add(lab6);
    Report myReport=new Report(tableModels[p.getSelectedIndex()],"Printer Manager",p1);
    Actually Report is a class that prepare a JFrame with a JPanel and inside the JPanel there is a JScrollPane that get the JTable.That's the code for the Report class:
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    public class Report extends Frame implements Printable
    JFrame frame;
    JTable tableView;
    JComponent component_dummy;
    public Report(AbstractTableModel tableModel,String title,JComponent component)
    super(title);
    this.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { dispose(); } } );
    final String[] headers = {"Description", "open price",
         "latest price", "End Date", "Quantity"};
    final Object[][] data = {
    {"Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
    {"Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
    {"legal pad", "1.00", "2.49", new Date(), new Integer(1)},
    {"tape", "1.00", "1.49", new Date(), new Integer(1)},
    {"stapler", "4.00", "4.49", new Date(), new Integer(1)},
    {"legal pad", "1.00", "2.29", new Date(), new Integer(5)}
    TableModel dataModel = new AbstractTableModel() {
    public int getColumnCount() { return headers.length; }
    public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {
         return data[row][col];}
    public String getColumnName(int column) {
         return headers[column];}
    public Class getColumnClass(int col) {
    return getValueAt(0,col).getClass();}
    public boolean isCellEditable(int row, int col) {
    return (col==1);}
    public void setValueAt(Object aValue, int row, int column) {
    data[row][column] = aValue;
    dataModel=tableModel;
    tableView = new JTable(dataModel);
    // component_dummy= new JComponent();
    component_dummy=component;
    JScrollPane scrollpane = new JScrollPane(tableView);
    scrollpane.setPreferredSize(new Dimension(600,300));
    this.setLayout(new BorderLayout());
    this.add(BorderLayout.NORTH,component);
    this.add(BorderLayout.CENTER,scrollpane);
    JButton printButton= new JButton();
    printButton.setText("Stampa");
    //this.getContentPane().add(BorderLayout.SOUTH,printButton);
    this.add(BorderLayout.SOUTH,printButton);
    // for faster printing turn double buffering off
    RepaintManager.currentManager(
         frame).setDoubleBufferingEnabled(false);
    printButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    PrinterJob pj=PrinterJob.getPrinterJob();
    pj.setPrintable(Report.this);
    pj.printDialog();
    try{
    pj.print();
    }catch (Exception PrintException) {}
    this.setVisible(true);
    this.pack();
    public int print(Graphics g, PageFormat pageFormat,
    int pageIndex) throws PrinterException
         Graphics2D g2 = (Graphics2D) g;
         g2.setColor(Color.black);
         int fontHeight=g2.getFontMetrics().getHeight();
         int fontDesent=g2.getFontMetrics().getDescent();
         //leave room for page number
         double pageHeight = pageFormat.getImageableHeight()-fontHeight;
         double pageWidth = pageFormat.getImageableWidth();
         double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
         double scale = 1;
         if (tableWidth >= pageWidth)
              scale = pageWidth / (tableWidth+(int)(pageWidth/2-pageWidth*0.43));
         double headerHeightOnPage=
    tableView.getTableHeader().getHeight()*scale;
         double tableWidthOnPage=tableWidth*scale;
         double oneRowHeight=(tableView.getRowHeight()+
    tableView.getRowMargin())*scale;
         int numRowsOnAPage=
    (int)((pageHeight-headerHeightOnPage)/oneRowHeight);
         double pageHeightForTable=oneRowHeight*numRowsOnAPage;
         int totalNumPages= (int)Math.ceil((
    (double)tableView.getRowCount())/numRowsOnAPage);
         if(pageIndex>=totalNumPages)
    return NO_SUCH_PAGE;
    g2.translate(0f,0f);
         g2.drawString("Laboratorio analisi Cliniche",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.86));
    g2.drawString("Dr.ssa xxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.82));
    g2.drawString("C/o xxxxxxxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.78));
    g2.drawString("Via xxxxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.74));
    g2.drawString("86100 xxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.70));
    g2.drawString("tel. 0874/316147-91720",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.66));
    //      g2.translate(0f,headerHeightOnPage);
         g2.translate((int)(pageWidth/2-pageWidth*0.33),-pageIndex*pageHeightForTable+(pageHeight+fontHeight-fontDesent-pageHeight*0.56));
         //If this piece of the table is smaller than the size available,
         //clip to the appropriate bounds.
         if (pageIndex + 1 == totalNumPages)
    int lastRowPrinted = numRowsOnAPage * pageIndex;
    int numRowsLeft = tableView.getRowCount() - lastRowPrinted;
    g2.setClip(0,(int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(oneRowHeight * numRowsLeft));
         //else clip to the entire area available.
         else
    g2.setClip(0, (int)(pageHeightForTable*pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(pageHeightForTable));
         g2.scale(scale,scale);
         tableView.paint(g2);
    g2.scale(1/scale,1/scale);
         g2.translate(0,pageIndex*pageHeightForTable);
         g2.translate(0, -headerHeightOnPage);
         g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage),
    (int)Math.ceil(headerHeightOnPage));
         g2.scale(scale,scale);
         tableView.getTableHeader().paint(g2); //paint header at top
         return Printable.PAGE_EXISTS;
    public static void main(String[] args)
    do you think that there are problems because the print method ? or mayby because I clipped the graphics area ?

  • Problem with JTable checkbox

    In my table I have a column of checkboxes. If user clicks any checkbox, the program will first check for some condition and pop out a warning dialog saying that "the action will change the current mode. are you sure you want to continue?". If user select "yes", some action are taken and the checkbox should be selected. Now the problem is that after user select "yes", the checkbox is not selected. (Same as when you press your mouse at a checkbox and then drag it out the checkbox cell, the actions are taken but the checkbox is not selected.)
    The code for the cell editor is as follows:
    public Component getTableCellEditorComponent(JTable table, Object value,
               boolean isSelected, int row, int column) {
             if (value instanceof ComboString) { // ComboString
               flg = COMBO;
               String str = (value == null) ? "" : value.toString();
               System.out.println("+++++++ " + row+" : "+column+"  flg: "+flg);
               return cellEditors[COMBO].getTableCellEditorComponent(table, str,
                   isSelected, row, column);
             else if (value instanceof Boolean) {                    
               flg = BOOLEAN;
               Boolean check = Boolean.getBoolean(value.toString());
                          // promptContinue returns true for continue, false for return; inside it a dialog box is popped for user selection "continue or not"
                          if(!promptContinue()){
                                return null;
               return cellEditors[BOOLEAN].getTableCellEditorComponent(table,
                   value, isSelected, row, column);
             

    Thanks. But my problem is not with stopping the editor, but with continuing the editor. Following is the code of getCellEditorValue()
    public Object getCellEditorValue() {
             switch (flg) {
             case COMBO:
               String str = (String) comboBox.getSelectedItem();
               return new ComboString(str);
             case BOOLEAN:
             case STRING:
               return cellEditors[flg].getCellEditorValue();
             default:
               return null;
                }I am not very sure whether it is the problem of cell editor or cell renderer, because it seems the code for continue condition is actually executed which is supposed to make the checkbox checked, but the result turns to be that the checkbox is not checked.

  • Any body please can solve my problem that iam facing with JTable

    Dear sir,
    Iam doing an educational product using Swing as front end in that
    iam using JTables. And back end iam using sqlserver. With jtable iam
    facing very serious problem the problem is actually iam entering the values
    in all the columns after that iam pressing the save button its not
    saving but if i click on any of the columns and try to save its saving.
    please anybody can solve my problem.Please if a piece of code is there ill
    be very thankful to you. my mailid is [email protected]
    regards
    surya

    The problem is, the cellEditor does not know that editing has stopped and therefore has not updated the model (where the data actually resides). When you click off the cell to another cell, the first cell knows it must be done editing because you are leaving it. If you click a button (or anything other than another cell), the cell being edited has no knowledge of this. You need to call stopCellEditing() on the cell editor and your problem will be solved. To do this, put the following method into your code and call it when you click the button to clear, save or whatever you need to do.
    public void ceaseEditing() {    int row = this.getEditingRow();
      int col = this.getEditingColumn();
      if (row != -1 && col != -1)
        this.getCellEditor(row,col).stopCellEditing(); 
      }Hope this helped...

  • Print JTable with multi line header

    I need to print a JTable with multi line header, I want to know if I can use the method jTable.print(int, MessajeFormat, MessageFormat) by manipulation of the MessageFormat. How I can manipulate it?
    Otherwise, How I can print this?

    hi again,
    To print pdf in a swing application you don't need servlet.jar.
    You'll only need itext.jar and a printer connected to your pc.
    Download the iText source code and unzip it. See the following classes:
    com.lowagie.tools.LPR and com.lowagie.tools.BuildTutorial. This latter is the main class of a swing tool that you can run.
    Silent Print:
    You have only to embed this javascript code in your pdf:
    writer.addJavaScript("this.print(false);", false);
                        document.add(new Chunk("Silent Auto Print"));Then, you have to send the document to the printer.
    Google : java print pdf
    http://forum.java.sun.com/thread.jspa?threadID=523898 or
    http://www.exampledepot.com/egs/javax.print/pkg.html for printing task.
    Under unix system, I used this:
                           String PRINTER = ...;
                   try {
                        String cmd = "lp -d " + PRINTER + " " + PDF_PATH;
                        Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd });
                   } catch (Exception e) {
                                 //handle the exception
                                 e.printStackTrace();
                   }hth

  • Print Jtable with multiline header?

    i want to print jtable with multi-lines header and footer
    using the print function that takes MessageFormat as header and footer
    i used MessageFormat header = new MessageFormat("hello\r\nworld");and i used '\n' only
    but it was printed all in the same line
    thnx in advance

    You can try something on the below lines. Set your custom renderer for the tableheader.
    public class MultiLineHeaderRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value,
                             boolean isSelected, boolean hasFocus, int row, int column) {
                         JLabel label = (JLabel) super.getTableCellRendererComponent( table,  value,
                              isSelected,  hasFocus,  row,  column);
                        label.setText("<html>a<br>b</html>");
                        return label;
        }Not the best way to do it. And might need to some modifications too to set the font position etc.

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

  • Problems with JTable

    Hi All,
    I am facing some problems in JTable :
    1) How to remove all lines between cells, neither i should have column nor row lines....there should not be any lines between any cell at all.
    2) If i select a perticular cell, complete row is getting selected with a blue background, that should not happen at all.....row should not get select....
    3) How to make a cell non editable.
    Regards,
    Ravi

    1) Read the API. Check out the set??? methods until you fine what you want
    2) Read the API. Check out the methods that deal with row and column selection
    3) Override isCellEditable(...) method of JTable or DefaultTableModel

  • Another problem with JTable

    Hi,
    I have encountered a problem with JTable, i am trying to display some 15 columns and their values , one of the columns value is null, then the JTable is not displaying its value from this column(which is with null value) onwards.
    Can anybody assiss me in this matter.
    Regards
    khiz_eng

    I don't know If I can fix your problem, but
    I know just that it works on my PC.... It's very very
    slow... I don't know how to insert PageSetUp option... I have to study the problem.....
    However I don't think it's a hard problem....
    I want ask to you if you have found some problems when you are in Editing mode in a cell.....
    in the jdk1.2 version I could save while was in editing mode using the editingStopped method.
    It permit to update all data .... also the data in the cell I was editing.
    in the jdk 1.3 if I use this method It doesn't work properly... It maybe destroy the content object in the Cell..... because I'm able to print all the table except the editing cell (it throw an exception...)
    What's changed????
    I don't know...
    Can u help me?

Maybe you are looking for

  • Security threat detected by my cable operator but I can't find it

    I received the following email from Cogeco this morning and they are going to shut me down soon if I can't deal with it. From my research at McAffee and Symantec it appears to something that only Windows users would get. I am confused. How can I dete

  • I subscribed but I cannot convert my files to Word

    I need help getting started.  I would like to convert a PDF file to Word and I subscribed but I an unable to proceed.  Please help and thanks

  • Reg:maps in obiee

    hi, can any body guide me how can i put a map in the obiee dashboard ie by clicking a region in the map,should show all details of the region.what are the steps to be followed to achieve this? thanks

  • Oil and Gas Business process overview

    Hello experts, I am a SAP BW consultant, I am very much interested to know the business process flow in the Oil and Gas company so that i can explore before entering into the project. Hope you experts will help me out with some Good Stuff which give

  • Does Firefox have a security alert popup or is this a disguised ad for a vendor's security software?

    My McAfee software full scan shows no viruses, yet I got a popup in Firefox with the title "Firefox security alert." The popup said my computer has 97 infected objects. The list includes 5 viruses, including one Trojan. There is a Start Protection bu