I have in my app 2 bars : topBar, bottomBar.
Basically each one of them creates images and set there positions on the screen. in my app I added a new screen that suppose to be with different bar - Advanced, but with some identical logic.
public class TopBar {
public TopBar () {
initImageA();
initImageB();
initResultManager();
initBG();
initLines()
}
}
public class BottomBar {
public BottomBar () {
initBg();
initBox();
initCover();
initcolorsLine();
initMenu()
}
}
In my app I crate bar according to the state:
private TopBar mTopBar;
private Bottom mBottomBar;
if (mState == "normal"){
mTopBar = new TopBar();
mBottomBar = new Bottom();
}
else {
mTopBar = new AdvancedTopBar();
mBottomBar = new AdvancedBottomBar();
}
mTopBar.setTitle()
mTopBar.setMainImage();
mBottomBar.drawLines()
.
.
.
AdvancedTopBar
public class AdvancedTopBar extends TopBar {
public AdvancedTopBar () {
super();
removeImageA();
removeImageB();
removeResultManager();
removeBG();
removeLines();
}
private removeImageA() {
.
.
.
}
}
Is it the right way to use inherence for creating the AdvancedTopBar for some identical logic (3,4 members) and calling to parent super() whats triggers initializing of images and then I just remove them one by one and create my own images, I think it's wrong... what options do I have to use different types of bars by on instance?
Just one of the many possible approaches: have one class and pass a boolean switch value in the constructor.
public class TopBar {
public TopBar(boolean advanced) {
doCommonStuff();
if (advanced) {
doAdvancedStuff();
}
}
}
So new TopBar(true) will give you an advanced bar, new TopBar(false) a standard one.
Related
As you can see from the image below I want to select something from my table ( which changes whenever I press a button from the vertical box to the left i.e "Overview", "Orders" ... ) and delete the record from an array ( i.e. where the content comes from ).
The method I approached bellow works but it is not elegant since I have to create at most 8 if statements for each button id. Is there any way to delete the content dynamically. Is there any way for the JVM to figure out which record belongs to which array list?
TableController
#FXML
private TableView<Object> defaultTableView;
public void delete(){
if( MockServer.getServer().currentButton.equals("btnIngredients"))
MockServer.getServer().removeIngredient(defaultTableView.getSelectionModel().getSelectedItem());
else if ( MockServer.------.equals("btnOrders"))
MockServer.getServer().removeOrder(defaultTableView.getSelectionModel().getSelectedItem());
}
Controller
#FXML
private TableController tableController;
#FXML
public void deleteRecord(ActionEvent event){
tableController.delete();
}
MockServer
public class MockServer implements ServerInterface {
public Restaurant restaurant;
public ArrayList<Dish> dishes = new ArrayList<Dish>();
public ArrayList<Drone> drones = new ArrayList<Drone>();
public ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
public ArrayList<Order> orders = new ArrayList<Order>();
public ArrayList<Staff> staff = new ArrayList<Staff>();
public MockServer(){}
public ArrayList<Ingredient> getIngredients() { return this.ingredients; }
public ArrayList<Order> getOrders() { return this.orders; }
public ArrayList<Staff> getStaff() { return this.staff; }
....
static public ServerInterface getServer(){
return server;
}
#Override
public void removeIngredient(Ingredient ingredient) {
int index = this.ingredients.indexOf(ingredient);
this.ingredients.remove(index);
this.notifyUpdate();
}
}
This pseudocode will need refactoring since I don't have all the code that you are using but I wish that you will get the general idea
Ok I believe that in the button click code you have to tell your mock server which list is currently used try adding this to the mock server
List currentList = null;
public void setCurrentList(String listName) { // you can use integer but the best is to use enum type setCurrentList(enum) this way you will get tapeSafety
switch(listName){
case "ingredients" : currentList = ingredients ; break;
//other cases
default : throw new Exception(" list not referred error with key value"+listName);
}
}
public void delete(Object o){
int index = this.currentList.indexOf(o);
this.currentList.remove(index);
}
now you can update you controller delete as bellow
public void delete(){
MockServer.getServer().delete(defaultTableView.getSelectionModel().getSelectedItem());
}
Why this should work?
you have to know that there is a good practice that says code to an interface, not an implementation
As you know List in java is an interface so when I assigned the ingredients object this interface will reference the same ArrayList as the object and it will take all it behaviours (how to search for an ingredient object etc...) this way when we will use the currentList on runtime after a button click we are sure that the currentList will be the same as the clicked list and pointing to the same list in the memory
Wish this simple and really resume explanation could help you
I'm using the java game engine made by thebennybox to create my own engine. Previously I worked with UE4 where you could have Static Mesh Actors, in his engine this would probably be a GameObject with a MeshRenderer component attached to it:
GameObject staticMeshActor_Grass = new GameObject();
AddObject(staticMeshActor_Grass.addComponent(new MeshRenderer(
new Mesh("plane.obj"), new Material(
new Texture("T_Grass_BC.png"), 1, 8,
new Texture("T_Grass_N.png")))));
Now I'm trying to create a large field of these grass tiles but since these are all their individual GameObjects (or Actors in UE4 terms) after 16x16 tiles it starts to cripple the frame rate!
I believe I can solve this problem if I make instances of multiple static meshes inside one GameObject in order to make it performance friendly. In UE4 this feature is called 'Instanced Static Mesh Component' which allows for that and I would like to have something similar.
Here's the GameObject class made by thebennybox:
public class GameObject
{
private ArrayList<GameObject> m_children;
private ArrayList<GameComponent> m_components;
private Transform m_transform;
private CoreEngine m_engine;
public GameObject()
{
m_children = new ArrayList<GameObject>();
m_components = new ArrayList<GameComponent>();
m_transform = new Transform();
m_engine = null;
}
public GameObject AddChild(GameObject child)
{
m_children.add(child);
child.SetEngine(m_engine);
child.GetTransform().SetParent(m_transform);
return this;
}
public GameObject AddComponent(GameComponent component)
{
m_components.add(component);
component.SetParent(this);
return this;
}
public void InputAll(float delta)
{
Input(delta);
for(GameObject child : m_children)
child.InputAll(delta);
}
public void UpdateAll(float delta)
{
Update(delta);
for(GameObject child : m_children)
child.UpdateAll(delta);
}
public void RenderAll(Shader shader, RenderingEngine renderingEngine)
{
Render(shader, renderingEngine);
for(GameObject child : m_children)
child.RenderAll(shader, renderingEngine);
}
public void Input(float delta)
{
m_transform.Update();
for(GameComponent component : m_components)
component.Input(delta);
}
public void Update(float delta)
{
for(GameComponent component : m_components)
component.Update(delta);
}
public void Render(Shader shader, RenderingEngine renderingEngine)
{
for(GameComponent component : m_components)
component.Render(shader, renderingEngine);
}
public ArrayList<GameObject> GetAllAttached()
{
ArrayList<GameObject> result = new ArrayList<GameObject>();
for(GameObject child : m_children)
result.addAll(child.GetAllAttached());
result.add(this);
return result;
}
public Transform GetTransform()
{
return m_transform;
}
public void SetEngine(CoreEngine engine)
{
if(this.m_engine != engine)
{
this.m_engine = engine;
for(GameComponent component : m_components)
component.AddToEngine(engine);
for(GameObject child : m_children)
child.SetEngine(engine);
}
}
}
The AddObject() method shown in the first part comes from an abstract class and eventually calls the method AddChild(GameObject child) inside the GameObject class. As you can see we have an ArrayList of GameObjects and GameComponents. Now I would have to implement some method in order to support the creation of multiple mesh instances inside one GameObject.
I've already tried to add multiple MeshRenderer components to one GameObject but this didn't work out. Maybe someone has a suggestion how I might go about this?
if you're really interested and want to help me you can download the engine here: https://github.com/BennyQBD/3DGameEngine
Just use 'Open Projects From File System..' in eclipse, choose the directory of this folder and once you've done that you should be able to run the program.
Thanks a lot for your help!
this might be what you are looking for:
http://www.java-gaming.org/topics/issues-with-batching-meshes/37809/view.html
They mention that ThinMatrix has created a tutorial about instancing meshes, hope this helps you!
I am implementing the frontend of an application in GWT (see attached picture) and I have view class which is getting bigger as more widgets are added to the frontend.
As stated in GWT tutorial, the view class must implement the Display interface of the presenter class. y problem is I have a lot a methods in that interface and as I implement them in the view class, it becomes too big. That's why I would like to refactor the code to reduce the size of the view class by implementing those methods in others
classes and reference them where needed in the view class;for instand by grouping them per group box (one class per group box).
Below is a sample code: Note that in the real application we have more widgets per group box.
The problem I am facing will be well explained as you read through the whole posting because I will be adding more details.
code to be refactored:
ContactPrewsenter.java
public class ContactPresenter {
public interface Display
{
void methodA();
void methodB();
void methodC();
void methodD();
void methodE();
void methodF();
.
.
.
void methodM();
}
public ContactPresenter()
{
//Some stuff here
}
......
......
#Override
public void bind(){
//Some stuff here
}
}
ContactView.java:
public class ContactView implements ContactPresenter.Display
{
private final Listbox listBoxA;
private final Listbox listBoxB;
private final Listbox listBoxC;
private final Listbox listBoxD;
private final Listbox listBoxE;
private final Listbox listBoxF;
private final Listbox listBoxG;
private final Listbox listBoxH;
private final Listbox listBoxI;
private final Listbox listBoxJ;
private final Listbox listBoxK;
private final Listbox listBoxL;
private final Listbox listBoxM;
public ContactView()
{
listBoxA = new ListBox();
listBoxB = new ListBox();
VerticalPanel vPanel1= new VerticalPanel();
vPanel1.add(listBoxA);
vPanel1.add(listBoxB);
GrooupBox groupBox1 = new GroupBox();
groupBox1.add(vPanel1);
listBoxC = new ListBox();
listBoxD = new ListBox();
VerticalPanel vPanel2 = new VerticalPanel();
vPanel2.add(listBoxC);
vPanel2.add(listBoxD);
GrooupBox groupBox2 = new GroupBox();
groupBox2.add(vPanel2);
listBoxE = new ListBox();
listBoxF = new ListBox();
VerticalPanel vPanel3 = new VerticalPanel();
vPanel3.add(listBoxE);
vPanel3.add(listBoxF);
GrooupBox groupBox3 = new GroupBox();
groupBox3.add(vPanel3);
listBoxE = new ListBox();
listBoxF = new ListBox();
VerticalPanel vPanel4 = new VerticalPanel();
vPanel4.add(ListBoxE);
vPanel4.add(ListBoxF);
....
GrooupBox groupBox3 = new GroupBox();
groupBox3.add(vPanel4);
listBoxG = new ListBox();
listBoxH = new ListBox();
....
VerticalPanel vPanel = new VerticalPanel();
vPanel.add(ListBoxG);
vPanel.add(ListBoxH);
....
GrooupBox groupBox4 = new GroupBox();
groupBox4.add(vPanel);
......
//create Horizontal/vertical panels, docklayout panel as well, to position the group boxes on the gui
....
}
#Override
void methodA(){
//uses listBoxA
}
#Override
void methodB(){
//used listBoxB
}
#Override
void methodC(){
//uses listBoxC
}
#Override
void methodD(){
//uses listBoxD
}
#Override
void methodE(){
//uses listBoxE
}
#Override
void methodF(){
//uses listBoxF
}
#Override
void methodG(){
//uses listBoxG
}
#Override
void methodH(){
//uses listBoxH
}
.
.
.
#Override
void methodM(){
//uses listBoxM
}
}
I have tried as follows:
ContactPreseter.java
public class ContactPresenter
{
public interface Display extends groupBox1View.Display, groupBox2View.Display, groupBox3View.Display, groupBox4View.Display
{
}
}
preseter classes of each group box
public class groupBox1Presenter
{
public interface Display
{
void methodA();
void methodB();
}
}
public class groupBox2Presenter
{
public interface Display
{
void methodC();
void methodD();
}
}
public class groupBox3Presenter
{
public interface Display
{
void methodE();
void methodF();
}
}
public class groupBox4Presenter
{
public interface Display
{
void methodG();
void methodH();
}
}
ContactView.java
public abstract class ContactView implements ContactPresenter.Display
{
// adds group boxes to horizontal/vertical panels, and docklayout panel
}
Below are the view classes for each group box:
But here I eclipse forces me to implement all the methods of the interface ContactPresenter.Display in each of these classes whereas , I wanted it to be the way you see implemented here.
I was wondering if there were a way to play with access modifiers in order to achieve that ? If not, please I would you to help with ideas how to do it ?
public groupBox1View extends ContactView implements groupBox1Presenter
{
public groupBox1View()
{
}
#Override
void methodA(){
//uses listBoxA
}
#Override
void methodB(){
//used listBoxB
}
}
public groupBox2View extends ContactView implements groupBox2Presenter
{
public groupBox2View()
{
}
#Override
void methodC(){
//uses listBoxC
}
#Override
void methodD(){
//used listBoxD
}
}
public groupBox3View extends ContactView implements groupBox3Presenter
{
public groupBox3View()
{
}
#Override
void methodE(){
//uses listBoxE
}
#Override
void methodF(){
//used listBoxF
}
}
public groupBox4View extends ContactView implements groupBox4Presenter
{
public groupBox4View()
{
}
#Override
void methodG(){
//uses listBoxG
}
#Override
void methodH(){
//used listBoxH
}
}
You are right, your view is growing too big. You need to cut it into components which are handling their own concerns.
The editor framework will prove helpful but has it's own caveats.
In the end, you have one presenter, working with the whole thing, but only reading and writing one contact object.
You build your view from multiple components, each may have it's own presenter and is responsible for one part of your large contact object.
An example: Instead of running 10 listboxes of generic type, make that 10 semantically different components, responsible for selection of different types of data: AgeListBox, CityListBox, FooListBox, BarListBox.
This will seperate the data provisioning for the boxes out of your central presenter, and into the specific presenters for each listbox.
Start at the lowest level and combine editing views for each semantic unit and combine them to larger return objects:
NameEditor, AgeEditor, FooEditor, BarEditor are combined into an AddressEditor, which assembles with a CVEditor into something bigger until you finally arrive at the contact level.
I hope this makes sense to you.
UPdate: You asked for code, let's try some pseudocode:
Let's say you have a profile you want to edit. It contains of
the user's personal data
contains the user address
a bunch of email or mobile addresses
an image or connection to Gravatar
payment information
the list of tags the user is interested in
the list of channels he subscribed
Newsletter/marketing information
public class UserProfile {
PersonalData person;
List<NewsTopic> topicsOfInterest;
List<NewsChannel> subscriptions;
MarketingInfo marketingInfo;
// bean stuff, constr, equals etc.
}
public class PersonalData {
String name;
String firstName;
List<ContactDevice>phoneAndMailList;
ImageContainer userImage;
BankAccount paymentData;
}
You get the idea, I guess...
You can now write ONE view class, detailing all the information you see here, resulting in a monolitic monster view and the matching monster presenter. Or you follow the advice in the gwtproject and cut the view in small as possible pieces (components). That is, subviews and presenters that form a hierarchy, matching the one of your UserProfile class. This is basically what the editor framework is really good at.
In the editor fw, the views are called "Editors" (makes sense), and they get fed the data from top editor down to the smallest part by an EditorDriver class. GWT will generate most of the code for you, which is very cool, but also is not working so perfect, if you have optional parts in the profile.
If we would implement this ourselves, you will build a structure like the following (I avoid the "Editor" and replaced by "Dialog"):
public class UserProfileDialogView extends Component implements HasValue<UserProfile> {
// subviews
#UiField
PersonalDataDialog personDataDlg;
#UiField
UserTopicListDialog topicListDlg;
#UiField
SubscriptionListDialog subscriptionListDlg;
#UiField
MarketingInfoDialog marketingInfoDlg;
#Overwrite
public UserProfile getValue() {
// we do not need to copy back the data from the sub-dialogs, because we gave them the values from the profile itself.
// Beware, substructures cannot be null in such a case!
return userProfile;
}
#Ovewrite
public void setValue(UserProfile profile) {
this.userProfile = profile;
// option one: manually distribute the profile parts
personDataDlg.getPresenter().setValue(profile.getPerson());
topicListDlg.getPresenter().setValue(profile.getTopicsOfInterest());
subscriptionListDlg.getPresenter().setValue(profile.getSubscriptions());
// option two: use eventbus and valuechanged event, dialogs are
}
}
There is now a variance of concerns: Who will set the value in the sub-dialogs. You can forward to the presenter of the sub-dialog, or you set it directly in the sub-dialog.
Anyway, what should get clear to you now, is that you do not have only one presenter to rule all parts of the view. You need to split the presenters to be responsible for one subview each. What I found useful in such a large dialog tree, was to have a separate model class, that keeps the object currently beeing edited and provides change communication logic for other dialogs. For example, if you add a list of topics, and you add one topic, the dialog for the channel subscription selection may want to know, that there is now one more topic to be shown in the topic-filter.
I have a very strange problem with a java class in my android application.
I have some sub classes which extend my abstract class GameDialog
GameDialog class
public abstract class GameDialog extends Sprite
{
private static boolean gd_visible = false;
protected GameDialog(GameScene scene, Camera camera, VertexBufferObjectManager pSpriteVertexBufferObject){
...
}
public boolean display(){
if(!GameDialog.gd_visible) {
...
}
}
protected boolean hide(){
if(GameDialog.gd_visible){
...
}
}
}
PauseDialog class
public class PauseDialog extends GameDialog {
public PauseDialog(GameScene scene, Camera camera, VertexBufferObjectManager pSpriteVertexBufferObject) {
super(scene, camera, pSpriteVertexBufferObject);
...
final ButtonSprite play_button = new ButtonSprite(...);
play_button.setOnClickListener(setPlayButtonListener());
}
private OnClickListener setPlayButtonListener() {
return new OnClickListener() {
#Override
public void onClick(ButtonSprite pButtonSprite, float pTouchAreaLocalX, float pTouchAreaLocalY) {
hide();
}
};
}
}
Each time I want to display a dialog, I write this line :
new PauseDialog(GameScene.this, camera, vbom).display();
The first time, it works well : the dialog is displayed, user make a choice and it's hidden.
But the 2nd time, the dialog is not hidden (after user's choice).
I used the debugger to see what's going on, and the conclusion is :
In the 2nd instance, it calls the hide() method of the first instance !
If some one can explain me what it is doing that ... Thank you.
It is because gd_visible is static. Delete the static keyword and it should work. Static fields doesn't belong to the instances but they belong to the class.
I am new in Java and i have a few questions for more advanced developers.
I have Swing-based GUI application in which I have several AbstractActions.
A large group of AbstractActions creates new tab based on JPanel. For example:
// opens "Documents" tab
documentsAction = new AbstractAction(DOCUMENTS) {
#Override
public void actionPerformed(ActionEvent e) {
try {
int index = getTabIndex(DOCUMENTS);
if (index >= 0) {
// Tab exists, just open it.
tabbedPane.setSelectedIndex(index);
} else {
// No tab. Create it and open
newCatalogTab(new DocumentService(), DOCUMENTS);
}
} catch (ServiceException ex) {
printError(ex.getMessage());
}
}
};
documentsItem.setAction(documentsAction);
Where getTabIndex is:
private int getTabIndex(String tabName) {
int result = -1;
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (tabName.equals(tabbedPane.getTitleAt(i))) {
result = i;
break;
}
}
return result;
}
and newCatalogTab is:
private void newCatalogTab(ICatalog service, String Name) throws ServiceException {
CatalogPanel panel = new CatalogPanel(service);
tabbedPane.add(Name, panel);
tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
checkTabs(); // changes activity of buttons like "edit" and "delete"
}
So, many AbstractAction do the similar work:
Create instance of class, that extends AbstractPanel;
Pass data access interface (DocumentService in example) to instance;
Create a new tab with instance.
Can I somehow template this if data access interfaces will use different POJO's?
Can I create Generic interface and use it?
Can you show me right direction for thinking?
Thanks for wasting your time.
There are no templates in Java, so there will be some code duplication in any case. However, you can cut some of the boilerplate code by using factories. For example:
interface CatalogFactory {
public ICatalog makeCatalog();
}
class DocumentServiceFactory implements CatalogFactory {
#Override
public ICatalog makeCatalog() {
return new DocumentService();
}
}
class TabAction extends AbstractAction {
private final String name;
private final CatalogFactory factory;
//Appropriate constructor...
#Override
public void actionPerformed(ActionEvent e) {
//...
newCatalogTab(factory.makeCatalog(), name);
//...
}
}
Then you can do
documentsItem.setAction(new TabAction(DOCUMENTS, new DocumentServiceFactory()));
without having to create a separate anonymous AbstractAction for each tab.
Similarly for panels and possibly other objects where this pattern fits.