Getting value of observed object? - java

How do I get the value of watched which is "New Value"?
Code from here:
import java.util.Observable;
import java.util.Observer;
class ObservedObject extends Observable {
private String watchedValue;
public ObservedObject(String value) {
watchedValue = value;
}
public void setValue(String value) {
// if value has changed notify observers
if(!watchedValue.equals(value)) {
watchedValue = value;
// mark as value changed
setChanged();
}
}
}
public class ObservableDemo implements Observer {
public String name;
public ObservableDemo(String name) {
this.name = name;
}
public static void main(String[] args) {
// create watched and watcher objects
ObservedObject watched = new ObservedObject("Original Value");
// watcher object listens to object change
ObservableDemo watcher = new ObservableDemo("Watcher");
// add observer to the watched object
watched.addObserver(watcher);
// trigger value change
System.out.println("setValue method called...");
watched.setValue("New Value");
// check if value has changed
if(watched.hasChanged())
System.out.println("Value changed" + new value of watched!); // that's what I want. ("New Value")
else
System.out.println("Value not changed");
}
public void update(Observable obj, Object arg) {
System.out.println("Update called");
}
}
Output:
setValue method called...
Value changed
Line 40:
System.out.println("Value changed" + new value of watched!); // that's what I want.
Wanted Output:
setValue method called...
Value changed to New Value

You already have a setter method in the form of setValue so now just implement a corresponding getter method:
import java.util.Observable;
import java.util.Observer;
class ObservedObject extends Observable {
private String watchedValue;
public ObservedObject(String value) {
this.watchedValue = value;
}
public String getWatchedValue() {
return watchedValue;
}
public void setWatchedValue(String value) {
if (!watchedValue.equals(value)) {
this.watchedValue = value;
setChanged();
}
}
}
public class ObservableDemo implements Observer {
public String name;
public ObservableDemo(String name) {
this.name = name;
}
public static void main(String[] args) {
ObservedObject watched = new ObservedObject("Original Value");
ObservableDemo watcher = new ObservableDemo("Watcher");
watched.addObserver(watcher);
System.out.println("setValue method called...");
watched.setWatchedValue("New Value");
if (watched.hasChanged()) {
System.out.println("Value changed: " + watched.getWatchedValue());
} else
System.out.println("Value not changed");
}
public void update(Observable obj, Object arg) {
System.out.println("Update called");
}
}
Output:
setValue method called...
Value changed: New Value

You can access the new value from the Observable by providing a getter function like given below and call the notifyObservers(); inside the setValue(String value)
class ObservedObject extends Observable {
private String watchedValue;
public ObservedObject(String value) {
watchedValue = value;
}
public void setValue(String value) {
// if value has changed notify observers
if(!watchedValue.equals(value)) {
watchedValue = value;
// mark as value changed
setChanged();
notifyObservers();
}
}
public String getValue(){
return watchedValue ;
}
}
And modify the below method to get the new value
public void update(Observable obj, Object arg) {
System.out.println("Update called :"+obj.getValue());
}

Related

update object in hashmap by java 8 lambda

