How to use cell editors in JTree?

Hi,
I have a component where I am placing JTable in JTree node.The table cells should be editable.
I was unable to do that.
I am giving code for 2 classes below,which I used.
To test this compile the classes seperately.
/**************************TableInTree.java(main class)**************/
import java.awt.Component;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
public class TableInTree extends JFrame
public TableInTree()
super("TableInTree");
JTree tree = new JTree(this.createTreeModel());
tree.setCellRenderer(new ResultTreeCellRenderer());
tree.setEditable(true);
this.getContentPane().add(new JScrollPane(tree));
public static void main(String[] args)
TableInTree frame = new TableInTree();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.show();
// * Method createRootNodes.
private TreeModel createTreeModel()
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("test1");
node1.add(new DefaultMutableTreeNode(new TableRenderDemo)));
root.add(node1);
root.add(new DefaultMutableTreeNode("test2"));
return new DefaultTreeModel(root, true);
public static class ResultTreeCellRenderer extends DefaultTreeCellRenderer
public Component getTreeCellRendererComponent(JTree t, Object value,boolean s, boolean o,boolean l, int r, boolean h)
if (value instanceof DefaultMutableTreeNode)
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
if (node.getUserObject() instanceof TableRenderDemo)
return new JScrollPane((TableRenderDemo) node.getUserObject());
return super.getTreeCellRendererComponent(t, value, s, o, l, r, h);
/*******************TreeRenderDemo.java**************************/
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.table.*;
import java.awt.*;
* TableRenderDemo is just like TableDemo, except that it
* explicitly initializes column sizes and it uses a combo box
* as an editor for the Sport column.
public class TableRenderDemo extends JPanel {
private boolean DEBUG = false;
public TableRenderDemo() {
super(new GridLayout(1,0));
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Set up column sizes.
initColumnSizes(table);
//Fiddle with the Sport column's cell editors/renderers.
setUpSportColumn(table, table.getColumnModel().getColumn(2));
//Add the scroll pane to this panel.
add(scrollPane);
* This method picks good column sizes.
* If all column heads are wider than the column's cells'
* contents, then you can just use column.sizeWidthToFit().
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer =
((JTableHeader)table.getTableHeader()).getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(
null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues,
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
//XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Knitting", new Integer(2), new Boolean(false)},
{"Sharon", "Zakhour",
"Speed reading", new Integer(20), new Boolean(true)},
{"Philip", "Milne",
"Pool", new Integer(10), new Boolean(false)}
public final Object[] longValues = {"Sharon", "Campione",
"None of the above",
new Integer(20), Boolean.TRUE};
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];
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
* Don't need to implement this method unless your table's
* editable.
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
* Don't need to implement this method unless your table's
* data can change.
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[j]);
System.out.println();
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
//JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("TableRenderDemo");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
Please give me a solution.
thanks in advance

rebounce

Similar Messages

  • How to use cell function in xcelsius

    Can anybody tell me ,how to use "=cell("filename")" function in xcelsius excel sheet. The function working properly in Excel,but not in Xcelsius workbook. Any suggestions. please........!

    Hi,
    Cell function is not supported in Xcelsius 2008.
    Please check all excel functions here:
    http://help.sap.com/businessobject/product_guides/xcelsius2008/en/Xcelsius2008_user_guide_en.pdf

  • How to add cell editor to cell variant dynamically?

    Hi everyone,
      I'm developing a web dynrpo component. In one of the views , I need to modify the view dynamically
    because the data structure only can be determined at runtime. And the table column should have two
    cell variants. I don't know the exact cell variant class which should be used. I only find an abstract class about cell variant CL_WD_ABSTR_TABLE_CELL_VAR , but I can't find any method in this class which
    can add cell editor under this cell variant.
    Thanks in advance.

