hi i am new in java programming i have a big problem when i use timer or while loop for my program to show my variable and update it my program will stopped, not stopped working just nothing i cant do anything in my program my game is a easy game that we should got money from ... ways and i want to show my money every x second. every second isn't important for me just a code that not stop my program, here is my money code:
static int money = 0;
static int energy = 100;
static String energyinfo = Integer.toString(energy);
static String moneyinfo = Integer.toString(money);
private void setmoneyenergy()
{
energyinfo = Integer.toString(energy);
moneyinfo = Integer.toString(money);
jenergy.setText(energyinfo);
jmoney.setText(moneyinfo);
}
while is in a button actionperformed
while(true)
{
setpoolenergy();
}
Related
I'm currently running into a rather annoying problem.
Im running round about this task, with a Spigot-1.8 in Java 1.8. But this exact code gives me two diffrent Results.
In one the Levelbar of Minecraft just counts down and in another the Levelbar just flickers every time it sets the new XP Value.
private static int buildTask;
private static int buildSeconds = 120;
public static void buildingTime() {
buildTask = Bukkit.getScheduler().scheduleSyncRepeatingTask(Plugin.getInstance(), () -> {
for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
onlinePlayer.setLevel(buildSeconds);
}
//executing other Actions with Actionbar and Broadcasting Seconds to all players
if (buildSeconds <= 0) {
//ending here
}
buildSeconds--;
}, 0, 20);
}
I'm using this Spigot: https://getbukkit.org/get/hNiHm0tuqAg1Xg7w7zudk63uHr0xo48D
Already solved.... Let two tasks run at the same time which conflicted
I've been tasked with creating a program which will lead a finch robot to move around somewhat randomly for the allotted amount of time, while counting the number of objects that it detects during the movement and returning this amount to then be displayed.
I can get the robot to move randomly, and I can get it to count objects that it detects - but not at the same time.
main:
int millsec = 5000;
int obstacleOccur = finchRandom(millsec);
System.out.println(obstacleOccur);
method:
static public int finchRandom(int x)
{
Finch myf = new Finch();
Random rand = new Random();
int obs = 0;
long time = System.currentTimeMillis()+x;
while(time - System.currentTimeMillis() > 0)
{
if (myf.isObstacle())
{
obs++; //this counts the obstacles
System.out.println("Obstacle");
} //below activates the wheels to move randomly,
//the function is setWheelVelocities(leftWheel,rightWheel,duration)
myf.setWheelVelocities(rand.nextInt(150)-75,rand.nextInt(150)-75,rand.nextInt(x/2));
}
return obs; //returns the count of obstacles
}
I believe it is because the if statement and incrementation for counting obstacles can't be ran while the finch robot is moving around. Are there any ways around this?
Thanks in advance.
The answer is multithreaded programming, your job is to figure out how to use THread or Runnable or a lambda expression to do so. Because any given thread can only do one thing at a time, and you need to be doing at least two things at a time.
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int full = 20;
int feed = -10;
int jHooitemp = Integer.parseInt(jHooi1.getText());
jHooi1.setText(jHooitemp+ feed+ " kg");
}
I managed to decrease the pre defined value of the JTextfield(jHooi1) but it only works once.
It made the value wich i entered(20) drop to 10. but if i press the JButton another time it displays errors in the run screen.
Is there a way to make it decrease to 0 and send a message when it hits 0?
Hello!
I am trying to display a text on the Screen (with Java), but I want it to be delayed, like, every 0.1 seconds, a letter of the text would appear on the screen. It's like Pokemons dialogs. Here's what I am talking about: https://www.youtube.com/watch?v=yUS1IcC5CBY
I don't want the fade and the acceleration of the text, I just want the text to appear letter-by-letter. Also, I would like the text to be a String. Please, can you help me?
Thanks a lot in advance!
You can use two methods:
One is Thread.sleep(), which is shown above:
private static String message = "Your Message";
private static JLable label = new JLabel();
private static String labelMessage = "";
for(int i = 0; i < message.length(); i++){
labelMessage += Character.toString(message.charAt(i));
label.setText(labelMessage);
try{
Thread.sleep(howManyMillisecondsYouShouldWait);//if you want to do it every .1
//seconds, just wait 100 milliseconds.
}catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
that will forever print it to the screen every 100 milliseconds. However, the only trouble with using Thread.sleep is (and I somehow just learned this the other day, even though I've been programming for a long while) it is not always accurate. It may sleep 100 ms, it may sleep 150, etc. Secondly, a slower computer may take longer to sleep through it.
The other method which you will use more often (probably) is to check the actual time of your system and see if it's been long enough since you last printed it to the screen, like this:
private static long timeOfLastWrite;//at what time did you last update the text?
private static long deltaTimeSinceLastWrite;//how long has it been since you last updated the text?
private static long timeOfFirstWrite;//when did you start?
private static long deltaTimeSinceFirstWrite;//how long has it been since you started?
private static String message = "Your Message";
private static JLabel label = new JLabel();
private static String labelMessage = "";
//print once here:
timeOfFirstWrite = System.currentTimeMillis();
timeOfLastWrite = System.currentTimeMillis();//every time you print to the screen, make
//sure that you make note of it by setting the timeOfLastWrite variable equal to the current time.
labelMessage += Character.toString(message.chatAt(0));
while(!labelMessage.equals(message)){
deltaTimeSinceLastWrite = System.currentTimeMillis() - timeOfLastWrite;
if(deltaTimeSinceLastWrite >= 100){
timeOfLastWrite = System.currentTimeMillis();
deltaTimeSinceFirstWrite = System.currentTimeMillis() - timeOfFirstWrite;
int currentIndexOfChain = (int) deltaTimeSinceFirstWrite / 100;
if(currentIndexOfChain >= message.length()){
currentIndexOfChain = message.length() - 1;
}
labelMessage = message.substring(0, currentIndexOfChain + 1);
label.setText(labelMessage);
}
}
This method isn't even slightly necessary for a program so simple as writing text to the screen 10 times a second. However, it's good to get into the practice of it. You'll learn that if you create a character and tell him to move 10 pixels, Thread.sleep(100), and move again and etc... that on a slower computer, the character will move slower. However, if you tell it to wait until a certain amount of time has passed according to your computer's time, if the user lags out and it takes 200 milliseconds before it tells the character to move again, you can account for that by simply making him move twice as far -- I think it's called framerate independence.
If I did anything wrong with the delta time management please let me now. Again, I just learned about this the other day even though I've been programming for awhile, so don't worry about it too much if you're just now learning to program.
And that's how you make an incredibly long (possibly too long) answer to an incredibly simple question. I hope you benefit from this response.
I'm unable to use Thread.sleep(x) or wait(): java.lang.InterruptedException; must be caught or declared to be thrown
try {
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
You may use this code for doing so. Simply put a thread to print the text onto a jLabel.
new Thread(new Runnable() {
#Override
public void run() {
String x="";
String txt="Hello this is a sample text. Let us see how this works.";
for(int i=0;i<txt.length();i++){
try {
jLabel1.setText(x=x+txt.charAt(i));
Thread.sleep(100);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}).start();
How about this?
import javax.swing.Timer;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DelayText
{
public String example = "As you can see, this sentence is being printed out a character at a time.";
public String transfer = "";
public Timer t;
public int i = 0;
public JFrame f;
public JLabel l;
public DelayText()
{
f = new JFrame("Example");
l = new JLabel();
f.add(l);
f.setSize(450, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
TimerListener tl = new TimerListener();
t = new Timer(100, tl);
t.start();
}
public static void main(String[] args)
{
DelayText d = new DelayText();
}
private class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(i < example.length())
{
transfer += (example.charAt(i));
l.setText(transfer);
i++;
}
if(i >= example.length())
{
t.stop();
}
}
}
}
I am using the timer to create a delay between each character outputted on the JFrame. I noticed a lot of these other ones were a bit more complex, thought this might make things a bit easier to understand.
This is a java game that I have started working on.I have been trying to add a button that says "RESTART" which on clicking resets the whole program the way it was when it was at the beginning( i mean at the start of the game).
Here is my code:
There are 2 buttons namely "PLAY" & "CHECK WHO WON!"
For "PLAY" This is the code:
int delay = 1000;
final Timer timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
String b = "C:\\Users\\COMPUTER\\Desktop\\deck\\.png";
Random r = new Random();
r1 = r.nextInt(upplim)+lolim;
String a = Integer.toString(r1);
String c = "C:\\Users\\COMPUTER\\Desktop\\deck\\"+a+".png";
l1.setIcon(new ImageIcon(c));
}
},delay, 50);
For "CHECK WHO WON!" This is the code:
final int p = h;
System.out.println("ANSWER IS:"+p);
int delay2 = 1000;
for (int i = 1; i < 53; i++)
{
while(true)
{
next = rng.nextInt(Ulim) + Llim;
if (!generated.contains(next))
{
generated.add(next);
break;
}
}
if ( i % 2 == 0 )
{count++;
deck1[e] = next;deck1count++;
e++;
}
else {count++;
deck2[f] = next;deck2count++;
f++;
}
System.out.println(""+next);
if(next==p)
{break;}
}
if(deck1count==deck2count)
{
count=count-2;
fcard=99;}
final Timer timer2 = new Timer();
timer2.schedule(new TimerTask(){
public void run(){
do
{
System.out.println("dec2 "+deck2[z]);
String a = Integer.toString(deck2[z]);
String c = "C:\\Users\\COMPUTER\\Desktop\\deck\\"+a+".png";
l3.setIcon(new ImageIcon(c));
System.out.println("dec1 "+deck1[z]);
String b = Integer.toString(deck1[z]);
String d = "C:\\Users\\COMPUTER\\Desktop\\deck\\"+b+".png";
l4.setIcon(new ImageIcon(d));
System.out.println("count"+count);
z++;
count=count-2;
if(fcard==99&&count<0)
{l3.setIcon(new ImageIcon("C:\\Users\\COMPUTER\\Desktop\\deck\\99.png"));
}
}while(count>0&&z==p);
if(count<0)
{timer2.cancel();
reschk=11;
timer2.purge();
}
}
},delay2, 1000);
There is also another set of code which is written on the MouseClicked event of a label but I don't think it would be of much help here.
I have tried:
classname.this.dispose();
classname classname = new classname();
But it just shuts the whole program down.Is there any other way to reset the game?
Thanks for reading.
Any help would be appreciated.
You obviously have values which update so that you can represent your game during different states. If you want to restart your game, you simply need to set all of these values back to the original start values. You can write a Restart method to this.
Also, dispose() is designed to close the window.
edit: There is no magic method you can call to reset your program.
For Swing based container use Swing Timer rather than util.Timer, otherwise output from util.Timer should be out of EDT.
You don't need to dispose old container and recreate a new for fresh game, you can remove its contents.
anything else isn't clear from code posted here, nor question
Keep the state of the game in a distinct class and replace that with a fresh instance.