JTree - How do I fire a valueChange Event from a keyPressed Event?

Hi,
I have been stumped trying to figure out how to fire a valueChange event in my JTree from a keyPressed event.
When a user changes tree node using the mouse a valueChange event fires. In my program the valueChange executes some code that must be done. I want to get my JTree to work, so that if a user is nagivating the tree using the keyboard, the code is only executed if they press the enter key.
Below is a little demo program of what I am attempting to accomplish. Any suggestions would be greating appriciated.
Thanks,
Corey
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.tree.*;
import javax.swing.event.*;
public class SimpleTreeDemo extends JFrame  {
  public SimpleTreeDemo() {
  public static void main(String args[]) {
    JFrame j = new SimpleTreeDemo();
    DefaultMutableTreeNode category = new DefaultMutableTreeNode("Top of JTree");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("leaf1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("leaf2");
    category.add(leaf1); category.add(leaf2);
    final JTree jtree = new JTree(category);
    boolean bflag = false;
    jtree.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {
              System.out.println("valueChanged");
              if (bflag)
                   // Execute Code
    jtree.addKeyListener(new KeyListener() {
        public void keyTyped(KeyEvent ke) {
          System.out.println("keyTyped");
        public void keyPressed(KeyEvent ke) {
             System.out.println("keyPressed");
             if (ke.getKeyCode() == KeyEvent.VK_ENTER)
                  bflag = true;
                // Fire valueChanged here!
        public void keyReleased(KeyEvent ke) {
             System.out.println("keyReleased");}
    Container c = j.getContentPane();
    c.add(jtree);
    j.setSize(200,200);
    j.show();

Try this, it works for me.
// Tree Key Listener
      tree.addKeyListener(new java.awt.event.KeyAdapter() {
         public void keyPressed(KeyEvent e) {
            tree_KeyReleased(e);
private void tree_KeyReleased(KeyEvent e) {
      try {
      int keyCode = e.getKeyCode();
      // Get the Tree Path
      TreePath selPath = tree.getSelectionPath();
      if (keyCode == e.VK_DELETE) { //KeyCode - 127
         removeSelectedNode(); // Remove the node
      else if (keyCode == e.VK_ADD) { // Key Code - 107
         tree.expandPath(selPath); // Expand the Node
      else if (keyCode == e.VK_SUBTRACT) { // Key Code 109
         tree.collapsePath(selPath); // Collapse the Node
      else if (keyCode == e.VK_ENTER) {
          // What Ever you want to do here
      else {
      } catch (NullPointerException ex) {
      //System.out.println("Null");
[/code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • How can I fire a change event from a JComboBox and JTextField?

    Is it possible to fire a ChangeEvent from JComboBox?
    Is it possible to fire a ChangeEvent from JTextField?
    If so how can I do that? Thanks.

    You can use an ItemStateListener with the combobox
    As for the textfield, it depends when you want to catch events (every keystroke, or when the user hits enter) but either way, you can do this too. Check keylistener and actionlistener

  • How to update the table value in the valuechange event?

    I have an input field in the datatable with the valueChangeListener
    <rich:dataTable id="cart" value="#{cart.cartList}" var="item">
    <h:inputText value="#{item.cost}" id="qty" valueChangeListener="#{items.updateCost}" onchange="submit()">
    <h:outputText value="#{item.errorMsg}"> </h:outputText>
    in the backing bean
         Item item = (Item) model.getRowData();
    // do some update, if the cost too larger, change to max_cost
         item.setCost(max_cost);
         item.setErrorMsg("Error Msg");
    After calling the valuechange method, the screen output doesn't update the cost.
    How to update the table value in the valuechange event?

    As you're misusing the valueChangeListener to set another input field, you need to skip the update model values phase. Otherwise the value set in the valueChangeListener will be overridden by the submitted value. You can do this by calling the FacesContext#renderResponse() inside the valueChangeListener method. This will shift the current phase immediately to the render response phase, hereby skipping the update model values and invoke application phases.

  • How to re-fire an event?

    How can I re-fire an event?
    1. I have a ddlist, that when a list item is selected, it makes a subform containing some checkboxes become visible.
    2. If I then select another list item, from the ddlist, it will make yet another subform appear, with more checkboxes....
    This works fine.
    The problem happens, when I reselect the first list item again in the ddlist.
    This should behave like part 1. (shown above)
    But the subform that appears is the one from part. 2
    It's like I need to re-fire the change event of the ddlist?
    Anyone know how I can fix this?
    I can't post the form publicly, but could email it, if necessary.
    Thanks in advance for any help!

    Hi,
    When using the change event with dropdowns, you can't use the .rawValue as this has not been set at the point of selection. Instead you would need to use xfa.event.newText.
    I would recommend moving the script to the exit event, as this will work reliably with the .rawValue.
    You can script to fire an event (execEvent), but that it not your problem here.
    Good luck,
    Niall
    Assure Dynamics

  • How to fire JComboBox itemStateChanged event manually?

    hello:
    I want to know how to fire JComboBox itemStateChanged event manually.
    thank you
    -Daniel

    Call setSelectedIndex or setSelectedItem.

  • How do you fire a button click event on apex page from fancybox iframe that was created by page

    I am trying to fire off the button click event from fancybox iframe. The apex page has a button that launches a fancybox iframe which is loaded with an APEX form. On close of that fancy box, I am trying to fire a click event on the parent page which will refresh a div with html that is created with plsql. The button on the page works as expected when clicked from the page. It will show a debug alert message to prove it was called and then load the div with the correct data. I am unable to fire off this button click from the fancybox iframe when it closes.
    A couple of points:
    I using Plug-in: Execute PL/SQL Code and Return Content ("PLUGIN_MULEDEV.SERVER_REGION_REFRESH") to place the create fancybox statement. It is used to populate a div using plsql.
    The name of the button on the main page is P2020_REFRESH_SECTION_BUILDER_BTN.
    The click dynamic action on the button is calling the plugin to replace the html in the div.
    The data in the form in the fancybox is being saved to the database. On close of the fancybox box I want to refresh the div so the new record is included in the div html.
    Can anyone help. Here is the fancybox code:
      function customProcessOnReadyState4(){
        for (var i=0;i<11;i++){
          $( "#tabs"+i ).tabs();
          $("#createNewExerciseLink"+i).fancybox({
              ''width''         : ''60%'',
              ''height''        : ''70%'',
              ''autoScale''     : true,
              ''transitionIn''  : 200,
              ''transitionOut'' : 200,
              ''type''          : ''iframe'',
              ''onClosed''         : function() {
                                         window.parent.$(''#P2020_REFRESH_SECTION_BUILDER_BTN'').click();
    Here are the dynamic actions assigned to the button:
    5 - Execute JavaScript Code
    alert("Starting refresh");
    10 - Execute PL/SQL Code and Return Content [Plug-in]
    begin
      SCTUI.create_sct_tabs2(:P2020_CREATE_SECTION_LOV, '1');
    end;

    user setActionListener...
    <af:setActionListener from="#{bindings.XXX.inputValue" to="#{backingbean.variable}"
                  <af:inputText value="#{bindings.Email.inputValue}"
                                label="#{bindings.Email.hints.label}"
                                binding="#{backingBeanScope.backing_ShuttlePage.it2}"
                                id="it2">
                    <f:validator binding="#{bindings.Email.validator}"/>
                  </af:inputText>
                  <af:commandButton text="commandButton 2"
                                    binding="#{backingBeanScope.backing_ShuttlePage.cb2}"
                                    id="cb2" action="passing">
                    <af:setActionListener from="#{bindings.Email.inputValue}"
                                          to="#{processScope.detail}"/>
                  </af:commandButton>next jsf page:
                <af:outputText value="#{processScope.detail}"
                               binding="#{backingBeanScope.backing_ProcessScope.ot1}"
                               id="ot1"/>setPropertyListener also should work
    <af:setPropertyListener from="#{bindings.Email.inputValue}" to="#{processScope.detail}" type="action"/>

  • How to trigger the valuechange event on button

    Hi All,
    I am working on ADF Application and i have a requirement where i have a valuechange event function associated with the textbox andthe requirement is like the user will enter the value in text box and he/she will press the submit button directly without tab out .I want to trigger my value change event first and if all validation goes right then it should trigger the button event but user will press the butto only once.
    Please reply !!!
    Urgent !!
    Thanks..

    public int validate(){
    int result=0;
    if (value == null){
    //do something
    result=1;
    return result;
    on button click call this
    public String commandButton1_action() {
    if(validate()!=0){
    return null;
    //do rest...
    }

  • JTree: how to rename or substitute folders/leafs ?

    Try to work with JTree …
    Tutorial and api description is not really clear.
    Could someone tell me:
    1. How can I change name of root or any folder/leaf from my program?
    2. How can I substitute the whole showed tree or some part of it, without deleting JTree object(since it is visible in my JPanel)?
    Thank you very much.

    You change the TreeModel which will fire the correct event so the JTree updates automatically.
    See DefaultTreeModel insertNodeInto, removeNodeFromParent and valueForPathChanged (note that you need to override this method and call nodeChanged() yourself if your tree nodes don't have String user objects.

  • ValueChanged Event

    It seems the value changed event fires only when the form is posted. I have a requirement to invoke the valuechange event when user select one item from dropdown list. Is there any way to achieve this? It works When I add the following line on jsf:
    onChange="this.form.submit();"
    But i am not sure if it is a good solution ....... Any help on this will be appreciated.
    -TT

    Don't worry, you're right on track. It's different calling onChange="submit()" and clicking on the commandLink/commandButton on your form.
    Could you please post the pertinent JSP form code, and the method that gets executed when the valueChangeEvent gets fired (i.e. the valueChangeListener in your managed-bean)?
    From there we should be able to tell you exactly how to set up.
    CowKing
    PS - Keep in mind that JSF is a server-side technology and that nothing can happen until a submit takes place.

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • Simple question - How do you make an onchange event occur in a select list

    Simple question - How do you make an onchange event occur in a select list to fire a process?
    Thanks

    1) Using ApEx Selec list on Submit Item.
    You will create a PL/SQL Process after Submit. -> Conditional Type Request = Expression1. -> Expression1 is the name of your Select List. Process Source - > Procedure you like. For example depending of your select List value you will add rows in different tables.
    2) Javascript This example will change a System parameter value when changed
    <select id="P3_SUBSYSTEM" onchange="location.href='f?p=101:3:2164422329953284::NO::P3_SUBSYSTEM:'+this.options[selectedIndex].value;" size="1" name="p_t21">

  • How do I delete a calendar event in my iphone?

    How do I delete a calendar event in my iphone? It allows me to "edit" the event but not to totally delete it. Or at least I can't seem to find a "delete" option anywhere!

    Did you create the event somewhere else?  A lot of time when u create it on lets say PC or mac, you wont be able to edit it unless its from the same device. 
    Its also possible its created under a mail account.  I would suggest making all your events via icloud, then u should be able to edit it on all platforms regardless on which device made the event.

  • How to create a table with events in smartforms?

    How to create a table with events view in smartforms?
    It doesn't like general table with header, main area and footer.
    for example:
    in smartforms: LE_SHP_DELNOTE
    table name is TABLEITEM(Delivery items table)

    Vel wrote:
    I am creating XML file using DBMS_XMLGEN package. This XML file will contain data from two different database tables. So I am creating temporary table in the PL/SQL procedure to have the data from these different tables in a single temporary table.
    Please find the below Dynamic SQL statements that i'm using for create the temp table and inserting the data into it.
    Before insert the V_NAME filed, i will be appending a VARCHAR field to the original data.
    EXECUTE IMMEDIATE 'CREATE TABLE TEMP_TABLE (UNIQUE_KEY NUMBER , FILE_NAME VARCHAR2(1000), LAST_DATE DATE)';
    EXECUTE IMMEDIATE 'INSERT INTO TEMP_TABLE values (SEQUENCE.nextval,:1,:2)' USING V_NAME,vLastDate;What exactly i need is to eliminate the INSERT portion of it,Since i have to insert more 90,000 rows into it. Is there way to have the temp table created with data in it along with the sequence value as well.
    I'm using Oracle 10.2.0.4 version.
    Edited by: 903948 on Dec 22, 2011 10:58 PMWhat you need to do to eliminate the INSERT statement is to -- as already suggested by others - eliminate the temporary table. You don't need it. It is just necessary overhead. Please explain why you (apparently) believe that the suggestion of a view will not meet your requirements.

  • How can I move photos in iPhoto from the WEB Photo Stream or WEB Facebook to one of my Events?

    How can I move photos in iPhoto from the WEB Photo Stream or WEB Facebook to one of my Events?

    From PhotoStream either drag the photos form PS to the iPhoto window or set the iPhoto peference to automatically import PS photos
    From Facebook save to isk and import from there
    LN

  • How to use the table maintenance events for validating the input entries..?

    Hi,
    I have created a Z table with 6 fields in which all are KEY fields. All are of CHAR type. I have created the Table Maintenance Generator for the same. While maintaining the entries in the table, even though I maintain a blank entry for a field it is saving the entry. But, I don't want that way. All the fields are mandatory in my table. One should enter all the fields. Otherwise it should not allow to save the entry. So, I think it can be done using the Table Maintenance Events. can someone tell me how to use the Table Maintenance Events. and which event to use for my reuqirement and what is the logic to be written.
    Or Is there any other way to solve my problem.
    Please share your inputs. Thanks in advance.
    Best regards,
    paddu.

    In the table maintenance generator, Environment --> Modifications --> Events then a screen will be appear here,we need to create the Events.In the EVENTS screen, press new Entries, there give 01(Before Saving the Data in the Database) and give a name(This will become a PERFORM), then click the Editor pushbutton, this will be there at the right side of the entry, then a popup will be appear, you can create an include program, there inside of the include program write ur code.
    Here is documentation for Event 01(Before Saving the Data in the Database )
    Event 01: Before Saving the Data in the Database
    Use
    This event occurs before new, changed or deleted entries are written to the database. Other activities can be performed, for example:
    hidden entry processing
    fill hidden fields
    flag data to be written to hidden tables after the database change.
    To have the changes saved by the central maintenance dialog routines, SY-SUBRC must be set to 0 at the end of the routine.
    Realization
    This event has no standard routine. The following global data is available for the realization of the user routine:
    internal table TOTAL
    field symbols
    field symbols <ACTION> and <ACTION_TEXT>
    <STATUS>-UPD_FLAG
    If internal table data are to be changed before saving, t he changes should be made in both the internal table TOTAL and in the internal table EXTRACT.
    FORM abc.
    DATA: F_INDEX LIKE SY-TABIX. "Index to note the lines found
    LOOP AT TOTAL.
    IF <ACTION> = desired constant.
    READ TABLE EXTRACT WITH KEY <vim_xtotal_key>.
    IF SY-SUBRC EQ 0.
    F_INDEX = SY-TABIX.
    ELSE.
    CLEAR F_INDX.
    ENDIF.
    (make desired changes to the line TOTAL)
    MODIFY TOTAL.
    CHECK F_INDX GT 0.
    EXTRACT = TOTAL.
    MODIFY EXTRACT INDEX F_INDX.
    ENDIF.
    ENDLOOP.
    SY-SUBRC = 0.
    ENDFORM.
    Regards,
    Joy.

Maybe you are looking for