Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I made this, basically the user can toggle options to be able to see them or not in the application, i wanted to know how i can improve this class. there are parts like SEARCH & MAP that only change the value in the map and nothing else, would be better to create an abstract class and extend for each type? TypeWithoutToggle (this will only change the value in the map for the type and implement empty #toggle)) TypeWithToggle.. then extend these depending.
public enum ToggleType {
NAME {
#Override
public void toggle(VideoPlayer videoPlayer) {
videoPlayer.doToggleName();
}
},
EDITOR {
#Override
public void toggle(VideoPlayer videoPlayer) {
if (videoPlayer.isTrue("EDITOR"))
videoPlayer.createEditors();
else
videoPlayer.deleteEditors();
}
},
SEARCH {
#Override
public void toggle(VideoPlayer videoPlayer) {
}
},
MAP {
#Override
public void toggle(VideoPlayer videoPlayer) {
// handle on {#link VideoPlayer#create()}
}
},
protected abstract void toggle(VideoPlayer videoPlayer);
public void run(VideoPlayer videoPlayer) {
videoPlayer.toggleMap.put(name(), !videoPlayer.isTrue(name()));
toggle(videoPlayer);
}
You should not expose the toggleMap attribute on VideoPlayer class. Instead the should be encapsulated as a method in VideoPlayer class.
It's difficult to give a more detailed comment only by looking at these few lines.
This question is mostly opinion based, but there are at least two things that I could mention:
First is you are coupling VideoPlayer with ToggleType. There should be a separate method, probably in VideoPlayer (or a VideoPlayerToggler), that is responsible for the toggle that accepts ToggleType.
Example:
switch(toggleType):
case NAME:
doToggleName()
break;
case EDITOR:
if (videoPlayer.isTrue("EDITOR"))
videoPlayer.createEditors();
else
videoPlayer.deleteEditors();
break;
...
Let's assume that you will add a new component that can be toggled, like a MenuComponent. So it might scale better, and decouples your code. With your approach, you would have to add another abstract method, that will handle your type. In short- ToggleType doesn't have to know what or how to toggle. There might be many toggle handlers depending on your environment, configuration or other factors.
Secondly if you put this method inside VideoPlayer, then you don't have to expose any methods, keep everything well encapsulated and private, which is a good idea in general.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm new to Java and development and don't know how to do most of the stuff. So I wanter to ask you guys how to check if an enum value changed. So I have this:
public enum GameState {
WAITING,
INTRO,
INTRO_WAIT,
INTRO_1,
INTRO_1_WAIT,
LOBBY_INTRO,
LOBBY,
INTRO_GAME1,
GAME1,
INTRO_GAME2,
GAME2;
}
So I want to know how to detect if an enum value changed from any of those to any of those. Hope you know what I'm try to say.
Thanks :)
I assume you mean that some other class has a field GameState state, and you want to know when it changes from one value to another.
There's not an "automatic" way to do that. Have that other class make that field be private (which is a good idea anyway), and any time it changes it (for instance, via a setState(GameState) method, it can perform whatever action you want — such as calling any GameStateListener that's been registered with that class, or whatever checking mechanism you want.
It might look something like this:
public interface GameStateListener {
void onChange(GameState changingFrom, GameState changingTo);
}
public class Game {
private GameState state = WAITING; // or whatever initial value
private final Collection<GameStateListener> listeners = new ArrayList<>();
public void registerListener(GameStateListener listener) {
listeners.add(listener);
}
public void changeState(GameState newState) {
for (GameStateListener listener : listeners) {
listener.onChange(state, newState);
}
this.state = newState;
}
...
}
Note that that code is not thread-safe, and making it be thread-safe would add a good deal of complexity. There are other ways to do it, too, but the above is a pretty standard pattern.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
So I've been looking over some java code that i understand is used for a foreach loop but it seems like it is overly complicated.
I have a Control.java file that contains properties.
I have a Controls.java file that uses Iterator and takes Control as the data type.
public class Controls implements Iterable<Control>{
protected ArrayList<Control> controls;
public Controls()
{
controls = new ArrayList<Control>();
}
public Controls(ArrayList<Control> controls)
{
this.controls = controls;
}
public ArrayList<Control> value()
{
return controls;
}
public void add(Control ctrl)
{
this.controls.add(ctrl);
}
public void add(Controls ctrls)
{
for(Control ctrl : ctrls)
{
this.controls.add(ctrl);
}
}
public void remove(Control ctrl)
{
if(this.controls.contains(ctrl))
{
this.controls.remove(ctrl);
} else
{
for (Control c: this.controls)
{
if(c instanceof ContainerControl)
{
((ContainerControl)c).controls.remove(ctrl);
}
}
}
}
public Control get(String name)
{
//stuff here
}
#Override
public Iterator<Control> iterator() {
return controls.iterator();
}
}
Other files use it as such:
public void dumpInstantiation(StringBuffer buf)
{
for(Control control : controls)
{
control.dumpInstantiation(buf);
}
}
To my understanding this is just a foreach loop with the added benefit of adding or removing (or calling any other method) as each control is iterated. As a java newbie a couple questions come to mind though:
Is there an easier way to implement this? Is this how it is usually done?
Is there any other benefits of doing it this way?
Is there a way to do this without ArrayList and Iterator?
Is there an easier way to implement this? Is this how it is usually done?
In order to use the Java foreach construct, your class needs to implement the Iterable interface, and provide enough functionality within the required methods to "iterate" over the list and return each item. Usually this means you need to know when there are items remaining and a way to return each one in step. The interface API will tell you if a method is "required" (ie: the method must be declared, but it can provide no implementation) or not. An easier method would be to leverage an already existing collection type, so you don't have to make your own.
Is there any other benefits of doing it this way?
It's a good way to provide a nice method to allow users to iterate over your list, and it makes the class compatible with other interfaces that operate on Iterable
Is there a way to do this without ArrayList and Iterator?
You could wrap your class in an existing collection that already implements iterator, but this will be up to you.
So, a for-each loop has two 'arguments'.
1. the variable to which is assigned the value of each item of an array one by one.
2. the array or ArrayList etc.
An example:
public class Test {
public static void main(String[] args) {
int[] numbers = new int[] {3,8,5,2};
for (int i : numbers)
System.out.println(i);
}
}
Prints:
3
8
5
2
You see, it's not that difficult!
And, instead of a normal array, you could use the ArrayList class to dynamically add/remove items:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(3);
numbers.add(8);
numbers.add(5);
numbers.add(2);
for (int i : numbers)
System.out.println(i);
}
}
Prints the same.
Did this answer your question?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So, I'm creating a snakes and ladders game in javafx, that asks a question when the player lands on a ladder or snake, and decides whether to go up the ladder/down the snake or not based on whether the answer is correct or not.
I have a Question class that creates a new window and displays the question, as well as a place to answer it, and a 'correct' boolean value that I am hoping to essentially, return to the main class, when the button is clicked.
Since EventHandlers cannot directly return values, I am hoping to say 'if the value of this 'correct' variable has changed, execute a getter method to get and store the value' but I don't know how to create a listener to check if the value has changed.
Any help would be appreciated!
I would do something like this:
public class Question {
public enum State {UNANSWERED, CORRECT, INCORRECT}
private final ReadOnlyObjectWrapper<State> state
= new ReadOnlyObjectWrapper<>(State.UNANSWERED);
public ReadOnlyObjectProperty<State> stateProperty() {
return state.getReadOnlyProperty() ;
}
public final State getState() {
return stateProperty().get();
}
private Button button ;
public Question() {
// ...
button = new Button(...);
button.setOnAction( event -> {
if (checkAnswer()) {
state.set(State.CORRECT);
} else {
state.set(State.INCORRECT);
}
});
// etc..
}
public void showWindow() {
// display window with question and controls, etc...
}
}
Then you can do
Question question = new Question();
question.stateProperty().addListener((obs, oldState, newState) -> {
if (state == Question.State.CORRECT) { /* ...*/}
else if (state == Question.State.INCORRECT) { /* ... */}
});
question.showWindow();
I don't know what type of listener you want but I found this for javafx changelistener at http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm. This might help you get started
package propertydemo;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.ChangeListener;
public class Main {
public static void main(String[] args) {
Bill electricBill = new Bill();
electricBill.amountDueProperty().addListener(new ChangeListener(){
#Override public void changed(ObservableValue o,Object oldVal,
Object newVal){
System.out.println("Electric bill has changed!");
}
});
electricBill.setAmountDue(100.00);
}
}
There is a great API built for Dialogs. It's going to become part of the official JavaFX API, but for now you can use the separate library:
Dialogs
Confirmation Dialog is probably the one you're looking for.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How can i change the virtual void Execute (vtkObject *caller, unsigned long eid, void *callData) function of the vtkCallbackCommand class (vtk) to java, thanks a lot, AMAL
Adding an callback method on a specific event is different from C++. As you can see in some vtk Java Exemple you don't have to create a class which extends from vtkCallbackCommand to rewrite the Execute Method.
To add specific behavior you have to use the Java AddObserver() method, It should be something like :
public class kbHandler
{
private vtkRenderWindowInteractor iren;
public static void main(String[] args) {
kbHandler kbh = new kbHandler();
kbh.doit();
}
void callbackHandler ()
{
// if i'm here, a key is pressed !!
// you can get back information from iren (which key : iren.GetKeyCode())
}
public void doit ()
{
// Do lot of things
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow(renWin);
// add observer for the handler arg1 = event to observe, arg2 object handler of the event, arg3: method to call
iren.AddObserver("CharEvent", this, "callbackHandler");
iren.Initialize();
iren.Start();
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
// AvgTemp.java
public abstract class AvgTemp {
// This function receives nottification from other Temperature Sensors
public AvgTemp() {
}
public void notifyReceived(String eventName, Object arg) {
if (eventName.equals("temperatureMeasurement"))
{
onNewtemperatureMeasurement((TempStruct) arg);
}
}
public abstract void onNewtemperatureMeasurement(TempStruct tempStruct);
}
For receiving notifications, AvgTemp.java file has to subscribe to a temperature sensor. It means I have to call subscribetemperatureMeasurement().
Now, my question is "Where should I call subscribetemperatureMeasurement() in AvgTemp.java file, so I can get notification from Sensor?"
Should I call subscribetemperatureMeasurement() function in the constructor of the AvgTemp class or in somewhere else?
Looks like your question is missing Sensor skeleton, I guess it looks like this:
public class Sensor {
public void subscribeTemperatureMeasurement(AvgTemp avgTemp) {
//keep avgTemp reference for later use
}
}
and you have a choice between:
public AvgTemp(Sensor sensor) {
sensor.subscribeTemperatureMeasurement(this);
}
or (somewhere outside):
AvtGemp avgTemp = SomeAvgTemp();
sensor.subscribeTemperatureMeasurement(avgTemp);
The former approach has several drawbacks:
introduces unnecessary coupling from AvgTemp to Sensor
what if you want to subscribe to several sensors, you provide first one as a constructor argument and the remaining using the latter approach?
this reference escapes from the constructor, very bad, your notifyReceived might get called before the object is fully initialized (especially because this is an abstract class)
the AvgTemp cannot live without a Sensor which seems to strict and makes testing harder (mocking/stubbing required)