I created an item named player as follows:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class player implements Comparable <player> {
int PlayerId ;
String name ;
double salary;
public player(int PlayerId) {
this.PlayerId = PlayerId;
}
public void setPlayerId(int PlayerId) {
this.PlayerId = PlayerId;
}
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getID() {
return PlayerId;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
#Override
public int hashCode() {
int key = 2;
return key=2*key+PlayerId;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final player other = (player) obj;
if (this.PlayerId != other.PlayerId) {
return false;
}
return true;
}
#Override
public String toString(){
return hashCode()+" "+getID() +" "+getName()+" "+getSalary();
}
// generic method StoreplayerDetails
public <T> void StoreplayerDetails( HashMap<Integer,T> inputMap ) {
// save elements into text file
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream("OutPut.txt"));
for(T element : inputMap.values())
pw.println(element);
pw.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
} finally {
pw.close();
}
}
#Override
public int compareTo(player other) {
if(this.salary>other.salary)
return 1;
else
if(this.salary<other.salary)
return -1;
return 0;
}
public interface Update {
public <T> void updateSalaries( HashMap<Integer,player> inputMap);
}
}
create an interface named update in the player class ,create a generic method named updateSalaries in the interface that takes a HashMap as input and returns a Queue of player objects after updating the salaries of players by adding 500 to each one's salary .
in the mainprogram class implement the method updatesalaries as a lamdba expression .in the mainprogram class,print the elements in the returned queue .
I tried it as follows but it did not work out:
#Override
public <T> void updateSalaries(HashMap<Integer, player> map) {
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
System.out.println("new map"+map);
}
This is the full code in the main class
import java.util.HashMap;
import player.player.Update;
public class MainProgram implements Update{
public static void main(String[] args) {
HashMap< Integer,player> Keys = new HashMap<>();
player p1 =new player(1);
p1.setName("Ali");
p1.setSalary(5000);
player p2 =new player(2);
p2.setName("Sayed");
p2.setSalary(7000);
player p3 =new player(3);
p3.setName("soha");
p3.setSalary(3000);
Keys.put(1, p1);
Keys.put(2, p2);
Keys.put(3, p3);
// p1.StoreplayerDetails(Keys);
MainProgram m = new MainProgram();
m.updateSalaries(Keys);
}
#Override
public <T> void updateSalaries(HashMap<Integer, player> map) {
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
System.out.println("new map"+map);
}
}
Is there any help in solving this?
In your code snippet you have the following line of code:
map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
Let's take this apart piece by piece:
map.replaceAll This method lets you replace all the values in a map. I believe you want to manipulate the values that are already there, instead.
(k,player.getSalary()) This is where you name the variables that the lambda will dump values into. You aren't supposed to supply numbers here, you are supposed to be receiving numbers. You likely want (k, p), where k will be set to the key (an Integer) and p will be set to the value (a player).
player.getSalary()+500 This returns an int. The replaceAll method requires that you return the value type, which in this case is player.
You forgot to include a close parenthesis at the end.
I believe you want to use this line of code instead, which mitigates all of the above errors:
map.forEach((k, p) -> p.setSalary(p.getSalary() + 500));

How to retrieve the changed item in an ObservableList via ListChangeListener

There is ListChangeListener.Change.wasUpdated() which is used to detect changes within elements for ObservableLists created via ObservableList.observableArrayList(Callback<E,Observable[]> extractor).
How do I retrieve the exact item(s) that caused the change to be triggered?
Edit
Maybe the question isn't clear enough, I'll give an example.
class Foo {
private StringProperty name = new SimpleStringProperty();
public final StringProperty nameProperty() { return name; }
public final String getName() { return name.get(); }
public final void setName(String n) { name.set(n); }
public Foo(String fooName) { setName(fooName); }
}
// Creates an ObservableList with an extractor
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);
fooList.addListener(new ListChangeListener<Foo>() {
public void onChanged(Change<Foo> c) {
while (c.next()) {
if (c.wasUpdated()) {
// One or more of the elements in list has/have an internal change, but I have no idea which element(s)!
}
}
}
});
fooB.setName("Mickey");
fooB.setName() will trigger a change in the ListChangeListener, which the wasUpdated() condition would return true. However, I have no way to know that it is fooB which has changed within the listener.
This may seem trivial, but I have a map application where the list stores the things which the map has to render. When one of the item changes its position (i.e. lat/long), I need to re-plot on the map. If I have no idea which item has changed location, I'll have to redraw everything that I already have.
You can get the index(es) of the item(s) that were changed, which gives you some useful information:
import javafx.beans.Observable;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener.Change;
import javafx.collections.ObservableList;
public class ListUpdateTest {
public static void main(String[] args) {
ObservableList<Foo> fooList = FXCollections.observableArrayList(foo -> new Observable[] { foo.nameProperty() });
Foo fooA = new Foo("Hello");
Foo fooB = new Foo("Kitty");
fooList.add(fooA);
fooList.add(fooB);
fooList.addListener((Change<? extends Foo> c) -> {
while (c.next()) {
if (c.wasUpdated()) {
int start = c.getFrom() ;
int end = c.getTo() ;
for (int i = start ; i < end ; i++) {
System.out.println("Element at position "+i+" was updated to: " +c.getList().get(i).getName() );
}
}
}
});
fooB.setName("Mickey");
}
public static class Foo {
private StringProperty name = new SimpleStringProperty();
public final StringProperty nameProperty() { return name; }
public final String getName() { return name.get(); }
public final void setName(String n) { name.set(n); }
public Foo(String fooName) { setName(fooName); }
}
}
Note that you can't determine from the list change event the actual properties that changed in those list elements (so, if your extractor pointed to two or more properties, there's no way to find which of those properties changed), and there is no way to get the previous value. This may be enough for your use case, though.
Straight from the docs.
Typical usage is to observe changes on an ObservableList in order to hook or unhook (or add or remove a listener) or in order to maintain some invariant on every element in that ObservableList. A common code pattern for doing this looks something like the following:
ObservableList theList = ...;
theList.addListener(new ListChangeListener<Item>() {
public void onChanged(Change<tem> c) {
while (c.next()) {
if (c.wasPermutated()) {
for (int i = c.getFrom(); i < c.getTo(); ++i) {
//permutate
}
} else if (c.wasUpdated()) {
//update item
} else {
for (Item remitem : c.getRemoved()) {
remitem.remove(Outer.this);
}
for (Item additem : c.getAddedSubList()) {
additem.add(Outer.this);
}
}
}
}
});
}

