Custom table cell

hi
in my project i created some custom-table-cell (classes) manually without interface builder.
now my question is; is it possible to create custom-table-cells with interface builder for dynamicly create instances?
i would like to have a nib file where a customtablecell is placed and defined which i can later create instances from.
i have no idea how i can do this.
thanks.

Make a XIB where the File's owner is a UIViewController and the only other thing in it is your custom table cell and it is hooked up to the file's owner as the view. Then you can do:
UIViewController* c = [[UIViewController alloc] initWithNibName:@"CustomCell" bundle:nil];
cell = (CustomCell *)c.view;

Similar Messages

  • Adding button to a custom table cell (and handling them)

    Hi
    I'm wondering if it's possible to add a button on each row of a table view using a custom table cell view. If it's possible, I'm really wondering how I can handle the click events on these buttons.
    Thanks

    No.
    Try creating a view and adding it to a cell. Let us know what problems you have, and we can try to help.

  • Small issue with custom table cell editor and unwanted table row selection

    I'm using a custom table cell editor to display a JTree. Thing i notice is that when i select a value in the tree pop-up, the pop-up closes (as it should) but then every table row, from the editing row to the row behind the pop-up when i selected the value becomes highlighted. I'm thinking this is a focus issue, but it thought i took care of that. To clairfy, look at this: Before . Notice how the "Straightening" tree item is roughly above the "Stock Thickness" table row? When i select Straightening, this is what happens to my table: After .
    My TreeComboBox component:
    public class TreeComboBox extends JPanel implements MouseListener {
        private JTextField itemField;
        private TreeModel treeModel;
        private ArrayList<ActionListener> actionListeners = new ArrayList<ActionListener>();
        private Object selectedItem;
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
        public TreeComboBox(TreeModel treeModel) {
            this(treeModel, null);
         * Creates a new <code>TreeComboBox</code> instance.
         * @param treeModel the tree model to be used in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public TreeComboBox(TreeModel treeModel, Object selectedItem) {
            this.treeModel = treeModel;
            this.selectedItem = selectedItem;
            initComponents();
         * Returns the current drop-down tree model.
         * @return the current <code>TreeModel</code> instance.
        public TreeModel getTreeModel() {
            return treeModel;
         * Sets the tree model.
         * @param treeModel a <code>TreeModel</code> instance.
        public void setTreeModel(TreeModel treeModel) {
            this.treeModel = treeModel;
         * Returns the selected item from the drop-down selector.
         * @return the selected tree object.
        public Object getSelectedItem() {
            return selectedItem;
         * Sets the selected item in the drop-down selector.
         * @param selectedItem tree will expand and highlight this item.
        public void setSelectedItem(Object selectedItem) {
            this.selectedItem = selectedItem;
            String text = selectedItem != null ? selectedItem.toString() : "";
            itemField.setText(text);
            setToolTipText(text);
         * Overridden to enable/disable all child components.
         * @param enabled flat to enable or disable this component.
        public void setEnabled(boolean enabled) {
            itemField.setEnabled(enabled);
            super.setEnabled(enabled);
        public void addActionListener(ActionListener listener) {
            actionListeners.add(listener);
        public void removeActionListener(ActionListener listener) {
            actionListeners.remove(listener);
        // MouseListener implementation
        public void mouseClicked(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
            showPopup();
        private void initComponents() {
            setLayout(new GridBagLayout());
            itemField = new JTextField();
            itemField.setEditable(false);
            itemField.setText(selectedItem != null ? selectedItem.toString() : "");
            itemField.addMouseListener(this);
            add(itemField, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
        private void showPopup() {
            final TreePopup popup = new TreePopup();
            final TreeComboBox tcb = this;
            final int x = itemField.getX();
            final int y = itemField.getY() + itemField.getHeight();
            int width = itemField.getWidth() + popupButton.getWidth();
            Dimension prefSize = popup.getPreferredSize();
            prefSize.width = width;
            popup.setPreferredSize(prefSize);
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    popup.show(tcb, x, y);
                    popup.requestFocusInWindow();
        private void fireActionPerformed() {
            ActionEvent e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "TreeComboBoxSelection");
            for (ActionListener listener : actionListeners) {
                listener.actionPerformed(e);
        private class TreePopup extends JPopupMenu {
            private JTree tree;
            private JScrollPane scrollPane;
            public TreePopup() {
                initComponents();
                initData();
            private void initData() {
                if (treeModel != null) {
                    tree.setModel(treeModel);
            private void initComponents() {
                setFocusable(true);
                setFocusCycleRoot(true);
                tree = new JTree();
                tree.setRootVisible(false);
                tree.setShowsRootHandles(true);
                tree.setFocusable(true);
                tree.setFocusCycleRoot(true);
                tree.addTreeSelectionListener(new TreeSelectionListener() {
                    public void valueChanged(TreeSelectionEvent e) {
                        tree_valueChanged(e);
                scrollPane = new JScrollPane(tree);
                add(scrollPane);
            private void tree_valueChanged(TreeSelectionEvent e) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                setSelectedItem(node.getUserObject());
                fireActionPerformed();
                this.setVisible(false);
    }My TreeComboBoxTableCellEditor:
    public class TreeComboBoxTableCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
        protected TreeComboBox treeComboBox;
        protected ArrayList<CellEditorListener> cellEditorListeners = new ArrayList<CellEditorListener>();
        public TreeComboBoxTableCellEditor(TreeComboBox treeComboBox) {
            this.treeComboBox = treeComboBox;
            treeComboBox.addActionListener(this);
        public Object getCellEditorValue() {
            return treeComboBox.getSelectedItem();
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            treeComboBox.setSelectedItem(value);
            return treeComboBox;
        public void actionPerformed(ActionEvent e) {
            stopCellEditing();
    }Any thoughts?
    Edited by: MiseryMachine on Apr 3, 2008 1:21 PM
    Edited by: MiseryMachine on Apr 3, 2008 1:27 PM

    As I said, you have to have empty context elements before additional rows will be open for input.
    For instance if you want to start with 5 rows available for input do the following to your internal table that you will bind:
    data itab type standard table of sflight.
    do 5 times.
      append initial line to itab.
    enddo.
    context_node->bind_table( itab ).
    The other option if you need n number of rows is to add a button to the table toolbar for adding more rows. When this button is pressed, you add a new context element to the node - thereby creating a new empty row in the table.

  • How do you do custom table cell in IB?

    I want to avoid writing those custom table cells because its really a hassle. I see that in IB there are all the controls I need to make the cell (label, sliders etc) and there is even a table view, but I just cant figure out how to create that cell with all the controls in it and attach that cell to a tableview. They dont seem to integrate well in IB at all! Any one with any ideas?

    I'm a car dealer and I created the bill of sale for my dealership in a Numbers spread sheet. I want to be able to use my iPad mini w retina for customers to sign directly on my iPad then print out the BoS with signatures on it so I can make transactions easier for my customers in case I have to meet them somewhere instead of my office. Then I would have the ability to send them another copy if they happen to lose theirs without digging thru my files to find the hard copy and scan and send it to them.
    Thanks

  • Customized table cell renderer doesn't work after table data model changed

    Hi:
    I have a jtable with a custimized table cell render (changes the row color). Everything works fine while the data model is unchanged. I can change the row color, etc. However, after I delete one row or any number of rows in the table, the data model is updated and the custmized table cell renderer is not being called anymore while jtable is rendering on its cells. Seems like the table cell render is no long associated with the jtable. Is this a known problem? Any help would be appreciated.
    Thanks

    I am having the same problem. Has anybody solved this issue?
    Thanks

  • Custom table cell renderer in a JTable is not called

    Hello, all,
    I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.
    My code snippents are as follows:
    //Declare the table and add custom cell renderer
    JTable table = new JTable (7,7);
    table.setCellSelectionEnabled (true);
    table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    //Add the custom cell renderer to render objects of type Item
    table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());
    //Get the selected cells and change the object type in those cells
    //This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
    int rowIndexStart = table.getSelectedRow();
    int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
    int colIndex = table.getSelectedColumn();
    Item item = new Item ();
    for (int i = rowIndexStart; i<=rowIndexEnd; i++){
                  table.setValueAt(item, i, colIndex);
                 //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
    //Definition of custom cell renderer. 
    //the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?
    class CustomTableCellRenderer extends DefaultTableCellRenderer  {
        public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
            System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
            if (this.isFocusOwner()) {
            cell.setBackground( Color.red );
            cell.setForeground( Color.white );
            return cell;
    } Please, help,
    Thank you!
    Elana

    The suggestion given above assumes that all the data in a given column is of the same type.
    If you have different types of data in different rows the you should be overriding the getCellRenderer(...) method. Something like:
    public TableCellRenderer getCellRenderer(int row, int column)
        Object o = getValueAt(row, column);
        if (o instanceof Item)
            return yourCustomRenderer
        else
            return super.getCellRenderer(row, column);
    }

  • Custom Table Cell Renderer Unable To Set Horizontal Alignment

    Hello,
    I have a problem that I'm at my wit's end with, and I was hoping for some help.
    I need to render the cells in my table differently (alignment, colors, etc) depending on the row AND the column, not just the column. I've got this working just fine, except for changing the cell's horizontal alignment won't work.
    I have a CustomCellRenderer that extends DefaultTableCellRenderer and overrides the getTableCellRendererComponent() method, setting the foreground/background colors and horizontal alignment of the cell based on the cell's value.
    I have a CustomTable that extends JTable and overrides the getCellRenderer(int row, int column) method to return a private instance of this CustomCellRenderer.
    This works fine for foreground/background colors, but my calls to setHorizontalAlignment() in the getTableCellRendererComponent() seem to have no effect, every cell is always displayed LEFT aligned! It's almost like the cell's alignment is determined by something else than the table.getCellRenderer(row,column).getTableCellRendererComponent() method.
    I've also tried setting the renderer for every existing TableColumn in the TableModel to this custom renderer, as well as overriding the table's getDefaultColumn() method to return this custom renderer as well for any Class parameter, with no success.
    No matter what I've tried, I can customize the cell however I want, EXCEPT for the horizontal alignment!!!
    Any ideas???
    Here's the core custom classes that I'm using:
    class CustomTable extends JTable {
    private CustomRenderer customRenderer = new CustomRenderer();
    public CustomTable() {
    super();
    public TableCellRenderer getCellRenderer(int row, int column) {
    return customRenderer;
    } // end class CustomTable
    class CustomRenderer extends DefaultTableCellRenderer {
    public CustomRenderer() {
    super();
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    if (row % 2 == 0) {
    setForeground(Color.red);
    setHorizontalAlignment(RIGHT);
    } else {
    setForeground(Color.blue);
    setHorizontalAlignment(LEFT);
    return this;
    } // end class CustomRenderer
    Even worse, I've gotten this to work fine in a trivial example I made to try and re-create the problem. But for some reason, this same thing is just not working for horizontal alignment in my actual project?!?
    Anyone have any ideas how the cell's horizontal alignment set in the getTableCellRendererComponent() method is being ignored or overwritten before the cell is being displayed???
    Thanks, any help is appreciated,
    -Alex Blume

    Ok, so I've looked into their source and I think I know where and what the trouble is. The JTable.java has a method called:
    3658> public TableCellRenderer getCellRenderer(int row, int column) {
    3659> TableColumn tableColumn = getColumnModel().getColumn(column);
    3660> TableCellRenderer renderer = tableColumn.getCellRenderer();
    3661> if (renderer == null) {
    3662> renderer = getDefaultRenderer(getColumnClass(column));
    3663> }
    3664> return renderer;
    3665> }
    starting at line 3658 of their source code. It retrieves the TableCellRenderer on line 3660 by calling the tableColumn's getCellRenderer method. This is found in the TableColumn.java class:
    421> public TableCellRenderer getCellRenderer() {
    422> return cellRenderer;
    423> }
    See the problem? Only ONE cell Renderer. It's referring to a variable found at line 140 which is of type TableCellRenderer ... well actually it's created as a DefaultTableCellRenderer at some point since TableCellRenderer is an interface.
    Basically the fix is this:
    In the TableColumn.java file, a collection (Vector, LinkedList, whatever) needs to keep track of each cell's renderer. This will solve the solution. Of course this will be something that you or I can make.
    What's funny is the contradiction in documentation between JTable's and TableColumn's getCellRenderer() method. First, if we look at TableColumn's documentation it states:
    "Returns the TableCellRenderer used by the JTable to draw values for this column."
    Based on that first statement, the getCellRenderer() method in TableColumn is doing its job exactly. No lies, no contradictions in what it does.
    However, that method is called up inside of the JTable's getCellRenderer() method which says a completely different thing which is:
    "Returns an appropriate renderer for the cell specified by this row and column."
    Now we have a problem. For the cell specified. It appears that the rush to push this out blinded some developer who either:
    1) mis-interpreted what the JTable getCellRenderer() method was supposed to do and inadvertently added a feature or;
    2) was in a 2 a.m. blitz, wired on Pepsi and adrenalin and wrote the bug in.
    Either way, I'm really hoping that they'll fix this because it will take care of at least 2 bugs. Btw, anyone interested in posting a subclass to solve this problem (subclass of TableColumn) is more than welcome. I've spent much too much time on this and my project is already behind so I can't really afford any more time on this.
    later,
    a.

  • Serialize Custome Table Cell Colors and Outlines to XML

    I would like to be able to have custom cell shading and outlining available as attribute or properties of the CELL element so I can have it serialized to XML along with the rest of my document.
    Currently, I have some fancy cell shading in my tables. But I export it to XML, then bring it back into FM8 and the fancy shading is lost.
    Or, more realistically, I want to generate the XML from a data source (like a Versant database) to import into FM8, and I cannot perform the cell shading during XML generation.

    I would like to be able to have custom cell shading and outlining available as attribute or properties of the CELL element so I can have it serialized to XML along with the rest of my document.
    Currently, I have some fancy cell shading in my tables. But I export it to XML, then bring it back into FM8 and the fancy shading is lost.
    Or, more realistically, I want to generate the XML from a data source (like a Versant database) to import into FM8, and I cannot perform the cell shading during XML generation.

  • Help with creating a custom table cell editor?

    hi, i was reading up on various tutorials and trying to write codes that pops up a simple calendar when clicked on text of the Date class in a table, so far, i can't seem to get my classes working.. the following is some classes i've written for this task (note, there are alot of commented out lines, those are the modifications done to the tutorial classes in http://java.sun.com/docs/books/tutorial/)
    any help would be appreciated :D
    thanks in advance!
    What i have done so far:
    /** BASIC TABLE CLASS FOR DEMONSTRATION*/
    //import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    public class TableBasic extends JFrame
         public TableBasic()
              String[] columnNames = { "Date", "String", "Integer", "Boolean" };
              Object[][] data =
                   {  { new Date(), "A", new Integer(1), Boolean.TRUE },
                        {new Date(), "B", new Integer(2), Boolean.FALSE },
                        {new Date(), "C", new Integer(9), Boolean.TRUE },
                        {new Date(), "D", new Integer(4), Boolean.FALSE}
              JTable table = new JTable(data, columnNames)
                   //Returning the Class of each column will allow different
                   //renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setDefaultRenderer(Date.class, new CalendarRenderer(true));
              table.setDefaultEditor(Date.class, new CalendarEditor());
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
         public static void main(String[] args)
              TableBasic frame = new TableBasic();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              //frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    * CLASS BASED ON ColorRenderer.java at http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ColorRenderer.java
    import javax.swing.BorderFactory;
    import javax.swing.JLabel;
    import javax.swing.JTable;
    import javax.swing.border.Border;
    import javax.swing.table.TableCellRenderer;
    //import java.awt.Color;
    import java.awt.Component;
    public class CalendarRenderer
         extends JLabel
         implements TableCellRenderer
         Border unselectedBorder = null;
         Border selectedBorder = null;
         boolean isBordered = true;
         public CalendarRenderer(boolean isBordered)
              this.isBordered = isBordered; setOpaque(true);
              //MUST do this for background to show up.
         public Component getTableCellRendererComponent(JTable table,
                                                                     Object color,
                                                                     boolean isSelected,
                                                                     boolean hasFocus,
                                                                     int row,
                                                                     int column)
              String newDate = (String)color;
              setText(newDate);
              if (isBordered)
                   if (isSelected)
                        if (selectedBorder == null)
                             selectedBorder = BorderFactory.createMatteBorder(2,5,2,5, table.getSelectionBackground());
                        setBorder(selectedBorder);
                   else
                        if (unselectedBorder == null)
                             unselectedBorder = BorderFactory.createMatteBorder(2,5,2,5, table.getBackground());
                        setBorder(unselectedBorder);
              //setToolTipText("RGB value: " + newColor.getRed() + ", " + newColor.getGreen() + ", " + newColor.getBlue());
              return this;
    * the editor based on ColorEditor.java at http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ColorEditor.java
    import javax.swing.AbstractCellEditor;
    import javax.swing.table.TableCellEditor;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JDialog;
    import javax.swing.JTable;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class ColorEditor
         extends AbstractCellEditor
         implements TableCellEditor, ActionListener
         Color currentColor;
         JButton button;
         JColorChooser colorChooser;
         JDialog dialog;
         protected static final String EDIT = "edit";
         public ColorEditor()
              //Set up the editor (from the table's point of view),
              //which is a button.
              //This button brings up the color chooser dialog,
              //which is the editor from the user's point of view.
              button = new JButton();
              button.setActionCommand(EDIT);
              button.addActionListener(this);
              button.setBorderPainted(false);
              //Set up the dialog that the button brings up.
              colorChooser = new JColorChooser();
              dialog = JColorChooser.createDialog(button,
                   "Pick a Color",
                   true, //modal
                   colorChooser,
                   this, //OK button handler
                   null); //no CANCEL button handler
          * Handles events from the editor button and from
          * the dialog's OK button.
         public void actionPerformed(ActionEvent e)
              if (EDIT.equals(e.getActionCommand()))
                   //The user has clicked the cell, so
                   //bring up the dialog.
                   button.setBackground(currentColor);
                   colorChooser.setColor(currentColor);
                   dialog.setVisible(true); //Make the renderer reappear.
                   fireEditingStopped();
              else
                   //User pressed dialog's "OK" button.
                   currentColor = colorChooser.getColor();
         //Implement the one CellEditor method that AbstractCellEditor doesn't.
         public Object getCellEditorValue()
              return currentColor;
         //Implement the one method defined by TableCellEditor.
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
              currentColor = (Color)value; return button;
    /** THE SIMPLE CALENDAR WRITTEN TALIORED TO WORK WITH DIALOGS*/
    import javax.swing.*;
    import java.util.Calendar;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.SimpleDateFormat;
    //import java.beans.*; //property change stuff
    public class CalendarDialog
         extends JDialog
         //implements PropertyChangeListener
         private JButton[] btn = new JButton[49];
         private int month = Calendar.getInstance().get(Calendar.MONTH);
         private int year = Calendar.getInstance().get(Calendar.YEAR);
         private JLabel lbl = new JLabel("", JLabel.CENTER);
         private JOptionPane optionPane;
         private String curDate = null;
         private JTextArea output = new JTextArea(curDate, 1, 20);
         private String btnString1 = "Enter";
         private String btnString2 = "Cancel";
         public CalendarDialog()
              //super(aFrame, true);
              setContentPane(buildGUI());
              setDates();
         public JPanel buildGUI()
              JPanel panel = new JPanel();
              String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
              JPanel midPanel = new JPanel(new GridLayout(7, 7));
              for (int x = 0; x < btn.length; x++)
                   final int selection = x;
                   btn[x] = new JButton();
                   btn[x].setFocusPainted(false);
                   if (x < 7)
                        JLabel lbl = new JLabel(header[x], JLabel.CENTER);
                        lbl.setFont(new Font("Lucida", Font.PLAIN, 10));
                        midPanel.add(lbl);
                   else
                        btn[x].addActionListener(new ActionListener()
                             public void actionPerformed(ActionEvent ae)
                                  displayDatePicked(btn[selection].getActionCommand());
                        midPanel.add(btn[x]);
              JPanel lowPanel = new JPanel(new GridLayout(1, 3));
              JButton prevBtn = new JButton("<< Previous");
              prevBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        month--;
                        setDates();
              lowPanel.add(prevBtn);
              lowPanel.add(lbl);
              lowPanel.add(output);
              JButton nextBtn = new JButton("Next >>");
              nextBtn.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent ae)
                        month++;
                        setDates();
              lowPanel.add(nextBtn);
              JPanel outputPanel = new JPanel();
              Object[] options = { btnString1, btnString2 };
              optionPane =
                   new JOptionPane(
                        output,
                        JOptionPane.QUESTION_MESSAGE,
                        JOptionPane.YES_NO_OPTION,
                        null,
                        options,
                        options[0]);
              outputPanel.add(optionPane);
              panel.setLayout(new BorderLayout());
              panel.add(lowPanel, BorderLayout.NORTH);
              panel.add(midPanel, BorderLayout.CENTER);
              panel.add(outputPanel, BorderLayout.SOUTH);
              return panel;
         public void setDates()
              for (int x = 7; x < btn.length; x++)
                   btn[x].setText("");
              SimpleDateFormat sdf = new SimpleDateFormat("MMMM yyyy");
              Calendar cal = Calendar.getInstance();
              cal.set(year, month, 1);
              int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
              int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
              for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
                   btn[x].setText("" + day);
              lbl.setText(sdf.format(cal.getTime()));
         public void displayDatePicked(String day)
              if (day.equals("") == false)
                   SimpleDateFormat sdf = new SimpleDateFormat("EEEE d MMMM, yyyy");
                   Calendar cal = Calendar.getInstance();
                   cal.set(year, month, Integer.parseInt(day));
                   curDate = sdf.format(cal.getTime());
                   //JOptionPane.showMessageDialog(this, "You picked " + sdf.format(cal.getTime()));
                   output.setText(sdf.format(cal.getTime()));
         public String getDate()
              return curDate;
         public void setDate(String date)
              curDate = date;
    }

    well, i have indeed narrowed down my problem after some digging around.. one thing i discovered that i don't need CalendarRenderer.java.. and i found out i don't really know what does
    //Implement the one method defined by TableCellEditor.
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
              curDate = (String)value; return button;
         }do, as it seems to be the problem:
    java.lang.ClassCastException
         at CalendarEditor.getTableCellEditorComponent(CalendarEditor.java:78)
         at javax.swing.JTable.prepareEditor(JTable.java:3786)
         at javax.swing.JTable.editCellAt(JTable.java:2531)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.adjustFocusAndSelection(BasicTableUI.java:510)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(BasicTableUI.java:494)
         at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:222)
         at java.awt.Component.processMouseEvent(Component.java:5097)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3195)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    mmm.. does anyone know what i should modify for that to work?

  • How to put gradient style table cell in a table?

    Hey, I am making a custom table cell right now but my custom cell is just white cell with some buttons and labels in background color which looks not that great.
    Is there a way to render the background color so that the cell has some vertical gradient effect?
    For example, on top of the cell it looks white and as it gets closer to center of the cell, it gets darker.
    But as it gets closer to the bottom of the cell, it gets whiter again.
    A great example would be this free app called "friendsaroundme".
    Another thing is that I don't want to use custom image to do it (i.e make the cell.backgroundcolor = [uicolor colorwithpatternimage:somethingsomething.png..... ) because it's not that flexible.
    So is there anyway to render the gradient style programatically?

    Congrats on answering your question, David! I'm sure many of the developers here would like to see your solution, so I hope you'll post it when you have the time. - Ray

  • IPhone UISwitch not appearing correctly in table cells

    I have a table cell with a UISwitch attached to it.
    When you click the switch it works (but not without a bit of code to make it switch when the word 'on' and 'off' are actually clicked) but when the table cell itself is clicked the switch distorts like shown here:
    http://img35.imageshack.us/img35/6510/picture1df.png
    what is the correct way to make a table cell with a UISwitch?

    The code you posted looks like it should work on 3.0 just fine.
    I've tried a custom table cell and it did the same thing
    Assuming your custom subclass was built and used correctly, the above tells me something is definitely wrong in the cell's environment.
    Perhaps it's something to do with the selecting of the row method?
    Well that's certainly the first place to look. The delegate method you posted looks kinky. I would comment out that method, then go back to the solutions that didn't work in the past and see if your tableView:didSelectRowAtIndexPath: hasn't been the problem all along.
    In any case I would get rid of the deselect message in tableView:didSelectRowAtIndexPath:. What are you trying to accomplish there? If you simply want to disable all selections, you can just code tableView.allowsSelection=NO during setup. If you want to know the user's selection but don't want the cell to actually become selected, try something like this in the delegate:
    - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    return nil;
    If you want the cell to actually become selected, but don't want its appearance to change, try cell.selectionStyle=UITableViewCellSelectionStyleNone in tableView:cellForRowAtIndexPath:.
    If tableView:didSelectRowAtIndexPath: turns out not to have been the problem, we'll need to look at the rest of your table view code. I've found the kind of problem you described is easily isolated once you have faith in some assumptions. In this case you just need to believe that both the subclass solution and the code in UICatalog will allow a UISwitch to display and operate perfectly. Once you believe that, you'll pay more attention to the rest of you code.
    One excellent way to gain faith in the basic structure is to start a fresh testbed and, for example, use code similar to UICatalog to bring up a table view with a UISwitch in one or more cells. Once you see how easy it is to make that work, you can start backing in some of your more creative init, delegate and/or data source methods until you break the testbed.
    - Ray

  • Creating 2 separate buttons instead of table cell

    Hi,
    I wonder how can I create a custom table cell like in contacts applications where instead of one cell you see 2 separate buttons on the same row? In my case I need to create 2 buttons instead of single row in the state of editing.
    Thanks for help,
    Nava

    Get to the end of the info of some contact. You will see in the end 2 separate buttons on the cell row:
    Text Message and Add To Favorites. Or you can see it on the top of the contact info when you press edit, you will see, that the icon on the top become to be a button, which when pressed brings you to an image picker and alongside lays a what seems to be a cell, which when pressed brings you to a screen, where you can edit the contact name... I can't figure out how do they do that. No sample gives a clue...

  • JTable changing borders for table cells

    Hi,
    I have a JTable which has columns which each represent a month for a
    specified time period. For example, my table displays rows containing numeric data for March 1998 - April 2002.
    I would like to create a Raised Cell for the numeric data for the first
    cell in the time series and a raised cell everytime the numeric data
    is under the column for January of the new year. For example,
    the cell containing the data under March 1998 column should be raised and the cells containing the data for January 1999,2000,2001,2002 should be raised.
    (FYI: I am using a TableModel which extends the AbstractTableModel)
    Many Thanks in advance,
    Alex

    You need to create a custom table cell renderer to do what you are asking. It is what actually draws the cells. Just subclass the DefaultTableCellRenderer and override the getTableCellRendererComponent() method. Look at the source for that class, and just change it to add your logic to use a different border depending on the cell to be drawn.

  • I lost the "..." in my table cells

    Hi,
    I have a JTable with a custom table cell renderer which I program as such inorder to allow an individual cell to render the value ( in this case, text ), in multiple fonts and colors :
    MyCellRenderer extends DefaultTableCellRenderer {
    public Component getTableCellRendererComponent() {
    else if ( value instanceof String ) {
    String s = "<html> ";
    String[] pieces = ((String)value).split("\\.");
    for(int i = 0; i < pieces.length - 1; i++ )
    s += pieces[i] + ".";
    s = s + "<B>" + pieces[pieces.length -1] + "</B>" + "</html>";
    ((JLabel)cell).setHorizontalAlignment(JLabel.LEFT);
    ((JLabel)cell).setText(s);
    ((JLabel)cell).setBorder(new EmptyBorder(0,10,0,0));
    return cell;
    and that works great. The problem is, before, if the cell value string was longer than the column heading, the value would have a "..." at the end to indicate there was more to show. Is there some way I can get this back, and preserve the HTML tag code?
    thanks in advance

    From the random code you posted, it looks like you only have two separate pieces of text in you renderer. If so, then heres a hack you might be able to use:
         class MultiLabelRenderer implements TableCellRenderer
              private JPanel panel;
              private JLabel red;
              private JLabel blue;
              public MultiLabelRenderer()
                   panel = new JPanel(new BorderLayout());
                   red = new JLabel();
                   red.setForeground(Color.RED);
                   blue = new JLabel();
                   blue.setForeground(Color.BLUE);
              public Component getTableCellRendererComponent(
                   JTable table, Object value, boolean isSelected,
                   boolean hasFocus, final int row, final int column)
                   String text = value.toString();
                   red.setText( text.substring(0,1) );
                   blue.setText( text.substring(1) );
                   panel.removeAll();
                   int columnWidth = table.getColumnModel().getColumn(column).getWidth();
                   int redWidth = red.getPreferredSize().width;
                   if (redWidth > columnWidth)
                        panel.add(red);
                   else
                        panel.add(red, BorderLayout.WEST);
                        panel.add(blue);
                   if (isSelected)
                        panel.setBackground( table.getSelectionBackground() );
                   else
                        panel.setBackground( table.getBackground() );
                   return panel;
         }

  • Custom table model, table sorter, and cell renderer to use hidden columns

    Hello,
    I'm having a hard time figuring out the best way to go about this. I currently have a JTable with an custom table model to make the cells immutable. Furthermore, I have a "hidden" column in the table model so that I can access the items selected from a database by their recid, and then another hidden column that keeps track of the appropriate color for a custom cell renderer.
    Subject -- Sender -- Date hidden rec id color
    Hello Pete Jan 15, 2003 2900 blue
    Basically, when a row is selected, it grabs the record id from the hidden column. This essentially allows me to have a data[][] object independent of the one that is used to display the JTable. Instinctively, this does not seem right, but I don't know how else to do it. I know that the DefaultTableModel uses a Vector even when it's constructed with an array and I've read elsewhere that it's not a good idea to do what I'm trying to do.
    The other complication is that I have a table sorter as well. So, when it sorts the objects in the table, I have it recreate the data array and then set the data array of the ImmutableTableModel when it has rearranged all of the items in the array.
    On top of this, I have a custom cell renderer as well. This checks yet another hidden field and displays the row accordingly. So, not only does the table sort need to inform the table model of a change in the data structure, but also the cell renderer.
    Is there a better way to keep the data in sync between all of these?

    To the OP, having hidden columns is just fine, I do that all the time.. Nothing says you have to display ALL the info you have..
    Now, the column appears to be sorting properly
    whenever a new row is added. However, when I attempt
    to remove the selected row, it now removes a seemingly
    random row and I am left with an unselectable blank
    line in my JTable.I have a class that uses an int[] to index the data.. The table model displays rows in order of the index, not the actual order of the data (in my case a Vector of Object[]'s).. Saves a lotta work when sorting..
    If you're using a similar indexing scheme: If you're deleting a row, you have to delete the data in the vector at the INDEX table.getSelectedRow(), not the actual data contained at
    vector.elementAt(table.getSelectedRow()). This would account for a seemingly 'random' row getting deleted, instead of the row you intend.
    Because the row is unselectable, it sounds like you have a null in your model where you should have a row of data.. When you do
    vector.removeElementAt(int), the Vector class packs itself. An array does not. If you have an array, when you delete the row you must make sure you dont have that gap.. Make a new array of
    (old array length-1), populate it, and give it back to your model.. Using Vectors makes this automatic.
    Also, you must make sure your model knows the data changed:
    model.fireTableDataChanged(); otherwise it has no idea anything happened..
    IDK if that's how you're doing it, but it sounds remarkably similar to what I went thru when I put all this together..

Maybe you are looking for