Clone column groups with custom cells

I have set up custom bordered cells meaning to copy them along with the border. Instead only the contents are copied, when I paste the columns the borders are ignored. How do I copy and paste blocks of cells including the borders?

We may do that in two operations.
• copy then paste the contents
• use the "Copy Style" button on the source block of cell
select the destination block (with the correct number of cells) then use the "Paste Style" button.
These two buttons aren't installed by default so, we must install them by ourself.
Yvan KOENIG (from FRANCE lundi 9 juin 2008 08:52:15)

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.

  • Target group with customer and contact person

    Hi experts,
    I want to create a target group with customer data and the names of the main contact person to execute a campaign.
    During execution I need the name of the contact person to personalize my forms, the campaign activity should be connected to the customer (and not the contact person).
    Is there a functionality to solve my problem? (CRM 7.0)
    Thanks in advance.
    Werner

    Hi Werner,.
    I assume you want to select for Organizations (BUT000 Type 2) and you want to see in the Target Group the Contact Persons which are assigned via Relationship to the Orgnizations.
    Create for example a Datasource with  Infoset CRM_MKTTG_BP_ORG, and under Details for Business Partner use BUT000_PER-PARTNER_GUID.
    In Field Function Module maintain CRM_MKTTG_PF_BP_TAB_TO_CP.
    Create an Attribute List an assign the Datasource. After Creating the Target Group you will see the Organizations with all the assigned Contact Persons via Relationsship.
    Regards
    Andreas
    Another Tip: Create a Target Group for Persons, assign it to the Campaign, and now set the B2B Flag. Depending from your SP Level you have to apply a note so that the B2B Flag is visible (1263915)
    If you set the B2B flag you will get Communication Data for letters, for a Call List from the Relationship.
    Regards,
    Andreas
    Edited by: Andreas Pauli on Apr 29, 2009 10:18 AM

  • Iterate through RichTable with custom cells

    Hi.
    I create a RichTable by drag and drop a view in DataControls. View is from table xxx and table contains only one column, binding description field in the table.
    This description is shown in an OutputText UI component.
    Then, I add a column with a SelectOneRadio component (to check Yes/No).
    Finally, I add another column with an Input Text to write comments.
    So, when I click one button, I capture the action event and want to process table content. But, how can I iterate through this table?
    How can I get each row, and each cell in its row (each radio, each text)?
    My JDeveloper version is 11.1.1.7.0
    Thanks in advance. Best regards
    EDIT: _________Final solution_________
    Add two transient attributes and iterate the VO object is very easy.
    For the specific issue about radio button, add a switcher and bind the radio group with the transient attribute.

    Hi,
    You could do something like
                   <af:switcher id="s1" defaultFacet="input" facetName="#{row.type eq 0?'radio':'input'"}>
                    <f:facet name="input">
                        <af:inputText id="it2" value="#{row.answer.inputValue"}/>
                    </f:facet>
                    <f:facet name="radio">
                        <af:selectBooleanRadio id="sbr1" value="#[row.answer.inputValue"}/>
                    </f:facet>
                    </af:switcher>
    -Arun

  • Performance decrease with custom cell renderer

    Hi,
    Finally, I have my cell renderer working fine (it was simpler than I thought). Anyway, I'm suspecting something is not working quite well yet. When I try to reorder my colums (by dragging them) they move like slow motion. If I don't register my custom cell renderer, I can move my columns fine. Next is the code of my custom renderer.
    class PriorityRenderer extends DefaultTableCellRenderer {   
      public Component getTableCellRendererComponent(
      JTable table, Object value,     boolean isSelected,
      boolean hasFocus, int row, int column) {              
        if(value instanceof coloredValue) {
        coloredValue cv = (coloredValue)value;
        if(isSelected) this.setBackground(table.getSelectionBackground());
        else this.setBackground(cv.getbkColor());
        this.setForeground(cv.gettxColor());
        this.setText(value.toString());
        this.setOpaque(true);
        return this;
    }All the cells of my JTable are "coloredValue"s. This is a little class with a String, two colors and some getter methods.
    Can anyone giveme a hint ?
    Thanks!!

    OK! Now the performance problem is gone!! (I don't know why, I didn't touch a thing)
    Thanks anyway

  • JTable - help with custom cell renderers and editors

    I've got myself into a bit of a mess with cell renderers and editors.
    I've got a custom component that wants displaying in a column and then hand over all functionality to this component when you start editing it.
    Now how I went out about this was to create a custom cell renderer that extends this component and implements TableCellRenderer.
    I then created a table cell editor that extends AbstractCellEditor and implements TableCellEditor and this cell editor creates a new component when it's initialized. I then use setCellEditor(new MyCellEditor()) on the column and setCellRenderer(new MyCellRenderer()).
    This works slightly but I'm wondering how this is all implemented.
    When I set the cell editor on it's own it seems to be sharing a reference to the single component that's being used which means that if you edit one cell all the cells get changed to the new value.
    Thanks for the help,
    Alex

    only a few forums are actually browsedAnd theSwing forum is one of the most active. Did you search it for editiing examples? I've seen many editing examples posted in a SSCCE format.
    SSCEE is also impossible as the functionality spans over about 10 classes We did not ask for your application, we asked for a SSCCE. The whole point of a SSCCE is to simplify the 10 classes into a single class and maybe an inner class for the editor to make sure you haven't made a silly mistake that is hidden because of the complexity of your real application.

  • LINQ grouping with custom comparer

    I'm trying to implement a linq grouping with a custom comparer. I have a datatable, I fill it with data, then I add the datarows to a
    List(Of DataRow), then I select all the rows to a IEnumerable(Of Object()). After that, I would like to group the result with a custom comprarer.
    This is the code:
    Dim result As IEnumerable(Of Object())
    Dim dt As New DataTable
    Dim indexes As New List(Of Integer)
    Dim groupedindexes As New List(Of Integer)
    Dim datarows As New List(Of DataRow)
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    dt.Columns.Add("f1", Type.GetType("System.Char"))
    dt.Columns.Add("f2", Type.GetType("System.Char"))
    dt.Columns.Add("f3", Type.GetType("System.Char"))
    For i = 0 To 100
    dt.Rows.Add("a", "b", "c")
    Next
    indexes.Add(0)
    indexes.Add(1)
    indexes.Add(2)
    groupedindexes.Add(0)
    groupedindexes.Add(1)
    groupedindexes.Add(2)
    For i = 0 To dt.Rows.Count - 1
    datarows.Add(dt.Rows(i))
    Next
    result = datarows.Select(Function(row) indexes.Select(Function(index) row(index)).ToArray)
    Dim test = result.GroupBy(Function(row) groupedindexes.Select(Function(grpindex) row(grpindex)).ToArray, New compare)
    End Sub
    And this is the compare class:
    Partial Class compare
    Implements System.Collections.Generic.IEqualityComparer(Of Object())
    Public Function Equals1(ByVal x() As Object, ByVal y() As Object) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Object()).Equals
    Dim equal As Boolean = True
    For i = 0 To x.Count - 1
    If x(i) IsNot y(i) Then
    equal = False
    Exit For
    End If
    Next
    Return equal
    End Function
    Public Function GetHashCode1(ByVal obj() As Object) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Object()).GetHashCode
    Dim hashcode As Integer
    For i = 0 To obj.Count - 1
    hashcode = hashcode + obj(i).GetHashCode
    Next
    Return hashcode
    End Function
    End Class
    With the above code, I get all the 101 rows, but I would like to get only one row (a, b, c), since all the rows are the same. Therefore I wrote the custom comparer class. I'm new to this and I'm not sure, that I use it correct.
    Can you advise me, how should I modify the code to get only one row?
    Thanks.

    Try code below.  I use a dictionary to group rows and then filter results to get unique rows.
    Module Module1
    Sub Main()
    Dim dt As New DataTable
    Dim dict As Dictionary(Of Integer, List(Of DataRow)) = dt.AsEnumerable() _
    .GroupBy(Function(x) x.Field(Of Integer)("Col A"), Function(y) y) _
    .ToDictionary(Function(x) x.Key, Function(y) compare(y.ToList()))
    End Sub
    Function compare(rows As List(Of DataRow)) As List(Of DataRow)
    Dim results As New List(Of DataRow)
    results.Add(rows.FirstOrDefault)
    If (rows.Count > 1) Then
    For i = 1 To (rows.Count - 1)
    Dim unique As Boolean = True
    Dim rowArray() As Object = rows(i).ItemArray
    For j = 0 To (results.Count - 1)
    Dim oldArray() As Object = results(j).ItemArray
    For cols = 0 To (rowArray.Length - 1)
    If rowArray(i) <> oldArray(j) Then
    unique = False
    Exit For
    End If
    Next cols
    If unique = False Then
    Exit For
    End If
    Next j
    If unique = True Then
    results.Add(rows(i))
    End If
    Next i
    End If
    Return results
    End Function
    End Module
    jdweng

  • JTable with custom cell for folding and unfolding rows

    Hi,
    I am trying to implement a JTable, whereas one of the columns is a custom component, which has a small + in the right upper corner.
    When you push this + the JTable should unfold other rows, giving more detail on the current row.
    So something like this :
    |--------------------------------|
    |   <some-string>              + |
    |--------------------------------|Drawing this custom component for the column is no problem but I am having trouble implementing the MouseMotionListener events over this.
    If I add a mouseMotionListener to the JTable, I am able to forward these events to my custom class which draws this custom component.
    But off course the X and Y coordinates of this MouseEvent are not mapped into the grid of my custom component, which poses my question.
    How can I attach to each cell of this custom column of my JTable, a listener as to implement some mouseover and mouseclick stuff ?
    In case this post is not all that clear, I will try to add a demo showing my problem.
    Kind regards,
    Wim.

    You're reinventing a wheel that's been done a few times. One example is JTreeTable (http://community.java.net/javadesktop/) but there are others.

  • How to make a spreadsheet column-formula with relative cell addresses?

    I'm trying to make a spreadsheet compute with relative cell addresses. I tried what's on the help page, and it doesn't work.
    What I’m attempting is to make one column contain the differences of another column, like,
    Gn=Fn-F(n-1)
    to apply to the entire G column, without typing (or even pasting) 100s of individual formulas. As an added bonus, I'd like for the invalid cell address resulting from n=1, to be defaulted to 0.
    How to do this???

    Another way to move the relative formula to other cells:
    Select the cell with the formula, use the little handle in the center of the side (it appears when you move your pointer there).  In the picture it is in the center of the bottom side.  Drag that handle downward, this copies the formula into the cells you include in the drag.  You can also do this upward, leftward, rightward by selecting one of the other sides.

  • Inconsistent behavior with Custom Cell Renderer

    I have two questions:
    Questions # 1.
    I have created a custom cell renderer for my JTable that changes color if the text property changes and the text contains the letter 'S'. Like
    so:
    class SchedRenderer extends DefaultTableCellRenderer{
    public SchedRenderer(){
    super();
    final Color c = scSelfCont.panelbg;
    this.setForeground(c);
    this.addPropertyChangeListener("text",new PropertyChangeListener(){
    public void propertyChange(PropertyChangeEvent e){
         boolean foundS=false;
         String text=e.getNewValue().toString();
         for(int i=0;i<text.length();i++)
         if(text.charAt(i)=='S'){
         foundS=true;
         break;
         if(foundS){
         SchedRenderer.this.setBackground(Color.red);
         SchedRenderer.this.setForeground(Color.red);
         else{
         SchedRenderer.this.setBackground(c);
         SchedRenderer.this.setForeground(c);
    99% of the time it works just fine. But occasionally the cell will revert back to its original color, and then back to the correct color after clicking somewhere entirely different. I set some breakpoints in the property change handler and it gets called quite frquently even if no change has been made. At first I thought this was a JDK bug, but I am now convinced that there simply must be a better way to do this, any ideas?
    Question # 2:
    Is there a simple way to change the color of an entire row without selecting it? Currently I am using Custom Cell Renderers to change
    colors of cells, but it seems like such an obtuse method. Is there a better way?
    Thanks in advance.
    Adrian Calvin

    I have two questions:
    Questions # 1.
    I have created a custom cell renderer for my JTable that changes color if the text property changes and the text contains the letter 'S'. Like
    so:
    class SchedRenderer extends DefaultTableCellRenderer{
      public SchedRenderer(){
        super();
        final Color c = scSelfCont.panelbg;
        this.setForeground(c);
        this.addPropertyChangeListener("text",new PropertyChangeListener(){
           public void propertyChange(PropertyChangeEvent e){
         boolean foundS=false;
         String text=e.getNewValue().toString();
         for(int i=0;i<text.length();i++)
           if(text.charAt(i)=='S'){
             foundS=true;
             break;
         if(foundS){
           SchedRenderer.this.setBackground(Color.red);
           SchedRenderer.this.setForeground(Color.red);
         else{
           SchedRenderer.this.setBackground(c);
             SchedRenderer.this.setForeground(c);
    [\code]
    99% of the time it works just fine.  But occasionally the cell will revert back to its original color, and then back to the correct color after clicking somewhere entirely different.  I set some breakpoints in the property change handler and it gets called quite frquently even if no change has been made.  At first I thought this was a JDK bug, but I am now convinced that there simply must be a better way to do this, any ideas? 
    Question # 2:
    Is there a simple way to change the color of an entire row without selecting it?  Currently I am using Custom Cell Renderers to change
    colors of cells, but it seems like such an obtuse method.  Is there a better way?
    Thanks in advance.
    Adrian Calvin

  • JTable column names with custom model

    I'm having problems with column names in a JTable which uses a custom model. For some reason, the colums are being shown as A, B, C etc. The data, however, displays fine.
    This is the code which constructs the table.
    MyTableModel tableModel = new MyTableModel(myArrayList);
      myTable = new JTable(tableModel);
      myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      myTable.setFillsViewportHeight(true);This is the class, MyTableModel
    class MyTableModel extends AbstractTableModel {
            private ArrayList<Account> data;
            private String[] colNames = {"", "Name","Type","Group","Created","Modified"};
            public MyTableModel(ArrayList<Account> data) {
                this.data = data;
            public int getRowCount() {
                return data.size();
            public int getColumnCount() {
                return 6;
            public Object getValueAt(int row, int col) {
                Account account = (Account)data.get(row);
                switch(col) {
                    case 0:
                        return account.getIcon();
                    case 1:
                        return account.getName();
                    case 2:
                        return account.getType();
                    case 3:
                        return account.getGroup();
                    case 4:
                        return account.getDateCreated();
                    case 5:
                        return account.getDateModified();
                    default:
                        return "";
            public String getColumName(int index) {
             System.out.println("N:"+colNames[index]);
                return colNames[index];
        }When the table is displayed, nothing's displayed to the console, but I'd have thought getColumnName would print the current column name. Am I missing something obvious?

    Oh great. I'll go back under my rock.
    Thanks =)

  • Size of combobox in JTable with custom cell editor

    Hi All -
    I have a JTable that displays a combobox in certain cells. I have a custom table model, renderer, and editor. All of that works fine. I render the combobox with the renderer, and then return the combobox as an editor in the editor so that it can drop down and actually be of use. My problem is - I set the size of the combobox with a setBounds call in the renderer, I add it to a panel, and return the panel - because I dont want the combobox to take up the entire space of the cell. This approach fails in the editor. The setBounds and setSize calls have no effect. As soon as you click the combobox, the editor takes over and all of a sudden the combobox resizes to the entire area of the cell. I assume this is because in the editor you arent actually placing anything - your simply returning the "editing form" of the component.
    So - anybody know of a way to work around this? Worst case, I could just allow the combobox to use the entire area of the cell - but it makes it uglier so I figured I would run it by the forums.
    Eric

    Rather than just redirect you to my previous answer from ages ago, I'll just give it again. :-)
    You can actually do this, but you have to get tricky. By default, the dropdown's width will be the same width as the cell... but it doesn't have to be that way. Essentially what you have to do is override the UI (MetalComboBoxUI) for the combo component. In your new customized UI component subclass (that you set the combo to use), modify the the createPopup() method of this UI class, and add your own logic to set the size of the popup before you return it.
    Ideally the size would be based on the computed max width of a rendered item shown in the combo, but really you could set it to whatever just to see how it works.

  • Using Functions and/or Graphs with Custom Cell Formats in Numbers

    I am attempting to use the AVERAGE function or create a graph in Numbers for cells with a custom format, however, I keep receiving an error message telling me that "Numbers can't be divided by Zero" or an empty graph.
    The format I am using is for a split time for a certain distance, as in time it takes a runner to go around a track: minute:seconds.milliseconds i.e. 1:56.4
    Is there a solution to the formatting or another way to accomplish having the correctly formatted cell and still be able to use functions and graphs.

    Hi nich.lee,
    You can't chart Duration formatted data without first converting it to another format. Also, you will get an error if you attempt to use the AVERAGE function on an empty range.
    Here's an example of charting Duration data by using a conversion...
    Best regards,
    Jerry

  • JTable custom cell editor losing focus

    This is a followup to Re: Tutorial on AWT/Swing control flow wherein I ask for pointers to help me understand the source of focus-loss behaviour in my JTable's custom cell editor.
    I have done some more investigations and it turns out that the focus loss is a more general problem with custom cell editors which call other windows. Even the color-picker demo in the JTable tutorial at http://download.oracle.com/javase/tutorial/uiswing/examples/components/index.html#TableDialogEditDemo has this problem, IF you add a text field or two to the layout BEFORE the table. The only reason the table in the demo doesn't lose the focus when the color-picker comes out is because the table is the only thing in the window!
    Here is the demo code, augmented with two text fields, which are admittedly ugly here but which serve the desired purpose:
    * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    *   - Redistributions of source code must retain the above copyright
    *     notice, this list of conditions and the following disclaimer.
    *   - Redistributions in binary form must reproduce the above copyright
    *     notice, this list of conditions and the following disclaimer in the
    *     documentation and/or other materials provided with the distribution.
    *   - Neither the name of Oracle or the names of its
    *     contributors may be used to endorse or promote products derived
    *     from this software without specific prior written permission.
    * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
    * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
    * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class TableDialogEditDemo extends JPanel {
        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();
            public Object getCellEditorValue() {
                return currentColor;
            public Component getTableCellEditorComponent(JTable table,
                                                         Object value,
                                                         boolean isSelected,
                                                         int row,
                                                         int column) {
                currentColor = (Color) value;
                return button;
        public class ColorRenderer extends JLabel
                implements TableCellRenderer {
            Border unselectedBorder = null;
            Border selectedBorder = null;
            boolean isBordered = true;
            public ColorRenderer(boolean isBordered) {
                this.isBordered = isBordered;
                setOpaque(true);
            public Component getTableCellRendererComponent(
                    JTable table, Object color,
                    boolean isSelected, boolean hasFocus,
                    int row, int column) {
                Color newColor = (Color) color;
                setBackground(newColor);
                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);
                return this;
        public TableDialogEditDemo() {
            super(new GridLayout());
            JTextField tf1 = new JTextField("tf1");
            add(tf1);
            JTextField tf2 = new JTextField("tf2");
            add(tf2);
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 70));
            table.setFillsViewportHeight(true);
            JScrollPane scrollPane = new JScrollPane(table);
            table.setDefaultRenderer(Color.class,
                    new ColorRenderer(true));
            table.setDefaultEditor(Color.class,
                    new ColorEditor());
            add(scrollPane);
        class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"First Name",
                    "Favorite Color",
                    "Sport",
                    "# of Years",
                    "Vegetarian"};
            private Object[][] data = {
                    {"Mary", new Color(153, 0, 153),
                            "Snowboarding", new Integer(5), new Boolean(false)},
                    {"Alison", new Color(51, 51, 153),
                            "Rowing", new Integer(3), new Boolean(true)},
                    {"Kathy", new Color(51, 102, 51),
                            "Knitting", new Integer(2), new Boolean(false)},
                    {"Sharon", Color.red,
                            "Speed reading", new Integer(20), new Boolean(true)},
                    {"Philip", Color.pink,
                            "Pool", new Integer(10), new Boolean(false)}
            public int getColumnCount() {
                return columnNames.length;
            public int getRowCount() {
                return data.length;
            public String getColumnName(int col) {
                return columnNames[col];
            public Object getValueAt(int row, int col) {
                return data[row][col];
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("TableDialogEditDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new TableDialogEditDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }When you come back from choosing a color, tf1 is given the focus, instead of the table. This is because bringing the color picker window to the front causes a focus lost event for the cell editor component; it's temporary, as it should be, so why on earth is the system losing track of who has focus in the window??
    I see the following in Window#getMostRecentFocusOwner():
      public Component getMostRecentFocusOwner()
        if (isFocused())
          return getFocusOwner();
        else
          Component mostRecent =
            KeyboardFocusManager.getMostRecentFocusOwner(this);
          if (mostRecent != null)
            return mostRecent;
          else
            return (isFocusableWindow())
                   ? getFocusTraversalPolicy().getInitialComponent(this)
                   : null;
      }My app has a custom focus traversal policy, so I'm able to see who is being called, and indeed, getInitialComponent() is being called. Clearly, the KeyboardFocusManager is actually losing track of the fact that the table was focussed at the point where control was transferred to the color picker! This strikes me as completely unreasonable, especially since, as noted, this is a temporary focus loss event, not a permanent one.
    I'd be grateful for any wisdom in solving this, since similar behaviour to this little demo -- without focus loss, naturally -- is an essential part of my application.

    Looks like it is because the 'restore-focus-to-previous-after-modal-dialog-close' is in a later event than when the control returns to the action performed (which I guess makes sense: it continues the action event handler and the focus events are handled later, but I needed two chained invoke laters so it might also be that the OS events comes later).
    The following works for me (in the actionPerformed edited):
               // create the dialog here so it is correctly parented
               // (otherwise sometimes OK button not correctly the default button)
               dialog = JColorChooser.createDialog(button, "Pick a Color", true,  //modal
                            colorChooser, this,  //OK button handler
                            null); //no CANCEL button handler
                    //The user has clicked the cell, so bring up the dialog.
                    button.setBackground(currentColor);
                    colorChooser.setColor(currentColor);
                    button.addFocusListener(new FocusListener() {
                        @Override
                        public void focusLost(FocusEvent e) {}
                        @Override
                        public void focusGained(FocusEvent e) {
                            // dialog closed and focus restored
                            button.removeFocusListener(this);
                            fireEditingStopped();
                    dialog.setVisible(true);but a simpler request might be better (althoug I still need an invoke later):
    // rest as before except the FocusListener
                    dialog.setVisible(true);
                    button.requestFocusInWindow();
                    EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            fireEditingStopped();
                    });And a quick fix to the renderer so you can actualy see the focus on it:
                    if(hasFocus) {
                        Border border = DefaultLookup.getBorder(this, ui, "Table.focusCellHighlightBorder");
                        setBorder(BorderFactory.createCompoundBorder(
                                border, BorderFactory.createMatteBorder(1, 4, 1, 4,
                                        ((MatteBorder) getBorder()).getMatteColor())));
                    }

  • Tableview custom cell problem

    Hi everyone.
    I created a iOS tabbed application using xcode 4.2 and storyboard. I added one tableviewcontroller with custom cell on it, when clicking the row, I want to open one tableviewcontroller, i used the following code below
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
        categoryClass *cc = [datas objectAtIndex:indexPath.row];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        iSubProducts *subProducts = [[iSubProducts alloc] init];
        subProducts.title = cc.categoryName;
        subProducts.catID = cc.categoryID;
        [[self navigationController] pushViewController:subProducts animated:YES];
        [subProducts release];
    but when I click the row it gives me the following error:
    *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath
    on my iSubProducts tableviewcontroller, i have the following:
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        static NSString *CellIdentifier = @"myCell2";
        iSubProductsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        productSubClass *cc = [datas2 objectAtIndex:indexPath.row];
        NSLog(@"Product Name: %@", cc.productName);
        cell.txtProductName.text  = cc.productName;
        cell.txtProductDesc.text = cc.productDesc;
        return cell;
    I assume this is where the error occurs, the cell is returning a nil value. When I try to attach the iSubProducts tableviewcontroller using or from a button, it all works fine, but if its coming from row clicked, this error shows up.
    Im quite new with iOS development, and maybe there is a error opening tableviewcontroller from a tableviewcontroller with a custom cell on it. I've been bangin my head for 2 days now and googled a lot, unfortunately I didn't find any solution. I'm pretty sure there's no error on the iSubProducts tableviewcontroller since its working if i tried pushing it from a button. Please I need advice on this one, Im so stucked right now with this issue. Thank you everyone.

    Hi,
    you need to create a tableViewCell in case the dequeueReusableCell-call doesn't return one.
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        static NSString *CellIdentifier = @"myCell2";
        iSubProductsCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
            cell = (iSubProductCell *)[[UITableViewCell alloc] init....
        productSubClass *cc = [datas2 objectAtIndex:indexPath.row];
        NSLog(@"Product Name: %@", cc.productName);
        cell.txtProductName.text  = cc.productName;
        cell.txtProductDesc.text = cc.productDesc;
        return cell;
    Dirk

Maybe you are looking for

  • How do i restore the information in my iphone back to how it was before I changed it?

    I accidentally didn't know what I was doing and ended up changing all my settings. It deleted all my contacts now I searching a way to get all my previous data back, any ideas? Please I am in desperate need of help. I was trying to put music in my ph

  • Keeping the right site tied to my short url on MobileMe

    I have maintained multiple websites in multiple domain files, all published to MobileMe since iWeb first came out. I have one site which serves as an index page to all the sites I maintain. This index site is designed to be tied to my short url at Mo

  • How do I export a freeze frame in CS4?

    There's no longer an "Export/Frame" menu option in CS4 (as there was in CS3). How can I export a simple freeze frame from Premiere into another editing program, such as Photoshop? Thanks.

  • Bash script run via cron not executing MYSQL command

    I have a bash script which is run from a cron, It is executing as I have it write to a log file which it does correctly. I am wanting the bash script to restore a mysqldump file. When I run the bash script manually the dump file gets loaded fine. But

  • HT4061 how can i reset my phone when my home button isnt working ?

    My phones home button hasnt been working for a few days. I tired installing the new software but now its stuck on a loop trying to switch on then saying connect to itunes. I've tried restoring it on itunes but that is giving me the error message (319