I was wondering if you could help me. I have a puzzle that needs to implement an undo method. There are two moves you can complete an assign move (assigns a number to the grid) and a relation move (which adds a relation move).
I have an abstract class (UserEntry) which instantiates one common method with Assign and RelEntry. I have called this public void addToPuzzle() {
it is as follows in the Assign Class:
#Override
public void addToPuzzle() {
Assign a = new Assign(row, col, num);
}
and this in the RelEntry Class:
#Override
public void addToPuzzle() {
RelEntry re = new RelEntry(greaterRow, greaterCol, lesserRow, lesserCol);
}
I am trying to create an undo method in my puzzle UI using a stack. I have tried this:
private void undo() {
if(stack.empty())
return;
stack.pop().addToPuzzle();
}
Moves are instantiated in the puzzle UI and I have pushed each move in the text UI into the stack using a stack.push line of code following each move being assigned. I have a feeling I'm not being clear, if this is the case, go easy on me as I'm new to Java.
Related
Having an issue with tables and updating a label! Here is the dilemma, I have a sell button in my game that is updating the player's coins whenever they sell an item, that part is working perfectly. The issue I am having is trying to get the coin value to update on the screen while there in this separate menu (see pic attached, coins in the top left). The problem is that the coin value is in another stage in another class. This is because I have different tables that pop up in the middle when I click the different buttons at the bottom. I have tried helper methods for going in and clearing that table and updating it and then sending me back to this item page but it is not working, I can post any code needed but this is more of a general question on how to update a label within a table in a stage.
Update: So to kinda sum up my question, I have a Screen and I have have three tables in it the bottom table the top left and the top right. Then I add the table to the stage in the middle when they press the inventory or shop button etc. What I am looking to do is to keep the item page open and simply just update the value of the Coin label, I know I can change the text using .setText(); Im just not sure how I can update that portion of the screen etc..
Update 2: If I just set the screen back to a new screen of this screen it updates the coin value but then I am not on the item page anymore which is not ideal.
Update 3: Thanks for the help so far guys, #John your answer is super helpful aswell. Im still not getting this working though here is a little bit of the code where the label is being handled.
playerCoinLabel = new Label(playerSave.getCoinsString(),skin,"defaultMiddle");
This is where it is getting added to the table.
tableLeft = new Table(skin);
stage.addActor(tableLeft);
tableLeft.setBounds(0,0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
tableLeft.setFillParent(true);
tableLeft.top().left();
tableLeft.add(healthNonButton).size(84,80).left().padLeft(10).padTop(5);
tableLeft.add(playerHealthLabel).left().padLeft(15);
tableLeft.row();
tableLeft.add(levelNonButton).size(74,70).center().padLeft(10);
tableLeft.add(playerLevelLabel).left().padLeft(19);
tableLeft.row();
tableLeft.add(coinNonButton).size(74,70).center().padLeft(10);
tableLeft.add(this.playerCoinLabel).left().padLeft(15); //This line
tableLeft.row();
Then I have this method for updating my label using the setText like you guys were telling me about.
public void updatePlayerCoins() {
playerCoinLabel.setText(playerSave.getCoinsString());
}
and if I call this method anywhere, render() or where im setting the new coin value it is not updating/changing the label in the top left of my screen. I can post all the code to a github if I need to just posted the things involving the label. This is just a project im working on to increase my skill set so sorry if I sound amateur, it is because I am!
Thanks everyone!
It seems like you're asking two things- how do I update a label? and How do I structure my code? It's hard to tell what's going wrong with the former since we can't see your code, but #Tenfour04 is right- you want to retain a reference to the label somewhere and call setText() when you want to change the amount.
As far as structuring your code, I would suggest a simple OOP design and then evolve it like so:
First, we need an object to represent the player:
class Player {
private int coins; // Pretend there are getters / setters.
private int health;
private int level;
}
Now you probably have more than one way that you want to represent this player information, so we'll split the rendering code into a separate class or set of classes:
class StatWidget {
private Stage stage;
private Player player;
private Label lblCoins;
public StatWidget(Player player) { // Pseudo-code
this.player = player;
this.stage = new Stage();
Table tbl = new Table();
this.lblCoins = new Label(); // Notice we keep a reference to the label
tbl.add( this.coins );
}
public void update() {
lblCoins.setText(player.getCoins());
}
}
Now you can sync the UI with your player object's state simply by calling Player#update(). But when do you call it?
You could call update() in your render method. This is a little inefficient because you're updating the object whether it needs to be updated or not, but it's dead simple, and if you're only updating a few UI elements this way it probably doesn't matter. Personally, I'd stop here.
If you want to be more precise, you would only call update() when you actually make a change to the Player's coins. You can do this by finding the places in your code where you set the player's coins and add the update call like so:
player.setCoins( A_LOT_OF_MONEY );
statWidget.update();
Problem is this gets more cumbersome as you add more widgets- all your game logic now has to know about StatWidget and make calls to it. We could cut this dependency a little bit by using an event-driven architecture. Essentially, whenever player's state changes, it would send an event to interested parties notifying them of the change. You could use the pseudo-code below:
interface Publisher {
void subscribe(Subscriber subby);
void unsubscribe(Subscriber subby);
}
class Player implements Publisher {
private List<Subscriber> subscribers;
private int coins;
// ...
public void setCoins(int amount) {
this.coins = amount;
for(Subscriber subscriber : subscribers) subscriber.notify("COINS", amount);
}
public void subscribe(Subscriber subby) {
this.subscribers.add(subby);
}
public void unsubscribe(Subscriber subby) {
this.subscribers.remove(subby);
}
}
interface Subscriber {
void notify(String event, int qty);
void dispose();
}
class StatWidget implements Subscriber {
private Publisher player;
private Label label;
// ...
public StatWidget(Player player) {
this.player = player;
this.player.addSubscriber(this);
void notify(String event, int qty) {
if(event.equals("COINS")) label.setText(qty);
}
void dispose() {
this.player.unsubscribe(this);
}
}
The event system above could certainly be polished, and you could likely do clever things with generics (or use a library that has thought all this out for your), but hopefully it illustrates the concepts.
I want to find out whether method for some object is being called for that instance or not.
Is it possible in java ?
Like ...
class Button {
public void focus(){}
public void setName(){}
}
class MyTest {
public static void main(String[] args){
Button button = new Button();
button.focus();
// I want to find out on button instance whether focus() or setName() is called or not.
whetherMethodCalled(button);
// OR
whetherMethodCalled(button, 'focus');
whetherMethodCalled(button, 'setName');
}
}
EDIT : Forgot to add Button class is third party class which I cannot modify... Also I want to check in my code whether method has called for given object instance or not on basis of that I have to write some code.
In order to reduce extra work, perhaps profiling your application with JConsole or another tool is good enough to show if certain methods have run. Another option is using a code coverage tool like EMMA which detects dead code. There is a list of open-source profilers for Java at http://java-source.net/open-source/profilers and EMMA is at http://emma.sourceforge.net/.
With some extra work AspectJ could be use to intercept method calls without changing existing code. For example, the following would intercept calls to Button.focus()
#Aspect
public class InterceptButtonMethods {
#Before("execution(* Button.focus())")
public void beforeInvoke() {
System.out.println("Button.focus invoked");
incrementFocusCount();
}
}
If more extra work is ok, there is a way to wrap all calls to the Button's focus() and setName() methods so that they update separate counters in addition to their normal functions. This can be done by extending Button in YourButton class which is identical to Button except for a couple of int counters with getters, setters and increment methods; and countingFocus() and countingSetName() methods which update their counters and call focus() and setName() respectively, such as in outline:
Class YourButton extends Button {
int focusCount;
int setNameCount
int getFocusCount() {return this.focusCount;}
void setFocusCount(int counter) {this.focusCount = counter} // optional to reset counter
void incrementFocusCount() {this.focusCount = getFocusCount() + 1;)
...
void countingFocus() {
incrementFocusCount();
focus()
}
...
}
If it is required in many places and involves complex things, I recommend to use Mockito to test your code. Using that you can verify if the method was invoked (also how many times if invoked)
You can mock the button and verify in your MyTest how many times the method must be called. Using Mockito you can mock and stub your methods(Stubbing voids requires different approach from when(Object) because the compiler does not like void methods inside brackets) and then verify it using verify statement.
verify(mockButton, times(1)).focus();
verify(mockButton, times(1)).setName();
You can write a wrapper class over the 3rd party Button class through which all calls to Button class will be made.
This wrapper class can keep track of whether each method has been called or not
class ButtonCaller {
private Button button = null;
private boolean focusCalled;
private boolean setNameCalled;
public ButtonCaller() {
button = new Button();
focusCalled = false;
setNameCalled = false;
}
public void focus() {
button.focus();
focusCalled = true;
}
public void setName() {
button.setName();
setNameCalled = true;
}
public void whetherMethodCalled(ButtonMethod method) {
switch (method) {
case FOCUS:
return focusCalled;
case SET_NAME:
return setNameCalled;
}
throw new RuntimeException("Unknown ButtonMethod !!!");
}
public static Enum ButtonMethod {
FOCUS,
SET_NAME;
}
}
I am using Kmax to create a DAQ software. The philosophy of the GUI and the code is that every object on the GUI(radio buttons, check boxes, progress bars etc) has to have the same name with the relevant method. For instance an object named BUTTON is linked with the method public void BUTTON(KmaxWidget widget){code}.
My code is
import kmax.ext.*;
public class Runtime implements KmaxRuntime {
KmaxToolsheet tlsh; // Store a reference to the toolsheet environment
KmaxHist hist1D;
KmaxWidget checkBoxWidget;
public void init(KmaxToolsheet toolsheet) {
tlsh = toolsheet; // Save this reference for use in the toolsheet
hist1D = tlsh.getKmaxHist("HIST1D");
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH").setProperty("VALUE", "1");
}
public static boolean stringToBool(String s) {
if (s.equals("1"))
return true;
if (s.equals("0"))
return false;
return true;
}
public void CalibInit(KmaxWidget widget, KmaxHist histo){
histo.setUseXAxisCalibration(stringToBool(widget.getProperty("VALUE")));
histo.update();
}
public void chooseCalib(){
checkBoxWidget = tlsh.getKmaxWidget("CHECK_BOX_CALIB_METH");
checkCalib(checkBoxWidget,hist1D);
}
public void GO(KmaxToolsheet toolsheet){}
public void SRQ(KmaxDevice device) {}
public void HALT(KmaxToolsheet toolsheet) {}
} // End of the Runtime object
In the above code I have the check box CHECK_BOX_CALIB_METH. The problem arises when someone wants to create many objects;one has to create many methods. In the above code you can see what I am trying to do. I want to create a "main" method that will do every function that is needed and then another method will apply those functions to each object.
This code compiles without any errors, but the check box isn't working. So I was thinking if there is a way around this. For instance a method that will include "submethods" that will do the job! Or perhaps a method that will construct methods in a for loop for each radio button, check box, progress bar etc. Something like
for(int i=0; i<number_of_buttons ; i++){public void BUTTON_i(){code}}
The above code may look ridiculous but I don't know what else to think and I really want to avoid having one method for each button.
Is something like that possible or is there another way around this?
EDIT
For instance I have 6 methods that do exactly the same;they just have different names.
public void SET_CALIB_1(KmaxWidget widget) {
double C0 = (getValueFrom("Ch2_1")*getValueFrom("En1_1")-getValueFrom("Ch1_1")*getValueFrom("En2_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C1 = (getValueFrom("En2_1")-getValueFrom("En1_1"))/(getValueFrom("Ch2_1")-getValueFrom("Ch1_1"));
double C2 = 0;
double[] coef = {C0, C1, C2};
hist1.setXCalibration(coef);
hist1.setUseXAxisCalibration(true);
hist1.update();
} // SET_CALIB_1
Is there a way to have a generator method to generate methods like the above?
what are the design goals for this software?
reflection may be a much better way to get access to the members; and/or put all the components into an array for access.
I find that I tend to over-engineer things a lot; since I enjoy building things; but then they get way too complicated and don't work.
so I advise to take a walk (or trudge through the snow) and think about it some more.
I'm developing a game in Java which uses the Lightweight Java Game Library (LWJGL) with OpenGL.
I encountered the following problem.
I want to create an ArrayList of all textures in an object in the main loop, and access these from objects instantiated in this main object. A simplified example:
game.class:
public class Game {
ArrayList Textures; // to hold the Texture object I created
Player player; // create Player object
public Game() {
new ResourceLoader(); // Here is the instance of the ResourceLoader class
player = new Player(StartingPosition) // And an instance of the playey, there are many more arguments I give it, but none of this matter (or so I hope)
while(true) { // main loop
// input handlers
player.draw() // here I call the player charcter to be drawn
}
}
// this method SHOULD allow the resource loader to add new textures
public void addTextures (Texture tx) {
Textures.add(tx);
}
}
ResourceLoader.class
public class ResourceLoader {
public ResourceLoader() {
Interface.this.addTexture(new Texture("image.png")); // this is the line I need help with
}
}
Player.class
public class Player {
public player() {
// some stuff, including assignment of appropriate textureID
}
public void draw() {
Interface.this.Textures.get(this.textureID).bind(); // this also doesn't work
// OpenGL method to draw the character
}
}
In my real code the ResourceLoader class has about 20 textures to load.
There is a total of over 400 entities in the game that have a draw method just like Player.class and most of them share the same texture; e.g. there are about 150-180 wall object all showing the same image of bricks.
The Game object is not the main class and it does not have the static void main() method, but it is one of the only few things instantiated in the main() method of the game.
Also, in the past, I worked around the problem by letting each entity load its own texture file. But as I increased the complexity and map size, it becomes very inefficient to load the same image hundreds of times.
I arrived at the state of the code above from this answer.
I believe I would have to put ResourceLoader.class and Player.class inside the game.class, which would not be a good solution considering that there are about 20 files that need this treatment and most of them are 200+ lines long.
I think my Texture object as well as initialization of OpenGL and other stuff are pretty generic and should not impact the issue in question. I can provide these if necessary.
Make the "outer" class instance a parameter to the constructors:
public class Player {
final Interface obj;
public player(Interface obj) {
this.obj = obj;
// some stuff, including assignment of appropriate textureID
}
public void draw() {
obj.Textures.get(this.textureID).bind();
}
}
public class ResourceLoader {
public ResourceLoader(Interface obj) {
obj.addTexture(new Texture("image.png"));
}
}
And instantiate those in Game like:
new Player(this);
Note: The example lines used Interface but Game does not implement it. I assume that's an artifact of code cleaned for the posting. Just use the type that is appropriate for your situation.
I'm very new to Java and I'm setting myself the challenge on writing a Caesar shift cipher decoder. I'm basically trying to clear a JTextArea from another class. I have two classes, a GUI class called CrackerGUI and a shift class. The JtextArea is in the GUI class along with the following method:
public void setPlainTextBox(String text)
{
plainTextBox.setText(text);
}
The GUI class also has a clear button with the following:
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
Shift classShift = new Shift();
classShift.btnClear();
}
Lastly i have the method in the shift class to clear the JTextArea.
public class Shift extends CrackerGUI {
public void btnClear()
{
CrackerGUI gui = new CrackerGUI();
gui.setPlainText(" ");
System.out.println("testing");
}
}
The testing text is printing out to console but the JTextArea wont clear. I'm not sure as to why :). I am sure it's a very simple mistake but it has me baffled. Any help would be appreciated.
Thank you in advance.
You're misusing inheritance to solve a problem that doesn't involve inheritance. Don't have Shift extend CrackerGUI and don't create a new CrackerGUI object inside of the btnClear() method since neither CrackerGUi is the one that's displayed. Instead have Shift hold a reference to the displayed CrackerGUI object and have it call a public method of this object.
e.g.,
public class Shift {
private CrackerGUI gui;
// pass in a reference to the displayed CrackerGUI object
public Shift(CrackerGUI gui) {
this.gui = gui;
}
public void btnClear() {
//CrackerGUI gui = new CrackerGUI();
gui.setPlainText(" ");
System.out.println("testing");
}
}
You also should probably not be creating new Shift objects in your GUI's actionPerformed methods, but rather use only one Shift object that is a class field.
The btnClear method clears the text area of a new CrackerGUI instance. It's like if you wanted to clear a drawing on a sheet of paper by taking a new blank sheet and clearing it. The original sheet of paper will keep its drawing.
You need to pass the gui instance to your Shift:
public class Shift {
private CrackerGUI gui;
public Shift(CrackerGUI gui) {
this.gui = gui;
}
public void btnClear() {
this.gui.setPlainText(" ");
}
}
and in the CrackerGUI class :
private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {
Shift classShift = new Shift(this);
classShift.btnClear();
}
Assuming CrackerGUI is your GUI, you should have the following instead:
public class CrackerGUI {
public void setPlainTextBox(String text)
{
plainTextBox.setText(text);
}
public void btnClear()
{
setPlainTextBox("");
System.out.println("testing");
}
}
One last thing, never make your GUI elements public! You should ask the GUI to clear itself and leave that knowledge of clearing elements hidden inside it.
You could try using static methods, as you would end up creating a new gui, then displaying that one, in stead of the current one already displayed.
This would require the parent class to be static too, which may cause errors in some of your methods, just a heads up.
Or else, you could create your own setText method:
void setText(JTextField t, String s){
t.setText(s);
}
that may enable you to directly edit components in the current GUI.