My question is conceptual about synchronizing data and events in programming a gui. (This example shows batch state being the facilitator of taking classes that implement the same interface and dynamical updating cells in two different frames.This code is where I got my idea. )
I am assuming that I will create new instances of this batch state object specifically in the classes where an event is triggered(panel) and the reaction to that event(another panel) . I will do this by adding the classes that need to communicate to the a list of bsListeners. Then call the batch state function like "setSelectedCell()" to iterate over each class to synchronize them.
The Problem
This would work perfect if the object both shared the same arrayList but since they are both new instances they don't. I tried changing things to static and it is freaking out especially in the interface. Is this approach logical I am brand new to programming gui's? Sorry this is a novel.
interface BatchStateListener {
public void valueChanged(Cell cell, String newValue);
public void selectedCellChanged(Cell newSelectedCell)
}
class BatchState {
private String[][] values;
private Cell selectedCell;
private List<BatchStateListener> listeners;
public BatchState(int records, int fields) {
values = new String[records][fields];
selectedCell = null;
listeners = new ArrayList<BatchStateListener>();
}
public void addListener(BatchStateListener l) {
listeners.add(l);
}
public void setValue(Cell cell, String value) {
values[cell.record][cell.field] = value;
for (BatchStateListener l : listeners) {
l.valueChanged(cell, value);
}
}
public String getValue(Cell cell) {
return values[cell.record][cell.field];
}
public void setSelectedCell(Cell selCell) {
selectedCell = selCell;
for (BatchStateListener l : listeners) {
l.selectedCellChanged(selCell);
}
}
public Cell getSelectedCell() {
return selectedCell;
}
}
My questions was a bit confusing, but I came to my answer. I was just wondering how to implement this BatchState class in my code. I found that if I make it in main and pass it to the constructors frames/panels that need to communicate with each other they all can share reference to it.
Related
I'm building a Java Swing class called ListView that attempts to be a general purpose list.
public class ListView<T> extends JPanel {
private IListViewDataSource<T> dataSource;
private JPanel list;
public ListView(IListViewDataSource<T> dataSource, Dimension dimension) {
this.dataSource = dataSource;
list = new JPanel(new GridLayout(0, 1));
this.add(new JScrollPane(list));
this.setPreferredSize(dimension);
}
public void loadRows() {
for (int i = 0; i < dataSource.getNumberOfElements(); i++) {
JLabel label = new JLabel(dataSource.getTitleOfElement(dataSource.getElementAtPosition(i)));
list.add(label);
}
}
}
In order to do this, I declared an interface called IListViewDataSource that defines the methods required for the list view to obtain its data.
public interface IListViewDataSource<T> {
T getElementAtPosition(int position);
int getNumberOfElements();
String getTitleOfElement(T element);
}
I wanted it to be possible to instantiate a new ListView with whichever DataSource you declare, in order to introduce whichever data in the list. So far so good.
Now, I'm building another class called OfferListView that extends ListView, and in order not to have an inneccessary extra file I wanted it to implement its own ListViewDataSource. The problem is that I can't call super(this, dimension) inside the constructor for this new class, as I'm then told that this can't be used before the superclass constructor has been called.
This "pattern" is what is used when programming with UIKit for iOS, and I think it's quite nice, but I can't get it to work in Java. How could I approach this?
Domain-View-Controller strategy was used in 90s on smaltalk to seperate view from domain and it is still being used in web-development.
Without writing all the classes for views etc, there are two ways for seperating view from domain.
(1st:) When view passes something to domain object then it keep polling to check for any additional changes. That means once a view object(a textfield, frame or anything else) has forwaded a request to domain it keeps checking after few seconds or minutes if something has changed. However this approach is not good.
(2nd:) The observer design pattern. When one thing changes it notifies automatically all listeners. Your view has to implement an interface and domain should provide a method for subscription for all objects which implement that interface. Here is an example and i did not compile it, However it clearly seperates view from domain.
public class View implements PropertyChangeListener {
private DomainObject object;
public View(DomainObject object) {
assert(object != null);
this.setObject(object);
}
public void enterText(String text) {
this.getObject().update(text);
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("string_updated"))
System.out.println("New value is " + evt.getNewValue());
}
public DomainObject getObject() {
return object;
}
public void setObject(DomainObject object) {
this.object = object;
}
}
Here is the domain class:
public class DomainObject {
private String text;
public DomainObject(String test) {
this.setText(test);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void update(String string) {
this.setText(string);
this.getListener().stream().forEach(e -> e.propertyChange(new PropertyChangeEvent(this,"string_updated","",this.getText())));
}
private ArrayList<PropertyChangeListener> listener;
public void subscribe(PropertyChangeListener listener) {
this.getListener().add(listener);
}
public ArrayList<PropertyChangeListener> getListener() {
return listener;
}
public void setListener(ArrayList<PropertyChangeListener> listener) {
this.listener = listener;
}
}
As i see, You are trying to have many views, if they are contained within eachother then use also Composite design pattern.
I have two combo-boxes as below,
whenever i click done button, i get the values from combo-box and store it in a object like below,
public class comboValues{
private String label1ComboString;
private String label2ComboString;
public String setLabel1Combo(String val){
this.label1ComboString = val;
}
public String setLabel2Combo(String val){
this.label2ComboString = val;
}
public void getLabel1Combo(){
return this.label1ComboString;
}
public void getLabel2Combo(){
return this.label2ComboString;
}
}
in a controller class i use,
comboValues obj = new comboValues();
obj.setLabel1Combo(label1ComboBox.getSelectionModel().getSelectedItem());
obj.setLabel2Combo(label2ComboBox.getSelectionModel().getSelectedItem());
For a design with two combo box the code looks simple. My doubt is what if the number of combo-boxes increases? with the above approach code will have
lot of lines. What is the design to overcome this problem and how can i implement that to this scenario?
You can have an array or an ArrayList of ComboBoxes. This way you can reference an arbitrary number of boxes. Your class would change to something like this:
public class ComboValues {
private String[] comboStrings;
...
public void setComboLabel(String label, int comboNum) {
comboStrings[comboNum] = label;
}
public void getComboLabel(int comboNum) {
return comboStrings[comboNum];
}
public void getComboBoxCount() {
return comboStrings.length;
}
}
...
String[] labels = ...
for (int i = 0; i < obj.getComboBoxCount(); i++) {
obj.setComboLabel(labels[i], i);
}
I can see from your approach that you want to add more combo-boxs and against it you want to do less code in java to handle those all.
You have option of implementing Array List collection and store multiple combo boxes inside this. so every time you will not be needed to create new object and it will become dynamic.
Hope it will clear your doubt. If you have not cleared please comment.
While creating my app. architecture I faced the need for one structure, that will be described below.
I'm pretty sure, that there is a well known design pattern with the same functionality, because I think that problem, for which I develop it is really common.
I write my own implementation of this, but I always try to use "build in language" implementations of patterns, so - please help me to name this construction.
The idea is close to reader-writer pattern. We have a "container" in which we can add Objects by the key (). And also we can get this objects by keys, removing it from container.
So, the implemented class should have two methods:
void putObject(Key key, Object object);
Object getObject(Key key); // remove <Key,Object> from container.
The next is most interesting.
This container should work in multi-threading environment as follows:
If there is no object associated with key, while calling get(Key
key) method the caller thread should WAIT for the object in this
container.
When another thread will call putObject(Key key, Object object)
method it should check if there is some thread that wait exactly for
this object, and if it is - then signal and wake up the thread that
waits.
I think that it is common structure, does it have "official" name?
My Java implementation of this pattern:
private static interface BlackBox {
public void addObject(IdObject object);
public IdObject getObject(ObjectId id);
}
private static class BlackBoxImpl implements BlackBox {
private final Lock conditionLock = new ReentrantLock();
private final Map<ObjectId, IdObject> savedObjects;
private final Map<ObjectId, Condition> waitingConditions;
public BlackBoxImpl() {
this.savedObjects = new ConcurrentHashMap<ObjectId, IdObject>(20);
this.waitingConditions = new ConcurrentHashMap<ObjectId, Condition>(20);
}
#Override
public void addObject(IdObject object) {
savedObjects.put(object.getId(), object);
if (waitingConditions.containsKey(object.getId())) {
Condition waitCondition = waitingConditions.get(object.getId());
conditionLock.lock();
waitCondition.signal();
conditionLock.unlock();
}
}
#Override
public IdObject getObject(ObjectId id) {
if (savedObjects.containsKey(id)) {
return savedObjects.get(id);
} else {
conditionLock.lock();
Condition waitCondition = conditionLock.newCondition();
waitingConditions.put(id, waitCondition);
waitCondition.awaitUninterruptibly();
conditionLock.unlock();
return savedObjects.get(id);
}
}
}
private static interface IdObject {
public ObjectId getId();
}
private static class IdObjectImpl implements IdObject {
protected final ObjectId id;
public IdObjectImpl(ObjectId id) {
this.id = id;
}
#Override
public ObjectId getId() {
return id;
}
}
private static interface ObjectId {
}
private static class ObjectIdImpl implements ObjectId {
}
I would probably use something like a
ConcurrentMap<K,BlockingQue<V>>.
Use the concurrent methods of the Map to add the pair. Take from your queue for the value. Use an ArrayBlockingQue(1).
Something like this perhaps:
static class MultiQueue<K, V> {
// The base structure.
final ConcurrentMap<K, BlockingQueue<V>> queues = new ConcurrentHashMap<>();
/**
* Put an item in the structure.
*
* The entry in the map will be created if no entry is currently there.
*
* The value will then be posted to the queue.
*/
public void put(K k, V v) throws InterruptedException {
// Make it if not present.
ensurePresence(k).put(v);
}
/**
* Get an item from the structure.
*
* The entry in the map will be created if no entry is currently there.
*
* The value will then be taken from the queue.
*/
public void get(K k) throws InterruptedException {
// Make it if not present - and wait for it.
ensurePresence(k).take();
}
private BlockingQueue<V> ensurePresence(K k) {
// Make it if not present.
return queues.computeIfAbsent(k, v -> new ArrayBlockingQueue(1));
}
}
Looking at your design, to me what you are describing
We have a "container" in which we can add Objects by the key (). And also we can get this objects by keys, removing it from container.
This container should work in multi-threading environment
is close to concurrent Object pool. It uses a set of initialized objects kept ready to use. A client of the pool will request an object from the pool and perform operations on the returned object.
The only real difference I see is that you are getting the objects based on your own criteria.
I have a problem with my app which uses JavaFX... In one view I have a tableview which contains list of people and I want change row style one person. Here is my code:
personTable.setRowFactory(new Callback<TableView<Person>, TableRow<Person>>() {
#Override
public TableRow<Person> call(TableView<Person> personTableView) {
return new TableRowRightFormat();
}
});
...
private class TableRowRightFormat extends TableRow {
#Override
protected void updateItem(Object o, boolean b) {
super.updateItem(o, b);
if(o == null) {
return;
}
getStyleClass().remove("headPerson");
if(((Person)o).getId()==2) {
getStyleClass().add("headPerson");
}
}
}
And it is working for one person(id=2) but when I scroll up my table and when person with id=2 disappears another person with id!=2 gets style called 'headPerson' (always one Person on visible elements in tableview has style 'headPerson', but above code is executing once time). What is the problem?
Update: I tested your code on both JavaFX 2.2 and JDK 8 and it seemed to work fine for my simple test case. The logic seems right; the one thing you have to be really careful of in these types of style-class based cell and row implementations is making sure you don't add multiple copies of a given string to the list of style classes - in your implementation this looks right. Double check and make sure you have the strings exactly the same in the add(...) and remove(...) methods.
I like to completely bullet-proof these at a slight cost to performance:
private final String headPersonStyleClass = "headPerson" ;
private class TableRowRightFormat extends TableRow<Person> {
#Override
protected void updateItem(Person p, boolean b) {
super.updateItem(p, b);
ObservableList<String> styleClass = getStyleClass();
if (p != null && p.getId()==2 && (! styleClass.contains(headPersonStyleClass))) {
styleClass.add(headPersonStyleClass);
} else {
// remove all occurrences:
styleClass.removeAll(Collections.singleton(headPersonStyleClass));
}
}
}
If you are using JavaFX 8, a better approach is to use a PseudoClass for this.
I seem not to grasp the concept of Events and such. After reading a while on how to implement the listeners and such I came across the Java tutorial saying I should extend AbstractListModel to get the data event firing. For some reason it still doesn't work.
Is there anything I'm doing wrong?
And what kind of code is expected at addListDataListener(ListDataListener l) for it to work? Since I don't understand that either.
public class CarComboBox extends AbstractListModel<Object> implements ComboBoxModel<Object> {
private JdbcRowSet jdbc;
private int size = 0;
private String selection;
public CarComboBox() {
try {
jdbc = new Query().getCarInfo();
jdbc.beforeFirst();
while (jdbc.next()) {
size++;
}
jdbc.beforeFirst();
}
catch (SQLException ex) {
System.err.println(ex.toString());
}
}
#Override
public void setSelectedItem(Object anItem) {
selection = (String) anItem;
}
#Override
public Object getSelectedItem() {
return selection;
}
#Override
public void addListDataListener(ListDataListener l) {
}
#Override
public void removeListDataListener(ListDataListener l) {
}
#Override
public int getSize() {
return size;
}
#Override
public String getElementAt(int index) {
try {
jdbc.absolute(index + 1);
return jdbc.getString(2);
}
catch (SQLException ex) {
System.out.println(ex.toString());
}
return null;
}
}
And to add a listener to the CarComboBox I do:
CarComboBox ccb = new CarComboBox();
ccb.addListDataListener(new ListDataListener()
I'm guessing that you are using the official tutorial.
However you should not touch ListModel and ComboBoxModel. Those are more advanced features you probably do not need.
The 4 examples in the tutorial do NOT use ListModel and ComboBoxModel.
If you use a standard JComboBox (no ListModel or ComboBoxModel), what happens is that when someone makes a selection, an ActionEvent is fired. This event is magically fired by Swing; you don't have to worry about how it is generated. However what is your responsibility is to have some (zero, one or more) objects being able to receive and do something about the ActionEvent:
public class MyClass implements ActionListener {
JComboBox comboBox = ...;
...
// You must register explicitly every ActionListener that you
// want to receive ActionEvent's from comboBox.
// Here we register this instance of MyClass.
comboBox.addActionListener(this);
...
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JComboBox) {
System.out.println("MyClass registered an ActionEvent from a JComboBox.");
System.out.println("Selected: " +
((JComboBox) e.getSource()).getSelectedItem());
}
}
}
Note that if you don't have any other ActionEvent's fired by different Swing components you
can skip the if (e.getSource() instanceof JComboBox) since you know your ActionEvent always comes from a JComboBox.
In my example the JComboBox is inside MyClass, but it does not have to be:
JComboBox comboBox = ...;
MyClass myClass = ...;
comboBox.addActionListener(myClass);
...
comboBox.addActionListener(someOtherActionListener);
You don't need to override addListDataListener() and removeListDataListener() method. The AbstractListModel already take care of the listeners. Here is the implementation of AbstractListModel.addListDataListener():
public void addListDataListener(ListDataListener l) {
listenerList.add(ListDataListener.class, l);
}
The idea of abstract classes is that they do most of the work for you. Usually you only need to implement abstract methods.
XXListener and XXModel are different sides of the coin: the former is the observer to the latter which is the observable. The listener registers itself to the model when it wants to get notified on changes. It's the responsibility of the model to
manage its listeners (that's typically handled already by the AbstractXXModel, as already explained by #userWhateverNumber ;)
fire the notifications if appropirate: that's the part a custom model must take over, in your case
like
#Override
public void setSelectedItem(Object item) {
selection = item;
fireContentChanged(this, -1, -1);
}
Arguably (there are personal preferences around :-) you often don't need custom model implementations but can just as well re-use the provided DefaultXXModels. In your context and assuming the content of the resultset is immutable it might be an option to fill the default model with the data at construction time, like
DefaultComboBoxModel model = new DefaultComboBoxModel();
forEachRowInResultSet {
model.addElement(resultSet.getString(2));
}
If, on the other hand, the content changes then your model implementation is invalid anyway: the model must notify its listeners whenever something had changed
Object one = model.getElementAt(index);
Object other = model.getElementAt(index)
if (!one.equals(other)) {
listener must have received a contentsChanged
}