How to veto a JComboBox selection change in ItemListener

I have a JComboBox whose current value is tied to some data cached in my application. I want to be able to examine the selection in an ItemListener attached to the JComboBox, and if the value is different than what I have cached, I want to ask the user if they really want to change because the change will render some other data as no longer valid. If the user wants to abandon the change, then I want to "abandon" or "veto" the selection change and reset it to the old value.
For instance, if the combo box has values "Foo" and "Bar" in it, and "Foo" is the cached selection, then the user goes and changes the selection to "Bar", I want to prompt them with something like "You have changed the value to Bar. Doing so will render XXX no longer valid. Do you want to continue?" -- if they cancel the change, then leave the selection as "Foo".
What is the best way to do this within ItemListener's itemStateChanged? Are there better ways to do this besides what I've outlined? I didn't see anything in "Core JFC" book or the JDK documentation that discussed this sort of thing.
Thanks in advance,
Eric

Hi,
It is a design problem and not realy a language problem... The way I create vetoing design it that a keep the previous selection of the JComboBox... upon action I look if the application can do the new computation...if not...ask the user... if true| run calculations if not set the JComboBox to the previous selection...
JRG

Similar Messages

  • How to 'veto' a jList selection change

    Hi All,
    I have a JList which I'm using as a record selector - so whenever my user selects an item on the list, the associated record is loaded up into the other controls on this form for editing. If the user edits any of the data items, I want to ask whether to save changes or not if another item is selected from the JList. So, I've added code in my 'selection changed' function to check for changes and show a 'yes/no/cancel' JOptionPane. The code for my 'yes' and 'no' respones work fine - either save the changes or not, then show the next record. My problem is handling if a user clicks cancel...
    If the user selects 'Cancel', I dont want any of my "show new record" code to execute (this is easy, I can just 'return' out of the function) but also I don't want the JList selection to change. I've tried calling setSelectedIndex() back to the originally selected item, but this in turn triggers my 'selection changed' function to be called again, which causes the user to be asked twice whether they want to save changes!
    So, what I'm after is a kind of beforeSelectionChanged event, which allows the possibility of denying the selection change - but it doesn't look like this exists! I vaguely remember another language (possibly C++/MFC) having this - the user's action could be ignored depending on the return value of the function. Can anyone offer a way of achieving this in Java?
    (It's been a while since I last touched Java, and I'm a complete n00b with Swing. Using NetBeans as my IDE.)
    Thanks in advance for any suggestions!
    Andy

    The way I do it, is to implement a VetoableSelectionModel similar to a bean with a vetoable property: on selection change it queries registered VetoableChangeListeners if they don't object and backs out if one of them barks.
    HTH
    Jeanette

  • How to listen for cell selection changes within a JTable

    Problem: my table has 8 columns, with 4 of them containing very large text (up to 1000 chars). Solution is to set the initial size these columns so that the 1st 20 chars are visible, and if one of these columns gains focus/selection via mouse-clicking/tabbing/arrow keys, the entire text is shown in a JTextArea below the table.
    I added a ListSelectionListener to the table, but this only informs me when the row selection has changed.
    I added a FocusListener to the table, but this only informs me when the table gains/loses focus, not when it's been changed within.
    I added a TableColumnModelListener to the TableColumnModel, but this only informs me when the column selection has changed.
    I didn't bother with MouseListener as this won't handle change of selection via tabbing.
    The LSL got me half way there, and the TCML got me the other half. Any ideas on how to combine?
    Or is there something obvious that I'm missing?

    Walter Laan wrote:
    Use both and call the same method which updates the text area based on the current selected (or focused == lead selection index) cell.Yeah - that's what I figured. I just didn't know if there was a magic bullet (i.e., a single listener) out there that I was missing.
    While you are at it, also add a table model listener which calls the same method if the selected cell is updated.I'll keep that in mind, but it's not necessary in this particular case. The table cells in question will be uneditable. The text area will have supporting Edit/Save/Cancel buttons.

  • How to prevent action (lead selection change) with popup (confirmation)?

    Hello all,
    I have an application where I want the user to confirm when he selects a new line in a table. When the user selects a new line in the table an other used component reloads its data based on the new line selected. If the user has not pressed the save button before selecting a new line, any changes in the used component will be lost.
    Currently I use onLeadSelect action on the table to call the load_data method(id=xxx) on the used component in order to display data relevant for id=xxx based the new line.
    I can open a popup to confirm from the onLeadSelect-action or the WDDoBeforeAction, but the action still happens; it doesn't wait for the user to respond. And then any changes are lost...
    I may have to store the parameters sent to the onLeadSelect method in context and continue when the button action from the pop-up returns via subscribed method, but I think this is an unelegant way of doing this.
    There must be a better way...? Any ideas?
    Regards,
    Christian Frier

    on the lead select event handler you can show the popup and no other logic. Move your logic to the ok and cancel button handlers of the pop up.

  • How do I find and/or change the pre-set voltage selection switch in an HP TouchSmart IQ500 series

    how do I find and/or change the pre-set voltage selection switch in an HP TouchSmart IQ500 series (specifically an IQ524)
    This question was solved.
    View Solution.

    Doesn't it use an external AC Adapter? If so, all you should need to use in another country is an adpater plug to match the wall socket.
    ... an HP employee expressing his own opinion.
    Please post rather than send me a Message. It's good for the community and I might not be able to get back quickly. - Thank you.

  • How to generate selection change event through code in JTree?

    I am developing an application which downloads the file from other system and adds it into the tree. On selecting any file in the tree I m displaying it's contents. But now i am trying to display the contents of downloaded file as soon as it's download completes. Here i am not getting the way to how to generate the event as the download completes, because i tried that setSelectionPath(TreePath path), but it also don't generates the selection change event. Is there any other way to do so?

    Put null in place of oldLeadSelectionPath. From the API for TreeSelectionEvent:
    protected TreePath     oldLeadSelectionPath:
    leadSelectionPath before the paths changed, may be null.
    I'm at the office and can't try out anything, so please let me know whether that works for you.
    db
    edit Or it may be easier to put all code from your valueChanged (...) override in a new method and invoke that method both from valueChanged (...) and wherever else you need.
    Edited by: Darryl.Burke

  • Problem in JComboBox selected Index change

    hi all
    Can anyone send me the code for Loading values to JComboBox & then i want to Display Particular value for that Loaded value in JTextField.
    Ex:
    I loaded category cade for JComboBox & when JComboBox selected index change the particular category name should appear in JTextBox
    Thankz

    Hi,
    I am sending a sample program.
    Try this, if u had any problem just mail me at [email protected]
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SwingDemo extends JFrame implements ItemListener
         JComboBox combo;
         JTextField text;
         Properties props;
         public SwingDemo() throws Exception
              super();
              combo=new JComboBox();
              text=new JTextField();
              addItems("combodata.dat");
              setLayout(new GridLayout(2,1));
              add(combo);
              add(text);
              combo.addItemListener(this);
              setTitle("JComboBox - Demo");
              setSize(400,400);
              setVisible(true);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
         public static void main(String[] args) throws Exception
              new SwingDemo();
         public void addItems(String str) throws Exception
              FileInputStream fis=new FileInputStream(str);
              props=new Properties();
              props.load(fis);
              Enumeration e=props.propertyNames();
              while(e.hasMoreElements())
                   combo.addItem((String)e.nextElement());
         public void itemStateChanged(ItemEvent ie)
              //System.out.println(ie.getSource());
              //System.out.println((ie.getSource()==combo));
              if(ie.getSource()==combo)
                   System.out.println(combo.getSelectedItem());
                   System.out.println(props.getProperty(combo.getSelectedItem().toString()));
                   text.setText(props.getProperty(combo.getSelectedItem().toString()));
                   pack();
    For the above program I took data from a file instead of the database
    You have to create that file to execute the above program with the name combodata.dat and the values as follwos
    1=BSc
    2=BCA
    3=BA/BCom
    4=MSc(IS)
    5=MSc(Cs)
    6=MCA
    7=BE/BTech
    8=MBA
    Bye...
    Thanks & Regards,
    Santhosh Reddy Mandadi

  • How to trap Selection change

    Hi All,
    I need to observer selection change. How do i go about it. In basicpersistinterface the kBPISelectionObserverImpl is bound with the panel. Similarly I want to call a method on selection change and not update some UI, so where do i need to put my ActiveSelectionObserver.
    It can  be just displaying an alert of selection change, but how do we trap it.
    Please contribute your valuable suggestions.
    Thanks in advance.
    Jasmine Shaikh

    You can aggregate your observer to any easily accessed boss that's permanently around. For example kSessionBoss already has 15 observers, kAppBoss has 7 observers. You would use a private IID, though. Invoke AutoAttach from a StartupShutdown service.
    Given that, you're probably wrong architecture-wise by watching the selection without UI involved. There are plenty other notifications, besides there are also different mechanisms to watch the selection from closer on (e.g. SelectionExt). Can you give more details on your intent?
    Dirk

  • How to change images of selected items in gridview on selection changed event in universal app

    Hi,
    I am developing Universal App. I have bind the images to the Gridview using ObservableCollection. I have set gridview
    SelectionMode as Multiple . I want to change the images of selected items but I don't know how to do in Selection Changed event of Gridview. I got selected items with the help of
    Gridview SelectedItems property. How can i change the images of respected selected items?
    Please reply me asap.
    Thanks in advance.

    Hi, Sorry for late reply,
    Please change the class : 
    public class ImageCollection : INotifyPropertyChanged
    private string source;
    public string Source
    get { return source; }
    set { SetProperty(ref source, value); }
    public int MyProperty { get; set; }
    protected void SetProperty<T>(ref T storage, T value, [System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
    if (!object.Equals(storage, value))
    storage = value;
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    protected void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] String propertyName = null)
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    public event PropertyChangedEventHandler PropertyChanged;
    XAML
    <GridView x:Name="gd"
    Tapped="gd_Tapped">
    <GridView.ItemTemplate>
    <DataTemplate>
    <Grid Height="300" Width="250">
    <Image Source="{Binding Source}" Stretch="Fill"/>
    <Grid Height="100" Background="#B2000000" VerticalAlignment="Bottom">
    <TextBlock Text="{Binding MyProperty}" FontSize="25" />
    </Grid>
    </Grid>
    </DataTemplate>
    </GridView.ItemTemplate>
    </GridView>
    C#
    //ObservableCollection of class
    ObservableCollection<ImageCollection> img = new ObservableCollection<ImageCollection>();
    public MainPage()
    this.InitializeComponent();
    img.Add(new ImageCollection() { MyProperty = 1, Source = "ms-appx:///Assets/Logo.scale-100.png" });
    img.Add(new ImageCollection() { MyProperty = 2, Source = "ms-appx:///Assets/2.jpg" });
    img.Add(new ImageCollection() { MyProperty = 3, Source = "ms-appx:///Assets/3.jpg" });
    img.Add(new ImageCollection() { MyProperty = 4, Source = "ms-appx:///Assets/4.jpeg" });
    gd.ItemsSource = img;
    private void gd_Tapped(object sender, TappedRoutedEventArgs e)
    GridView gv = (GridView)sender;
    ImageCollection ic = gv.SelectedItem as ImageCollection;
    ic.Source = "ms-appx:///Assets/4.jpeg";
    gv.UpdateLayout();
    I have used  INotifyPropertyChanged now UI is not fluctuate 
    and I have not bind again O-Collection.
    I hope so You will get right answer. 
    shah

  • How can I set a property when an event happens? (selection changed on datagrid)

    I have a datagrid, I would like to change the backgrund of the datagrid when the selection changed event is fired.
    I can not use data trigger, because is in the case that I expected a value, but in this case is when change, to any value.
    An option is to use an event trigger, but all the examples that I have found is to use with an actions, and I just want to set a property.
    How could I do that?
    I am using MVVM pattern, so I would like to avoid the use in code-behind.
    Thank so much.

    You could use an event trigger and implement your own TriggerAction<T> that sets the background property. There is an example of how to create a custom TriggerAction available here:
    http://stackoverflow.com/questions/942548/setting-a-property-with-an-eventtrigger.
    The following example sets the Background property of the DataGrid to a red SolidColorBrush when the SelectionChanged event is fired. It should give you the idea:
    <DataGrid x:Name="dgrid"
    xmlns:local="clr-namespace:WpfApplication22">
    <i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
    <local:SetPropertyAction PropertyName="Background" TargetObject="{Binding ElementName=dgrid}">
    <local:SetPropertyAction.PropertyValue>
    <SolidColorBrush>Red</SolidColorBrush>
    </local:SetPropertyAction.PropertyValue>
    </local:SetPropertyAction>
    </i:EventTrigger>
    </i:Interaction.Triggers>
    <DataGrid.Columns>
    namespace WpfApplication22
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    public string PropertyName
    get { return (string)GetValue(PropertyNameProperty); }
    set { SetValue(PropertyNameProperty, value); }
    public static readonly DependencyProperty PropertyNameProperty
    = DependencyProperty.Register("PropertyName", typeof(string),
    typeof(SetPropertyAction));
    public object PropertyValue
    get { return GetValue(PropertyValueProperty); }
    set { SetValue(PropertyValueProperty, value); }
    public static readonly DependencyProperty PropertyValueProperty
    = DependencyProperty.Register("PropertyValue", typeof(object),
    typeof(SetPropertyAction));
    public object TargetObject
    get { return GetValue(TargetObjectProperty); }
    set { SetValue(TargetObjectProperty, value); }
    public static readonly DependencyProperty TargetObjectProperty
    = DependencyProperty.Register("TargetObject", typeof(object),
    typeof(SetPropertyAction));
    protected override void Invoke(object parameter)
    object target = TargetObject ?? AssociatedObject;
    PropertyInfo propertyInfo = target.GetType().GetProperty(
    PropertyName,
    BindingFlags.Instance|BindingFlags.Public
    |BindingFlags.NonPublic|BindingFlags.InvokeMethod);
    propertyInfo.SetValue(target, PropertyValue);
    For more information about how to hook up event triggers and handle events in MVVM, please refer to my blog post:
    http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
    Please also remember to mark helpful posts as answer.

  • How to block lead selection change in a tree ?

    Hi Guys,
    <u>Scenario</u>
    I have MasterTree - DetailEditor pair. <i>MasterTree</i> is used to visit some tree-structured data and <i>DetailEditor</i> is used to edit currently selected tree node.
    <u>Requirement</u>
    If currently selected node data is updated through <i>DetailEditor</i> and needs to be saved, than on a subsequent tree selection change the user should be warned about unsaved data.
    <u>Implementation</u>
    In <b>onAction</b> event handler of <i>MasterTree</i> I check whether last selected node data is updated and needs to be saved and if this is the case rollback <i>treeSelection</i> to that node. On the time <b>onAction</b> event handler is called the tree selection is changed from the node that needs save to the newly selected node. In order to rollback <i>treeSelection</i> I need to introduce variable referencing last selected tree node.
    <u>Question</u>
    Is there any other technique to implement above scenario without using additional variable and manually rollback <i>treeSelection</i> ? For example, to plug in WDP framework on validation step just before lead selection is changed.
    Thanks in advance

    Alex,
    Here is a link to the phase model of WD:
    http://help.sap.com/saphelp_nw04/helpdata/en/b8/cd96edb9c8794aa362e6e8b4236a1f/frameset.htm
    There aren't any hooks provided prior to the event handlers being called. As far as I can tell, the way you are handling it is the only way that will work.
    -Cindy

  • To update the JComboBox selection

    Hi,
    I have JTable and JComboBox on a Frame. I got data into table and combo box from database. Now I want to change the combo box value depending on a JTable's row selection. I'm calling jComboBox1.getSelectedItem() , but there's changes in the JComboBox .
    Please help, if you know how

    I mean I just want to know how can I request the selection of the combo box

  • JComboBox selected value

    Hi,
    I have a JComboBox and I need to be notified if the selected item (or index) has changed. How can I do that?
    Thanks a bunch

    Use the addItemListener() method and add an item listener to the JComboBox. This will tell you when the selection changes.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • How to avoid the user selecting a different path in my installer

    Hello again all you helpful forum-goers!
    I have an application and a corresponding installer, and then I have a separate installer putting some support files in the same directory.  My problem is that if the user selects a different path to which to install my primary application, the secondary installer will not put the required support files in the same spot.
    Now, I think I've figured out how to get the user-selected path from the "Run executable at the end of installation" option in the Advanced pane of the LabVIEW installer configuration, and I can pass that in to my secondary installer, and that should fix the problem.  However, what I'd really like to do is just not give the user the option to install my primary application in a different directory to begin with.  I've looked, but cannot find any way to do that.
    Does anyone know of any way to not present the option to install an application in a different directory when using the LabVIEW installer?
    Thanks in advance for any suggestions,
    -Joe

    Ben64,
    That's great!  Thank you so much for your quick reply.  The only reason I haven't already accepted that as my solution is that it requires a manual post-compile change to a text file.  Ideally I'd prefer not to have to remember to do that every time I rebuild my installer.  Is there any way that you know of to automate the process?
    If not, I'm happy to have a good solution even if it takes an extra step each time to implement.
    -Joe

  • How can I reduce the selection for the characteristics value in a BW query

    Good morning,
    I need to find out how I can reduce the selection for the characteristics values in a BW query.
    In a BW query I have a characteristic "Due month".
    The characteristic values shown in the query are from 01.2001->03.2007. I would like to reduce it to the last 2 years,in the query view,  without deleting the data for the other years in the cube.
    Do you know how this can be done?
    Thank you in advance for your feedback.
    Kind regards,
    Linda Verding
    Staff Consultant - CSC

    hi,
    First thing you have to do is check the report how the data is being restricted only to those months.
    1) one it can be variable in which the code is written for that to populate for last few years.
    or else it must have been hardcoded for these months.
    Go into your report and underneath the characteristicsCALMONTH there must be an variable or hardcoding.
    You need to change this here in the report.
    You dont have to delete anything there.
    Regards, Siva

Maybe you are looking for