How do I access variables from the main class from another class (java)?

I'm making a cookie clicker clone in java to practice my java skills and I have a small problem, I have variables that are declared in the main method that I want to access from an ActionListener class. Here is some sample code from the ActionListener class. the the int variables (ex. clicks, grandamaCost) and the JTextFields (ex. display, cpsDisplay) are all in the main method. I was wondering how I could have access to variables in the main method so that this code could work in the other class. Thanks!
#Override
public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
button(b.getText());
}
public void button(String input) {
switch (input) {
case "Cookie":
clicks++;
display.setText("Cookies: " + clicks + "");
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy grandma":
if (clicks >= grandmaCost) {
grandmas++;
clicks = clicks - grandmaCost;
grandmaCost = (int) ((.15 * grandmaCost) + grandmaCost);
cps++;
}
display.setText("Cookies: " + clicks + "");
prices[0].setText("$" + grandmaCost);
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy monkey":
if (clicks >= monkeyCost) {
monkeys++;
clicks = clicks - monkeyCost;
monkeyCost = (int) ((.15 * monkeyCost) + monkeyCost);
cps = cps + 2;
}
display.setText("Cookies: " + clicks + "");
prices[1].setText("$" + monkeyCost);
cpsDisplay.setText("CPS: " + cps);
break;
case "Buy Teemo":
if (clicks >= teemoCost) {
teemos++;
clicks = clicks - teemoCost;
teemoCost = (int) ((.15 * teemoCost) + teemoCost);
cps = cps + 3;
}
display.setText("Cookies: " + clicks + "");
prices[2].setText("$" + teemoCost);
cpsDisplay.setText("CPS: " + cps);
break;
}
}
}
Your variables should be fields.
Fields are declared outside of a class's methods and are usually found right below the class declaration. Fields can be accessed by all methods of a class.
They can also be accessed from other classes (unless they are private) using the dot operator.
If a field is marked with static, its class name is used to reference it.
If a field is not static, an object of its class is used to reference it.
Example
public class Man {
public String name; //this is a field
public static String gender = "Male"; //this is a static field
public Man(String newName) {
name = newName; //assigns the value of a field from within a method
}
}
and another class...
public class Main {
public static void main(String[] args) {
Man bob = new Man("Bob");
System.out.println(bob.name); //referenced from object, prints Bob
System.out.println(Man.gender); //referenced from class name, prints Male
}
}
And to have more control over the access of your fields, you can use getters and setters. Take a read!
public class ActionClass {
{
private static int clicks;
#Override
public void actionPerformed(ActionEvent e) {
clicks++;
}
public static void setClicks(int c){
clicks = c;
}
public static int getClicks(){
return clicks;
}
}
public class AnyClass {
{
// now you have access to your clicks count .
int clicks = ActionClass.getClicks();
// set value of clicks
ActionClass.setClicks(0);
}
Here, I will give you an example for exactly what you need. In this code you simply just need to set anything you would like to add to actionPerformed as static.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class testJava implements ActionListener {
protected static JButton b; // since this is static you can
// now access it in other classes
public static void main(String[] args) {
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == b) {
// do stuff here
}
}
}
You would have to make the variables public class variables instead of method variables, thereby increasing the scope and visiblity of the variables. Like so:
public class ActionClass {
{
public string MyPublicVariable = "woot";
#Override
public void actionPerformed(ActionEvent e) {
...
}
}
A more popular/recommended way to do this is to use a getter/setter instead of making the variable explicitly public. You would access a private variable through public methods like so:
public class ActionClass {
{
#Override
public void actionPerformed(ActionEvent e) {
private string MyPublicVariable = "woot";
public void setMyString(string newString){
MyPublicVariable = newString;
}
public string getMyString(){
return MyPublicVariable;
}
}
}
This way, you have more control over what your variables are set to.
Using fields and their accessor methods. An example here.
You can pass main class instance reference to another class instance, or register callback.
For the first way
Class MainClass {
private int mValue;
public void init() {
AnotherClass cla = new AnotherClass(this);
}
public void setValue(int value) {mValue = value;}
public int getValue(){return mValue;}
}
Class AnotherClass {
private MainClass mMain;
public AnotherClass(MainClass ref) {
mMain = ref;
}
public void controlValue() {
if (mMain != null) {
mMain.setValue(1);
mMain.getValue();
}
}
}
For the second way
1. declare an interface
2. implement this interface in main class
3. register this implementation to another class.
4. get and set value in another class.
public interface ClassListener {
public void setValue(int value);
public int getValue();
}
public class MainClass implements ClassListener{
private int mValue;
public void registerListener() {
AnotherClass cla = new AnotherClass();
cla.registerListener(this);
}
#Override
public void setValue(int value) {
// TODO Auto-generated method stub
mValue = value;
}
#Override
public int getValue() {
// TODO Auto-generated method stub
return mValue;
}
}
public class AnotherClass{
private ClassListener mListener;
public void registerListener(ClassListener listener) {
mListener = listener;
}
public void controlValue() {
if (mListener != null) {
int value = mListener.getValue();
mListener.setValue(++value);
}
}
}

Binding issue between POJO and JavaFX components

Currently, what I want to do is use JAXB generated POJO to bind every Java properties to JavaFX components. To do that, I proceeded as followed :
I changed the default generation of JAXB to add PropertyChangeSupport to make POJO support binding.
I created a kind of factory which take a class instance at input and return a Map where the key is the property itself and the value the JavaFX component binded with the value of the property.
The returned map is displayed in a JFXPanel.
Here's a sample of my factory :
public static Map<Field, Node> createComponents(Object obj) throws NoSuchMethodException
{
Map<Field, Node> map = new LinkedHashMap<Field, Node>();
for (final Field field : obj.getClass().getDeclaredFields())
{
#SuppressWarnings("rawtypes")
Class fieldType = field.getType();
if (fieldType.equals(boolean.class) || (fieldType.equals(Boolean.class))) //Boolean
{
map.put(field, createBool(obj, field));
}
else if (fieldType.equals(int.class) || (fieldType.equals(Integer.class))) //Integer
{
map.put(field, createInt(obj, field));
}
else if (fieldType.equals(BigInteger.class)) //BigInteger
{
map.put(field, createBigInt(obj, field));
}
else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) //Long
{
map.put(field, createLong(obj, field));
}
else if (fieldType.equals(String.class)) //String
{
map.put(field, createString(obj, field));
}
...
}
return map;
}
public static Node createBool(Object obj, final Field field) throws NoSuchMethodException
{
System.out.println(field.getType().getSimpleName() + " spotted");
JavaBeanBooleanProperty boolProperty = JavaBeanBooleanPropertyBuilder.create().bean(obj).name(field.getName()).build();
boolProperty.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2)
{
prettyPrinter(field, arg1, arg2);
}
});
CheckBox cb = new CheckBox();
cb.setText(" : " + field.getName());
cb.selectedProperty().bindBidirectional(boolProperty);
return cb;
}
public static Node createInt(Object obj, final Field field) throws NoSuchMethodException
{
System.out.println(field.getType().getSimpleName() + " spotted");
JavaBeanIntegerProperty intProperty = JavaBeanIntegerPropertyBuilder.create().bean(obj).name(field.getName()).build();
StringProperty s = new SimpleStringProperty();
StringConverter sc = new IntegerStringConverter();
Bindings.bindBidirectional(s, intProperty, sc);
s.addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> arg0, String arg1, String arg2)
{
prettyPrinter(field, arg1, arg2);
}
});
TextField tf = new TextField();
tf.textProperty().bindBidirectional(s);
return tf;
}
So, the problem I have is : In the most case when I change, for example, a textField the POJO property doesn't notice. But in some case, when I change the order of the fields in the POJO every listener will notice any change.
Here's an example of what the GUI looks like with the followed Personne class (which currently works)
public class Personne
{
private int taille;
private Boolean lol;
private long pointure;
private BigInteger age;
private boolean zombified;
private String name;
private PropertyChangeSupport _changeSupport = new PropertyChangeSupport(this);
public Boolean getLol()
{
return this.lol;
}
public long getPointure()
{
return this.pointure;
}
public int getTaille()
{
return taille;
}
public boolean getZombified()
{
return zombified;
}
public BigInteger getAge()
{
return age;
}
public String getName()
{
return name;
}
public void setPointure(long pointure)
{
final long prev = this.pointure;
this.pointure = pointure;
_changeSupport.firePropertyChange("pointure", prev, pointure);
}
public void setTaille(int taille)
{
final int prev = this.taille;
this.taille = taille;
_changeSupport.firePropertyChange("taille", prev, taille);
}
public void setAge(BigInteger age)
{
final BigInteger prev = this.age;
this.age = age;
_changeSupport.firePropertyChange("age", prev, age);
}
public void setName(String name)
{
final String prev = this.name;
this.name = name;
_changeSupport.firePropertyChange("name", prev, name);
}
public void setLol(Boolean lol)
{
final Boolean prev = this.lol;
this.lol = lol;
_changeSupport.firePropertyChange("lol", prev, lol);
}
public void setZombified(boolean zombified)
{
final boolean prev = this.zombified;
this.zombified = zombified;
_changeSupport.firePropertyChange("zombified", prev, zombified);
}
public void addPropertyChangeListener(final PropertyChangeListener listener)
{
_changeSupport.addPropertyChangeListener(listener);
}
}
I'm wondering how can the property order influence the binding like that. Furthermore, I noticed that if I want to return my nodes wrapped in HBox the binding doesn't work no more.
I think that I'm doing someting wrong, but I can't figure out what.
Your JavaBeanIntegerProperty and JavaBeanBooleanProperty are being garbage collected too early.
The method Property.bind(Observable) makes the property hold a strong reference to the observable, but the observable only holds a weak reference to the property! (it registers a Listener on the Observable that only has a WeakReference back to the Property). Likewise, when you call Bindings.bindBidirectional(Property, Property), both properties hold weak references to each other! This is an extremely important detail that is hard to find in the documentation.
If you only ever interact with JavaFX objects, this is not a problem because a JavaFX object naturally holds strong references to all its Properties. But if you are using JavaBeanIntegerProperty to wrap a bean property from a legacy object, then the bean does not hold a strong reference to the JavaBeanIntegerProperty, so after gc the Property will disappear and stop updating the bean! I think this is a design bug in the JavaBeanIntegerProperty.
The solution is to assign the JavaBeanIntegerProperty to a field and store it for as long as you want the binding to keep updating the bean.
Alternatively, you can write your own Property subclasses that do something to ensure that a strong reference exists from the bean to the Property (e.g. addPropertyChangeListener to the bean to listen forever).

