How to force something to happen before something else JAVA - java

In my app I'm trying to create a "loading screen" so the user knows what's happening and doesn't think the app is lagging when loading a new view upon releasing a button. I'm trying to have my "setViewVisibility" method run before the rest of the code but I can't seem to make it work. The way I have it set up right now is that there's an instance boolean that gets changed when one action is completed but for some reason it's not working. Any ideas on how I could fix this?
if(isLoadScreen == true){
setViewVisibility(visibility.END);
buttoni.setAlpha((float) 1);
isLoadScreen = false;
}
if (isLoadScreen == false){
setKeysList(list);
startQuestion(keysList.get(0));
currentQuestion = 0;
isLoadScreen = true;
}

Your second block is always executed because isLoadScreen is always false at that point. You need to use else instead of if to get the behavior you want.
if (isLoadScreen == false){ //isLoadScreen is always false here - just use else instead
setKeysList(list);
startQuestion(keysList.get(0));
currentQuestion = 0;
isLoadScreen = true;
}
That said, there are better ways to create splash/loading screens - this question How do I make a splash screen? might provide some hints.

Related

Detecting current color in window

I am doing a beginner project and I have had a little issue with a radio button. This button's job is to change the theme of the window from light to dark and vice versa.
I'm not too sure on how to ask for Java to detect the value for the Color.decode() method. I want it to check if the current color is either "#21252B" or "#FFFFFF"
I expect it to look kind of like:
if(*however you are supposed to do it*.equals("#21252B")) {
frame.getContentPane().setBackground(Color.decode("#FFFFFF"));
darkMode.setBackground(Color.decode("#FFFFFF"));
} else {
frame.getContentPane().setBackground(Color.decode("#21252B"));
darkMode.setBackground(Color.decode("#21252B"));
}
What can I do?
I figured out what I had to do. Thanks to #AndrewThompson for the suggestion. If anyone needs an answer to a similar problem, here it is. Make
private boolean isDark = true //or false if you want from the get go.
Then, whenever you do your button do the following code
public void actionPerformed(ActionEvent arg0) {
if(isDark == true) {
lightTheme();
isDark = false;
} else {
darkTheme();
isDark = true;
}
after this you should be good to go.

How to handle event in a program running in a cycle (loop)?

I´ve been dealing with this for some days now I´ve serach over the internet and tried everything that came up to my mind but nothing works. My problem is that I am making a pexeso game, we have some additionaly library directly from school or something like that which allows us to draw some pictures instead of comad line only... (We didn´t have graphics yet) So my problem is that my game is running in cycle and waiting for my click som I am checking the condition if click was made. And if I want to click I have to have just a method public void vyberSuradnice(int, int) declared in my code.
So the problem is that my game is runinng in cycle and checking if click was made. But when the click was made the method vyberSuradnice is executed and there I am setting the value off atrrbiute - cakatNaKlik on false, so click was made and one step of game can be made.. But since the function is running in cycle, then even If I clicked and in the method vyberSuradnice the value of attribute is changed, my function which is running in cycle isn´t respond to that change, so the game isn´t going on.
this is the method for clicking
public void vyberSuradnice(int paSuradnicaX, int paSuradnicaY) {
this.riadokOdkry = (paSuradnicaY ) / 25;
this.stlpecOdkry = (paSuradnicaX - 10) / 25;
if (this.riadokOdkry > this.aPocetRiadkov || this.stlpecOdkry > this.aPocetStlpcov) {
System.out.println("Klikli ste mimo hracieho pola ");
} else {
this.cakatNaKlik = false;
}
}
This the part of code where I am waiting for cakatNaklik - false value
while (uhadol) {
if (!this.cakatNaKlik) {
if (this.pocetUhadnutych >= (this.aPocetRiadkov * this.aPocetStlpcov) / 2) {
uhadol = false;
}
this.hraciaPlocha[this.riadokOdkry][this.stlpecOdkry].setUhadnute(true);
But even if the value is changed in method vyberSuradnice this condition is not triggered. But when I make something like this :
while (uhadol) {
System.out.print(this.cakatNaKlik);
if (!this.cakatNaKlik) {
if (this.pocetUhadnutych >= (this.aPocetRiadkov * this.aPocetStlpcov) / 2) {
uhadol = false;
}
this.hraciaPlocha[this.riadokOdkry][this.stlpecOdkry].setUhadnute(true);
the game is working like by writing the variable refresh it or something... but I am getting neverending print of true true or false on command line and this is something I can´t afford to have...
I know this may can be dan by threads but it´s something I can´t allowed to make and I am basically trying to do two things at once.
Is there any other to do this that the variable will be refreshed even without that println and the code will work ?
Thanks very much for every help
Thanks everybody for help, I finally solved it. I just tried tu put a sleep before the if condition. It only need to sleep for even a one miliseconds and it´s seems that the condition is refreshed so it works.
Try this:
Implement an ActionListener interface or extend a class that implements an ActionListener interface. For example:
public class MyClass implements ActionListener {
}
Register an instance of the event handler class as a listener on one or more components. For example:
someComponent.addActionListener(instanceOfMyClass);
instanceOfClass = this; //(if it is handled in the same Class)
Include code that implements the methods in listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
Reference:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

LibGdx moveTo action not executed

I am making an app and i have an annoying bug/error: when i want my image to move gradually upwards, it doesn't do anything. Here is some of my code:
public void checkButtons(){
MoveToAction moveUp = new MoveToAction();
moveUp.setDuration(actionDuration);
moveUp.setPosition(0, Gdx.graphics.getHeight());
MoveToAction moveDown = new MoveToAction();
moveDown.setDuration(actionDuration);
moveDown.setPosition(0, Gdx.graphics.getHeight() - Gdx.graphics.getHeight() * 2);
MoveToAction moveLeft = new MoveToAction();
moveLeft.setDuration(actionDuration);
moveLeft.setPosition(Gdx.graphics.getWidth() - Gdx.graphics.getWidth() * 2, 0);
MoveToAction moveRight = new MoveToAction();
moveRight.setDuration(actionDuration);
moveRight.setPosition(Gdx.graphics.getWidth(), 0);
if (goingUp == true){
red_dot.addAction(moveUp);
if (goingUp == false){
red_dot.removeAction(moveUp);
}
}
if (goingDown == true){
red_dot.addAction(moveDown);
if (goingDown == false){
red_dot.removeAction(moveDown);
}
}
if (goingLeft == true){
red_dot.addAction(moveLeft);
if (goingLeft == false){
red_dot.removeAction(moveLeft);
}
}
if (goingRight == true){
red_dot.addAction(moveRight);
if (goingRight == false){
red_dot.removeAction(moveRight);
}
}
red_dot is an image and the rest of the variables are pretty straightforward.
Thanks in advance.
A few things to check:
Are you calling stage.act()?
Is your actionDuration non-zero?
Are you sure about those coordinates? Most of them look like they would be off-screen if you're using a ScreenViewport. And if you're not, why would the size of the screen have anything to do with where you want to move your object?
It also seems you have some kind of misunderstanding about logic flow. The code structure that you repeat four times doesn't make sense:
if (someCriterion == true) {;
doSomething();
if (someCriterion == false) {
//Code in here will never be called unless `doSomething()` immediately causes
//someCriterion to become false as a side effect (which addAction() will not do).
}
}
I'm guessing you are thinking either that the code under addAction will get called after the action is complete, or that it will be called repeatedly. But neither is the case. If you want to stop the actions early, you must remove them at the spot in your code where you are changing variables such as goingUp to false.
But if you are just trying to remove actions that are complete, that is unnecessary, because that happens automatically.
Also, you shouldn't be creating all those extra actions that you may not be using. You're generating lots of garbage that could cause stuttering. Only create actions that you are definitely going to use. And instead of using new MoveToAction(), use Actions.moveTo() to get the action you need from the pool. Then it will not trigger garbage collection when it is complete, because Stage knows to send pooled actions back to the pool for recycling.

GWT infinite scroll with discarding start-of-list results

Looking for a GWT DataGrid component which implements infinite scroll, BUT also makes sure to discard the results no longer visible on the screen : such as the previously loaded results that are not shown anymore.
This is to avoid a memory hog.
I've been trying to find this on Google, but no luck so far.
Please note : I could take a JS library and adapt it to what I need, but I don't think it would work good with GWT's DataGrid component.
Edit: I am interested specifically in an infinite scroll which ALSO discards/releases the topmost results that are not visible (and loads them up as appropriate).
Any ideas ?
As a matter of fact the showcase example has an infinite scrolling CellList. (you can find the code there).
Although this was done with a CellList the same principles should also apply to a DataGrid.
Check out the ShowMorePagerPanel.java file.
Update:
The onScroll function of ShowMorePagerPanel.java will add the new records at the bottom. However you can easily change the behavior:
Something along the lines (not tested tough):
HasRows display = getDisplay();
if (display == null) {
return;
}
boolean loadData = false;
// If scrolling up, change newStart
int oldScrollPos = lastScrollPos;
lastScrollPos = scrollable.getVerticalScrollPosition();
// get the current visible Range
Range currentRange = display.getVisibleRange();
if (oldScrollPos >= lastScrollPos) {
int newStart = Math.max(
currentRange.getStart() - incrementSize,0);
loadData = true;
}
int maxScrollTop = scrollable.getWidget().getOffsetHeight()
- scrollable.getOffsetHeight();
if (lastScrollPos >= maxScrollTop) {
// We are near the end, so increase the page size.
int newPageSize = Math.min(
display.getVisibleRange().getLength() + incrementSize,
display.getRowCount());
loadData = true;
}
if (loadData) {
display.setVisibleRange(newStart, newPageSize);
}

Do not change right the icon,java

i have a problem with my code. I think that my problem is easy,but i have compiled for 3 days without good results. I have three images. They are put on screen one-one each time. User choose from 4 button if image's side is up, down, right or left. Also, i want to understand if user was wrong and then i will count errors. When user make 3 errors then the game will stop. I have shown code below. Please help me if you have any good idea.
The problem is that at the first loop,run right.It goes at the first if. After that it do the loop and then it does not go to second if.
if it is more helpful,some details:
i want to make a programma that it will show to user an image.This image has 4 sides (up,down,right,left).When the image is at "up side",user has to click on up button,when the image is at "down side",user has to click on down button etc. User can do 3 errors max. At first,program show the image at right side,if user clicks on right button then i want to show the "second image" at left side.If user does not at left side,then i want to add an error(error++) and after it shows the third image at up side etc. I hope it is more helpful to understand. If you can't please let me know.
My program is at Netbeans,java.
Thank you
public void actionPerformed(ActionEvent e)
{
while(errors<3)
{
image.setIcon(createImageIcon("visual1" + e.getActionCommand() + ".PNG"));
if (k==1)
{
if(e.getSource() == right_button)
{
image.setIcon(createImageIcon("visual2" + e.getActionCommand() + ".PNG"));
}
}
else if ( k==2 )
{
if(e.getSource() == left_button )
{
image.setIcon(createImageIcon("visual3" + e.getActionCommand() + ".PNG"));
}
}
else if (k==3 )
{
if(e.getSource() == up_button)
{
System.out.print("if3");
}
}
else
{
errors++;
}
k=k+1;
}
}
You should consider calling Repaint and Invalidate, right after you update your GUI like this -
mainframe.repaint();
mainframe.invalidate();
here mainframe is your JFrame object.
A problem I see with your while loop is that it is at risk of getting stuck in an infinite loop, since the variable used as an exit criterion is only updated some of the time, in an else block. I think you should re-arrange your logic:
Get rid of that while loop as it will only cause trouble. It is useful for a linear command line program but not for an event-driven GUI program like yours.
Read in all images and create all ImageIcons in the class constructor, and store them in variables. There's no need to re-read the images multiple times (unless they're huge).
Instead of using a while loop, increment the error variable in your method above, and then write the method so that it will change behaviors depending on the value of error (depending on the state of the class).
e.g.,
// somewhere in your code create your icons
Icon rightIcon = ......;
Icon leftIcon = .....;
Icon upIcon = .....;
Icon downIcon = .....;
// elsewhere in your code
public void actionPerformed(ActionEvent e) {
if (errors >= 3) {
// notify user of error
return; // end this method
}
// check if current icon matches image
// if so, change icon
// if not increment error
}
Note that an enum Direction {UP, DOWN, LEFT, RIGHT} and a Map<Direction, Icon> could be helpful here.

Categories

Resources