    Hi Sireesha,
    Thanks for link you provided.
    I am able to add Column with CommandImageLink.And onclick of that link i am able to display another popup.
    Now another problem which i am facing is when i select one row from popup and click "Ok" i have to modify some columns from Dyanamic table which is displayed on main page.
    For this.
    1)First i took the selected row from dyanamic table to update that perticular row depending upon the row which i select from popup.
    if you see the code above i am refaring the list as collection for data.So i am updating that collection but again it is refreshing to it's original value.
    because number of times getList() method of bean get's called equal to number of columns. which brings the values from database.
    Here On click of popup's Ok button I don't want to save the data for table i just want to show there in some column's .and After click on SAVE button from table i have to save it.
    Let me help how can i modify the Dynamic table's data.
    Thanks for all help.
    Jaydeep

  • Domesticating JCheckBox when used as editor in JTree

    If you look at the way checkboxes are drawn in certain L&F's (say, 1.5's Metal), you'll see that upon arming (mouseover/hover) of the box, a highlight or focus is painted on the little square box. I believe this may be true in the XP L&F and know it is true in JGoodies Plastic XP.
    This is caused by arming of the box occuring just by a mere mouseover which gives a fancy visual effect. However, when used as a cell editor in a JTree, this looks really bad and even inconsistent since the renderers don't have the same effect.
    So I'd like to disable this, but after a long night of hacking through Swing code, it appears that this stuff is really tightly wrapped in. There are no per-instance flags that can be set to disable it. BUT, here is what gives me hope. I've got JCheckBoxes in all my JTables and NONE of them experience this visual feature. Somehow JTable must be trapping and consuming the mouse entered, exited, etc. events so that you never see the painting of the checkbox change when you hover over it. JTable has tamed this wicked beast and put him in his place. What is this great master's secret?

    What I meant to say was a table is a single component so once the mouse enters the table no more mouseOver events will be generated.
    As you move the mouse around the table you are moving the mouse over rendered versions of a checkBox. Again since these are rendered versions you won't generate a mouseOver event.
    When you generate a mousePressed event on a cell with a checkBox as an editor, the editor is invoked and the checkBox is painted in its "pressed" state, so again you won't see the rollover effect. When you release the mouse cell editing is stopped and the renderer is again displayed, so again you won't generate a mouseOver event on the checkBox.
    So I don't think JTable is doing anything fancy to handle mouseOver or mouseExited events. Its just that they are only generated at the table level and not the cell level.
    I haven't played with JTree or any fancy LAF's, so I'm not sure what to suggest. I'm surprised that JTree would work differently.

  • How to use Property Editor from an Add-In?

    Hi,
    I am writing a WYSIWYG add-in for JDev that allows users to put some object into a JPanel instance.
    Thess object has properties such as left, right, width, height, etc.
    - Question: how to use JDev's property editor to allow users change properties of thess object?
    - Another word: how to user JDev's Property Editor API from an add-in?
    I looked at the document. It does not give me enough information about Property Editor.
    Thanks in advance,
    Trung

    Hello Prasad,
    You are on the right avenue - launch an external application which can connect to running Outlook instance and then close it. After this you can launch Outlook anew. Here are the steps required to get the job done:
    1. Use the Marshal.GetActiveObject method which obtains
    a running instance of the specified object from the running object table (ROT) - Outlook in your case, for example:
    // Check whether there is an Outlook process running.
    if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
    then use the
    Quit method to close the running instance. The
    associated Outlook session will be closed completely; the user will be logged out of the messaging system and any changes to items not already saved will be discarded.
    2.  Use the
    Start method of the System.Diagnostics.Process class to start Outlook anew.

  • How to use renderer for a Jtree Element

    Hi all,
    i have been told to use Renderer for drawing a JTree on a JPanel.
    I mean, i want to draw each element of the JTree as a rectangle with a label inside it.....each element of my JTree contains an UserObject with a string inside it.
    Any suggestions ?
    Cheers.
    Stefano

    read the link below it shows how to use trees and tree renderer.
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

  • How to Use different icons for JTree in the same level

    Hi guys, i come cross a problem with JTree. The module need a JTree which need to represent items in the same level using different icons. For example:
    [Icon for Root]Root
    |
    |_____________[Icon for Table] TABLES
    |
    |_____________[Icon for Index] INDEXS
    |
    |_____________[Icon for Views] VIEWS
    As i know, the default behavior for JTree is using the same icon for all leaves and
    the same icon for all node that has children. How can i achieve that?
    Thansk a lot!

    subclass DefaultTreeCellRenderer. if you overwrite the method below, then you can set the icon to whatever you want....!
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                    boolean sel,
                                    boolean expanded,
                                    boolean leaf, int row,
                                    boolean hasFocus) {
         String         stringValue = tree.convertValueToText(value, sel,
                               expanded, leaf, row, hasFocus);
            this.tree = tree;
         this.hasFocus = hasFocus;
         setText(stringValue);
         if(sel)
             setForeground(getTextSelectionColor());
         else
             setForeground(getTextNonSelectionColor());
         // There needs to be a way to specify disabled icons.
         if (!tree.isEnabled()) {
             setEnabled(false);
             if (leaf) {
              setDisabledIcon(getLeafIcon());
             } else if (expanded) {
              setDisabledIcon(getOpenIcon());
             } else {
              setDisabledIcon(getClosedIcon());
         else {
             setEnabled(true);
             if (leaf) {
              setIcon(getLeafIcon());
             } else if (expanded) {
              setIcon(getOpenIcon());
             } else {
              setIcon(getClosedIcon());
            setComponentOrientation(tree.getComponentOrientation());
         selected = sel;
         return this;
        }

  • How to use cell phone as modem

    I have a 3G enabled cell phone (Nokia E71) that I use as modem with my windows laptop
    - connects via USB
    How can I do the same with my MacBook Air ?
    - have tried to connect, but nothing seems to be happening / detected

    IF there are any drivers for your cellphones, they would be available through your cellphone manufacturer, or through 3rd party programmers who program for your cellphone and have written a Mac interface. Apple does not support it from their end --

  • How to use Abap Editor(SE38) Test Plan Management Option

    Hi,
    I am trying to use the Test Plan Management option in Abap Editor.
    I could not find any articles/forum postings about it.
    Please guide me on the same.

    hi,,
    go through the below link for help.
    http://help.sap.com/saphelp_erp2005vp/helpdata/EN/06/27185efc5211d1bcfd080009b4534c/frameset.htm
    regards,
    bhavana

  • How to use Script Editor to open iTunes visualizer?

    I have an AppleScript which I used to use in previous versions of OS X to open a visualizer and put it into full screen if music was currently playing. If no music was playing, then it would turn off the visualizer and take iTunes out of full screen. This script still works, but only if iTunes is already open and you can see iTunes on the desktop. If iTunes is open with music playing, but not visible(not visible on the desktop aka minimized or you clicked the red "x" to close iTunes, but not actually quit it), then I get the error...
    "Can’t set «class pVsE» of application "iTunes" to true.
    iTunes got an error: Can’t set visuals enabled to true. (-10006)"
    How can I fix this error so it no longer happens?
    I believe I just need to find a way to bring iTunes to the desktop, even if it's already open. Again, it works just fine if you can see iTunes on the desktop
    Any suggestions?
    I am using Mac OS X Yosemite 10.10.3.
    Thanks for any help!
    Here is the Apple Script...
    tell application "iTunes"
         activate
         delay 1
         if player state is playing then
              if visuals enabled is true then
                   set full screen to false
                   delay 3
                   set visuals enabled to false
             else if visuals enabled is false then
                  set visuals enabled to true
                  set full screen to true
            end if
       end if
    end tell

    The visualizer appears to be bound to the browser window - if there is no browser window, enabling the visualized fails.
    The simplest solution, therefore, may be to show the browser window before trying to enable the visualizer:
      else if visuals enabled is false then
      set visible of browser window 1 to true -- add this line to show the browser window
      set visuals enabled to true
      set full screen to true
      end if

  • How to use cell contents to indirectly reference other tables?

    I think I need to use the INDIRECT or ADDRESS function here, but I just can't seem to structure it right. Does anyone have ideas?
    I have a model that uses multiple tables, and I want to be able to enter table names, column names and row names into a new table, and for it to go and look up the right value in that TABLE::ROW NAME, COLUMN NAME.
    In more detail: I have a table called SITES that has columns called Site1, Site2 etc, and rows of information such as Name, Phone, etc. I also have a whole series of tables called OPTION1, OPTION2 etc etc, which also have multiple columns for Site1, Site2 etc, and then rows of different information for each site, labelled Alt1, Alt2, Alt3 etc.
    What I want to do is create new tables for reports, where I can enter eg OptionN in one cell, SiteN in another, and for that table to lookup the value of table OptionN::SiteN AltN. I need this to be built into the formulae partly for data integrity purposes eg, if the table shows Site1 name, and Option1, I need to be certain that the information in that table truly reflects Site1 and Option1 information, and also because I want to be able to create some simple whatif comparisons by changing a table from say Option1 to Option2 and seeing the difference.
    So far, I have tried entering OptionN in A1 of the new table, and SiteN in B1, butI can't find a formula that will then go to table OptionN (A1) and lookup eg SiteN (B1), AltN. The AltN term would be written into the formula rather than referenced from another cell such as C1. I've tried the following sort of thing - none work:
    =&A1 &"::" &B1 &"AltN"
    =INDIRECT(A1&"::"&B1&"AltN")
    =INDIRECT(ADDRESS(AltN,B1,,,A1))
    I'd be very grateful for any help, as the ability to create tables that will lookup info from elsewhere using contents of its own cells will transform Numbers for me from a novelty to a seriously useful tool.
    Message was edited by: MrJim

    MrJim wrote:
    I've tried this, but it doesn't seem to work for non-numeric values. If $C was the name of a Header row, eg Mot, instead of a number then it doesn't seem to work.
    James,
    Here's a primitive example that, I believe, in your words "will transform Numbers for me from a novelty to a seriously useful tool".
    In the Result column we have the nice little expression: =INDIRECT(Site&" "&Alt). You should be able to take it from there.
    That's it.
    Jerry
    Edit: This presumes that you have gone to the Numbers Preferences and selected Use Header Names as References.

  • How to use the cell editor in FICO reports for YTD

    HI experts,
    I am working with BI7.0, in the below report, i have displayed result based on user input.but how to calculate the YTD values. User will give the input like 072007, results will be display one year from 072007 to 062006 (one yearback) and one more column is YTD
    Report structure is :
         user input(single value): 072007
              AUG06....JAN07....JULY07....YTD
    KEYFIGURE-1        453      -
    777     -
       232       -
      777 (Only Jan07 value of Keyfigure-1)   
    KEYFIGURE-2        879      -
    233        -
    123       -
      ???? (only sum from Jan07 to July07)
    KEYFIGURE-3        212            -
    879      -
    989                -
    KEYFIGURE-4        234            -
    656      -
    788                   -
    KEYFIGURE-5        345            -
    878      -
    878                 -
    KEYFIGURE-6        767            -
    767       -
    323                 -
    KEYFIGURE-7        879            -
    878     -
    999                -
    999 (Only last value of keyfigure-7 (July07)
    in the above report, total 7 keyfigures so 7rows of YTD column
    1) in the first YTD column, how will display only one value (keyfigure-1) of Jan07?
    2) in the last YTD Column, how will display only one value (keyfigure-7) of July07?
    3) from 2 to 6 columns of YTD, how will display the sum from Jan07 to July07?
    Note: months will be changed based on user input(single Value)
    how can use cell editor for above the senior.
    if any option is availabel please let me know
    Thanks
    kishore

    I think the following should work:
    Context:
    Rows (node,c=0:n)
    --- rowIndex (integer)
    selectedRowIndex (integer)
    Bind the "selectedKey" property of the radio button (cell editor) to attribute "selectedRowIndex" (outside table data source node) and bind "keyToSelect" to attribute "Rows.rowIndex". Make sure that the "rowIndex" attribute will contain the index of the node element in node "Rows".
    Armin

  • Cell editor use

    what all the advantages using cell editor and where it is necessary to use

    Hi,
    Refer,
    Re: cell editor
    http://help.sap.com/saphelp_nw04/helpdata/en/cb/89fa3a0376a51fe10000000a114084/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/a5/359840dfa5a160e10000000a1550b0/content.htm
    Regards,
    Gunjan.

  • How to use Tooltips with JTree

    Hi to all,
    i need to show tool tip with on mouse over event on JTree. Tooltip text should be
    dynamic and its value depends on tree node.
    i did't implemented tooltips as of now. i have visited some sites but i did't
    get good information. Please suggest me that wher to start this.
    Thanking You

    Sun's JTree tutorial has an example that shows how to use tool tips in JTrees:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    Look at the TreeIconDemo2.java example.

  • Create a VC Model for BEx queries with Cell Editor

    Hello All,
    I am trying to create a VC Model for BEx queries with Cell Editor.
    BW Development Team has created a BEX query with complex restrictions and calculations using Cell Editor feature of BI-BEX.
    The query output in BEx analyzer is correct where all values are being calculated at each Cell level and being displayed.
    But, while creating VC model, system is not displaying the Cells.Thus, no VC Model can be created.
    I have executed below steps:
    1. Created a VC Model for BEx Query - ZQRY_XYZ
    2. Create Iview -> Create a dataService -> Provide a Table from the Output
    In the Column field system is not showing any of the Cells (present in Cell Editor)
    Please help me to solve this issue.
    Thanks,
    Siva

    Hi
    If 'Cell Editor' is been used then that query must have the structure in it. You have to select that 'structure' object in your 'VC Table'.
    If you select that then you will get the required result in the output. This structure will be the structure where 'cell reference' is used in BI query, You have to select that structures name.
    Regards
    Sandeep

Maybe you are looking for

  • HR Configuration guideline.

    Hi, I am moving from ABAP to HR functional, can any body help me in this regard to be a HR certified? I can work as HR power user but I don't know about the configuration? thanks Syed Tayab Saha

  • Logging in ADF BC Applications.

    I am looking for logging implementation in ADF BC applications and I found oracle.adf.share.logging.ADFLogger as part of the ADF Model Runtime resources. Can we use this for logging in our Application development. What is the best way to implement lo

  • Using XQuery Transformations

    Hi, I am new to OSB and have been trying my hand creating XQuery transformations. I have been getting the following error while testing the proxy service:           (receiving request) Initial Message Context *          added $body* *     <soapenv:Bo

  • Alternate row color urgent

    Hi I have to make alternate color rows. now possible solution is below but it is giving one extra line below table.so i dont want to use this. is there any idea thanxs<% int num = 0; String SLATE = "#E4E4E4"; String WHITE = "#FFFFFF"; String bgColor

  • Client Backup Service stopped, can not be restarted

    Recently I started to get a critical error saying the service Windows Server Essentials Computer Backup is not running. It did work before and I hadn't made any changes to the server. I can not repair the error / restart the service. It will stop aga