Cannot access JList items in custom property editor

I have a simple OutlineView in the NetBeans editor area that shows two columns. The content of the cells of the second column shall be settable with a custom property editor via the PropertySupport. The custom property editor contains a JList that allows multiple selection of items.
The PropertySupport class looks like
public class CityProperty extends PropertySupport.ReadWrite<String> {
Customer c;
public CityProperty(Customer c, HashMap<String, Boolean> optionalCities) {
super("city", String.class, "City", "Name of City");
setValue("labelData", optionalCities);
this.c = c;
}
#Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return c.getCity();
}
#Override
public PropertyEditor getPropertyEditor() {
return new CityPropertyEditor(c);
}
#Override
public void setValue(String newValue) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
c.setCity(newValue);
}
}
The PropertyEditor looks like
public class CityPropertyEditor extends PropertyEditorSupport implements ExPropertyEditor {
Customer c;
PropertyEnv env;
public CityPropertyEditorPanel editor = null;
public CityPropertyEditor(Customer c) {
this.editor = new CityPropertyEditorPanel();
this.c = c;
}
#Override
public String getAsText() {
String s = (String) getValue();
if (s == null) {
return "No City Set";
}
return s;
}
#Override
public void setAsText(String s) {
setValue(s);
}
#Override
public void attachEnv(PropertyEnv env) {
this.env = env;
}
#Override
public Component getCustomEditor() {
HashMap<String, Boolean> cities = (HashMap<String, Boolean>) env.getFeatureDescriptor().getValue("labelData");
DefaultListModel model = new DefaultListModel();
/* selection in the gui */
int[] selectedIdxs = new int[cities.size()];
int idx = 0;
for (String str : cities.keySet()) {
model.addElement(str);
if (cities.get(str) == Boolean.FALSE) {
selectedIdxs[idx] = model.indexOf(str);
idx++;
}
}
if (selectedIdxs.length > 0){
editor.jList.setSelectedIndices(selectedIdxs);
}
editor.jList.setModel(model);
return editor;
}
#Override
public boolean supportsCustomEditor() {
return true;
}
#Override
public Object getValue() {
System.out.println("getValue(): " + editor.jList.getSelectedValuesList());
System.out.println("getValue(): " + editor.jtf.getText());
return super.getValue();
}
}
and the editor CityPropertyEditorPanel() itself is a simple JPanel with a JList and a JTextField.
My codes creates a nice custom editor with all the items listed, but it is not returning the new selected items from the list. My question is now, how do I get the selected items from the JList back to the CityProperty class? My try was to use
editor.jList.getSelectedValuesList());
in the getValue() method but the result is always empty. The same for the JTextField, where a new written value is also not transferred back.
What Am I doing wrong here?
I think I found a solution/workaround.
The CityPropertyEditor recognized the content of the "editor" object when I activated the PropertyEnv.STATE_NEEDS_VALIDATION feature. The code then in CityPropertyEditor should have to override the attacheEnv method and include the VetoableChangeListener
#Override
public void attachEnv(PropertyEnv env) {
this.env = env;
env.setState(PropertyEnv.STATE_NEEDS_VALIDATION);
env.addVetoableChangeListener(new VetoableChangeListener() {
#Override
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
/* User has pushed OK */
for (Entry entry : editor.isoValNew.entrySet()){
isoVal.put((Double) entry.getKey(), (Boolean) entry.getValue());
}
}
});
}
while the Jlist in the CityPropertyEditorPanel() itself has a ListSelectionListener who updates the Map variable isoValNew
isoValueList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
isoValNew.clear();
for (Object obj : isoValueList.getSelectedValues()) {
isoValNew.put((Double) obj, Boolean.TRUE);
}
}
});
I'm sure this is not a perfect solution, but it works fine in my case.
Hope this helps someone.

Categories