cannot write in TextArea JavaFX - java

I cannot write in TextArea and I don't know what to do in this case.
Here is my code from class "Server" that is used in order to put text in TA:
public class Server implements Runnable {
.
.
.
#Override
public void run() {
while (true) {
try {
if (queue.size() !=0) {
Task task = queue.take();
String text = "Server" + Integer.toString(getIdServer()) + " is processing the task: " + Integer.toString(task.getIdTask()) + " with proc time " + Integer.toString(task.getProcessingTime());
InputShop.textArea.setText(text);
Thread.sleep(task.getProcessingTime() * 1000);
waitingTime.addAndGet(-task.getProcessingTime());
}
} catch (InterruptedException e) {
}
}
}
public void addTask(Task newTask) {
String text2 = "Task "+ Integer.toString(newTask.getIdTask()) + " arrives at s " + Integer.toString(newTask.getArrivalTime())+ " on server "+ Integer.toString(getIdServer());
InputShop.textArea.setText(text2);
queue.add(newTask);
waitingTime.addAndGet(newTask.getProcessingTime());
}
And my UI Class looks at that part with TextArea like this:
TextArea textArea = new TextArea();
textArea.setPrefWidth(300);
textArea.setPrefHeight(300);
GridPane.setConstraints(textArea, 8, 8);
gridPane.getChildren().add(textArea);
textArea.setEditable(false);
If I write "System.out.println(...);" instead of the part with "InputShot.textArea.setText(...);" everything works fine, and it prints everything on the output log of the screen.
I have been searching a lot and struggling with this problem for hours and I do not know how to manage it, so I would appreciate every help!
If I missed an important part of code, or information, please let me know in order to edit the question!

Related

.jar program not operating the same as compiled program

I made a simple java program to move the mouse cursor 1 pixel every 10 seconds. The program works as its supposed to when compiled and ran from command line. But when running the program from the .jar the cursor doesnt move. I know the timer is still running because I have that output to the JFrame. Any ideas on why the timer still runs but the cursor doesnt move like it does when ran from command line?
public static void main(String args[]) {
JFrame frame = new JFrame("Mouse-Mover");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
JButton startButton = new JButton("Start");
frame.add(startButton, BorderLayout.NORTH);
JButton stopButton = new JButton("Stop");
frame.add(stopButton, BorderLayout.SOUTH);
frame.setVisible(true);
//when start button is clicked, start the timer
startButton.addActionListener(e -> {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
int cursorPositionX = MouseInfo.getPointerInfo().getLocation().x;
int cursorPositionY = MouseInfo.getPointerInfo().getLocation().y;
int firstX = cursorPositionX + 1;
int firstY = cursorPositionY + 1;
try {
Robot robot = new Robot();
robot.mouseMove(firstX, firstY);
} catch (AWTException e) {
e.printStackTrace();
}
System.out.println("Running: " + new java.util.Date());
JTextArea jTextArea = new JTextArea();
jTextArea.setEditable(false);
jTextArea.setText("Running: " + "X Coordinate: "+firstX + " " + "Y Coordinate: " + firstY + " " + new java.util.Date());
frame.add(jTextArea, BorderLayout.CENTER);
frame.add(jTextArea);
frame.setVisible(true);
stopButton.addActionListener(e -> timer.cancel());
//system.out.print size of jframe
System.out.println(frame.getSize());
}
}, 0, 1000);
});}}
`
A .jar is a compiled application.
Below is an example runnable of how this can be done. Do keep in mind however, as already stated within comments, this may not work properly or (not work at all) on some platforms due to security reasons. Some platforms may not allow for access to low-level input control. You would need to set special privileges or extensions in the OS for your application to function properly.
Please read the comments in code:
package movemouseeveryseconddemo;
public class MoveMouseEverySecondDemo {
public int interval = 1000;
public int pixelMovementX = 1;
public int pixelMovementY = 1;
public javax.swing.Timer moveTimer;
public java.awt.Robot robot;
public final javax.swing.JFrame frame = new javax.swing.JFrame("Mouse-Mover");
public final javax.swing.JTextArea jTextArea = new javax.swing.JTextArea();
public int firstX = 0, firstY = 0;
public MoveMouseEverySecondDemo() {
try {
// Initialize robot
robot = new java.awt.Robot();
}
/* Robot may not work in some operating systems due to improper
permissions. If this is the case then OS configurations will
need to be done to allow Robot to function. */
catch (SecurityException ex) {
System.out.println("Permission required for Robot or this application"
+ "to function within Operating System!");
}
/* Just as the Exception Description states. Operating System
Configuration will need to be done in order for this application
to perform low-level input control such as what Robot does. */
catch (java.awt.AWTException ex) {
System.out.println("The Operating System configuration does not "
+ "allow low-level input control!");
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new MoveMouseEverySecondDemo().startApp(args);
}
private void startApp(String[] args) {
/* See if there are Command-Line arguments...
Allows for the User to supply a desired Timer Interval and desired pixel
X/Y movement amounts. The interval must be in Milliseconds (default is
1000 [1 second]) and the pixel movement must be an integer value (default
is 1). Any or no Command-Line arguments can be supplied and they can be
supplied in any order. */
if (args.length > 0) {
for (String arg : args) {
String value = "";
String cma = arg.contains(":") ? arg.split(":")[0].toLowerCase() : arg.toLowerCase();
switch (cma) {
case "-help":
case "/help":
case "/?":
case "-?":
displayHelp();
System.out.println();
System.exit(0);
break;
case "/i":
case "-i":
value = arg.split(":")[1].trim();
if (!value.matches("\\d+")) {
System.out.println("Invalid value (" + value + ") supplied to the /I:[n] command-line parameter!");
System.out.println("Ignoring this argument and default of " + this.interval + " will be used!");
break;
}
this.interval = Integer.parseInt(value);
break;
case "/x":
case "-x":
value = arg.split(":")[1].trim();
if (!value.matches("\\d+")) {
System.out.println("Invalid value (" + value + ") supplied to the /X:[n] command-line parameter!");
System.out.println("Ignoring this argument and default of " + this.pixelMovementX + " will be used!");
break;
}
this.pixelMovementX = Integer.parseInt(value);
break;
case "/y":
case "-y":
value = arg.split(":")[1].trim();
if (!value.matches("\\d+")) {
System.out.println("Invalid value (" + value + ") supplied to the /Y:[n] command-line parameter!");
System.out.println("Ignoring this argument and default of " + this.pixelMovementY + " will be used!");
break;
}
this.pixelMovementY = Integer.parseInt(value);
break;
default:
System.out.println("Invalid command-line argument supplied! (" + arg + ")");
System.out.println("This argument will be ignored!");
}
}
}
// Initialize the timer.
moveTimer = new javax.swing.Timer(interval, new moveTimerActionListener());
// Set some JFrame properties
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
/* Set up a Window Listener for JFrame to detect when it's
closing so that the Timer can stopped if it's running
and, return an application Exit indicator for the Console. */
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
// If the timmer is running then stop it.
if (moveTimer.isRunning()) {
moveTimer.stop();
System.out.printf("%-13s | %-25s%n", "Timer Stopped", getCurrentDateTime());
System.out.println("Timer Stopped!");
}
System.out.println("Application Closed!");
// Shut down application.
System.exit(0);
}
});
// Create the Start button and add to JFrame
javax.swing.JButton startButton = new javax.swing.JButton("Start");
frame.add(startButton, java.awt.BorderLayout.NORTH);
// Set some JTextArea properties and add JTextArea to JFrame
jTextArea.setEditable(false);
jTextArea.setText("NOT RUNNING: Mouse X: 0 - Mouse Y: 0 | Date-Time: "
+ getCurrentDateTime());
frame.add(jTextArea, java.awt.BorderLayout.CENTER);
// Create the Stop button and add to JFrame
javax.swing.JButton stopButton = new javax.swing.JButton("Stop");
frame.add(stopButton, java.awt.BorderLayout.SOUTH);
// Set the JFrame to center Screen and make it visible.
frame.setLocationRelativeTo(null);
frame.setVisible(true);
/* The Start Button ActionPerformed event. When the `Start`
button is selected, the timer starts. */
startButton.addActionListener(e -> {
/* If User tries to Start the Timer while it's already
running then prevent it and indicate `No Can Do` in
the Console and JTextArea. */
if (moveTimer.isRunning()) {
String curDateTime = getCurrentDateTime();
jTextArea.setText("Failed Start! Timer is still running! " + curDateTime);
System.out.printf("%-13s | %-25s%n", "Failed Start", curDateTime);
System.out.println("-------------------------------");
System.out.println("-- Failed To Restart! --");
System.out.println("-- Timer is still running! --");
System.out.println("-- Press STOP Button! --");
System.out.println("-------------------------------");
}
// Otherwise, indicate the timer has started.
else {
moveTimer.start();
System.out.println("--------------------");
System.out.println("-- Timer Started! --");
System.out.println("--------------------");
// Header Line in console for output data.
System.out.println("--------------------------------------------"
+ "--------------------------------------------");
System.out.println(" Status Date - Time "
+ " Form Dimensions Mouse Coordinates");
System.out.println("--------------------------------------------"
+ "--------------------------------------------");
}
});
/* The Stop Button ActionPerformed Event. When stop
button is selected, the timer Stops. */
stopButton.addActionListener(e -> {
// If the `moveTimer` Timer is not running then get otta here.
if (!moveTimer.isRunning()) {
return;
}
moveTimer.stop(); // Stop the timer.
String curDateTime = getCurrentDateTime();
// Place the 'Stopped' fact into the JTextArea.
jTextArea.setText("NOT RUNNING | STOPPED: Mouse X: " + firstX
+ " - " + "Mouse Y: " + firstY + " | Date-Time: " + curDateTime);
// Also place the 'Stopped' fact into the Console Window.
System.out.printf("%-13s | %-25s%n", "Stopped", curDateTime);
System.out.println("--------------------");
System.out.println("-- Timer Stopped! --");
System.out.println("--------------------");
});
}
public String getCurrentDateTime() {
/* Establish the current Date-Time using methods from the java.time package.
These methods a better than the antique & troublesome Date class. */
return java.time.LocalDate.now() + " - " + java.time.LocalTime.now();
}
private void displayHelp() {
System.out.println();
System.out.println("MoveMouseEverySecondDemo Command-Line Help:");
System.out.println("Command-Line Options:");
System.out.println("---------------------");
System.out.println(" /? or -? or /help or -help - This help information.");
System.out.println(" /I:[value] or -I:[value] - The interval at which the internal timer");
System.out.println(" should fire. The value provided must be in");
System.out.println(" milliseconds. Default is: 1000.");
System.out.println(" /X:[value] or -X:[value] - The desired amount of X axis (horizontal)");
System.out.println(" mouse pointer movement for every fired");
System.out.println(" interval. Default is 1.");
System.out.println(" /Y:[value] or -Y:[value] - The desired amount of Y axis (vertical)");
System.out.println(" mouse pointer movement for every fired");
System.out.println(" interval. Default is 1.");
}
/* A Inner-Class: The Action Listener for the Timer. On every timer interval,
the ActioPerformed Event is fired within this inner-class. */
class moveTimerActionListener implements java.awt.event.ActionListener {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// Establish current date-time for output.
String curDateTime = getCurrentDateTime();
// Get the current Mouse Pointer `X` location on the Screen.
int cursorPositionX = java.awt.MouseInfo.getPointerInfo().getLocation().x;
// Get the current Mouse Pointer `Y` location on the Screen.
int cursorPositionY = java.awt.MouseInfo.getPointerInfo().getLocation().y;
/* Apply the `X` location plus the desired movement amount
to the MoveMouseEverySecondDemo class `firstX` member
variable. */
firstX = cursorPositionX + pixelMovementX;
/* Apply the `Y` location plus the desired movement amount
to the MoveMouseEverySecondDemo class `firstY` member
variable. */
firstY = cursorPositionY + pixelMovementY;
// Let Robot move the mouse pointer to the new screen location.
robot.mouseMove(firstX, firstY);
// Update the information within the JTextArea.
jTextArea.setText("RUNNING: " + "Mouse X: " + firstX + " - "
+ "Mouse Y: " + firstY + " | Date-Time: " + curDateTime);
// Also update the information to Console Window:
System.out.printf("%-13s | %-25s | %-20s | %-22s%n", "Timer Running", curDateTime,
"Form Size: " + frame.getWidth() + ", " + frame.getHeight(),
"Mouse X: " + firstX + ", Y: " + firstY);
}
}
}
This runnable application will run if started from the IDE or if compiled to a JAR file and started from a Command/Console Window. The provided demo application above does of course allow for Command-Line arguments so to change some operational features. They are as follows:
/? or -? or /help or -help:
Displays help about the Command-Line arguments. Application closes after displaying.
/I:[value] or -I:[value]:
The Interval at which the internal timer should fire. The value provided must be in milliseconds. Default is: 1000 (1 second).
/X:[value] or -X:[value]:
The desired amount of X axis (horizontal) mouse pointer movement for every fired interval. Default is 1 (DPI or Pixel if you have a real good mouse with a high resolution setting).
/Y:[value] or -Y:[value]:
The desired amount of Y axis (vertical) mouse pointer movement for every fired interval. Default is 1 (DPI or Pixel if you have a real good mouse with a high resolution setting).
Any number of command-line arguments can be supplied and they can be supplied in any order. Letter case is also ignored. Any Invalid argument is ignored and its related default will be used.
This demo application will provide information in both the GUI or the Console Window. You choose what you want to keep.

Youtube Search Command for JDA Discord Music Bot

I've been working on a Discord bot for a few days now.
Initially only with simpler commands etc. But slowly I also devoted myself to the topic of music bot.
I also use the YouTube Data API for this and everything works so far. However, I would now like to incorporate a Youtube Search Command or build it into another (Play Command). I already have half a search command.
So far you can do $play (song title)
and the first track found will be selected.
However, I want to be able to see the first 10 search results and then choose between them.
I have already figured out how to display the search results, but now I need a little help with how to enter a command, after you have already entered another.
So you enter: $play Faded
Then a normal EmbedBuilder comes up and shows you the search results, and then you can select the desired track by entering 1, 2, 3, 4, 5, 6, 7, 8, 9 or 10.
This is the code:
public class PlayCommand implements ServerCommand {
private final YouTube youTube;
public PlayCommand() {
YouTube temp = null;
try {
temp = new YouTube.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
null
)
.setApplicationName("JDA Discord Bot")
.build();
} catch (Exception e) {
e.printStackTrace();
}
youTube = temp;
}
#Override
public void performCommand(List<String> args, Member m, TextChannel channel, Message message) throws RiotApiException {
String input = String.join(" ", args.subList(1, args.size() - 1));
if (!isUrl(input)) {
String ytSearched = searchYoutube(channel, input);
if (ytSearched == null) {
channel.sendMessage("Keine Ergebnisse!").queue();
return;
}
input = ytSearched;
}
PlayerManager manager = PlayerManager.getInstance();
manager.loadAndPlay(channel, input);
manager.getGuildMusicManager(channel.getGuild()).player.setVolume(100);
}
private boolean isUrl(String input) {
try {
new URL(input);
return true;
} catch (MalformedURLException ignored) {
return false;
}
}
#Nullable
private String searchYoutube(TextChannel channel, String input) {
String youtubeKey = "AIzaSyDoQ4OInMTYth7hdlWwQSIaHuxpxxv7eJs";
try {
List<SearchResult> results = youTube.search()
.list("id,snippet")
.setQ(input)
.setMaxResults(10L)
.setType("video")
.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)")
.setKey(youtubeKey)
.execute()
.getItems();
if (!results.isEmpty()) {
String videoId = results.get(0).getId().getVideoId();
/*EmbedBuilder builder = new EmbedBuilder();
builder.setTitle("Suchergebnisse");
builder.setColor(Color.RED);
builder.setDescription( "1. " + results.get(0).getSnippet().getTitle() + "\n" +
"2. " + results.get(1).getSnippet().getTitle() + "\n" +
"3. " + results.get(2).getSnippet().getTitle() + "\n" +
"4. " + results.get(3).getSnippet().getTitle() + "\n" +
"5. " + results.get(4).getSnippet().getTitle() + "\n" +
"6. " + results.get(5).getSnippet().getTitle() + "\n" +
"7. " + results.get(6).getSnippet().getTitle() + "\n" +
"8. " + results.get(7).getSnippet().getTitle() + "\n" +
"9. " + results.get(8).getSnippet().getTitle() + "\n" +
"10. " + results.get(9).getSnippet().getTitle());
channel.sendMessage(builder.build()).queue();
*/
return "https://www.youtube.com/watch?v=" + videoId;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
I think you are looking for an EventWaiter.
With JDA-Utilities you can achieve what you want.
You just basically wait for an event, check if it's suitable for the use case of yours (eg: is a specific event, or contains a specific text)
Check out this stackoverflow answer about EventWaiter and adding it as an EventListener.
You would want to check if the received text for example is part of the youtube search result. Also don't forget about having a time limit for accepting answers.

getInt Function Doesn't Return Anything

I am currently trying to making a custom rules plugin (for minecraft) and I am trying to see if the player has something activated which I stored in the config file. It is in the listener class (which calls the config from the main). Here is my code:
#EventHandler
public void onEvent(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (config.getInt("EditingLine." + player.getName().toLowerCase()) == 1) {
int line = 0;
try {
line = Integer.parseInt(e.getMessage());
} catch (Exception b) {
player.sendMessage(ChatColor.RED + "Invalid Number.");
config.set("EditingLine." + player.getName().toLowerCase(), 0);
}
if (!(line == 0)) {
config.set("EditingLine." + player.getName().toLowerCase(), 0);
config.set("EditingText." + player.getName().toLowerCase(), 1);
e.setCancelled(true);
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.GOLD + "Custom Rules" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enter the text you would now like on that line.");
}
}
}
The, config.getInt() function in the if then statement currently returns nothing. This may be happening because the config in the Listener Class is actually calling a custom made config, called 'playerdata.yml' and not the actual 'config.yml'. If there is any easier way to write this script, also let me know. I'm trying to make this as simple as I can.
The answer has been solved by merging my two configuration files together.

Threads in Java, states? Also what is the right way to use them?

I'm up for my exame presentation the day after tomorrow, so i need to get some straight before it which i hope you guys can help me with.
First i do know that there are 4 states of Threads (i.e Running, Ready, Blocked, Terminated), however i'm not quite sure how it works in Java. In my code i use the thread.sleep(3000) to do some waiting in the program, does this make the thread Blocked or Ready?
Also it have come to my attention that i might not have used the threads the right way, let me show you some code
public class BattleHandler implements Runnable {
private Player player;
private Monster enemyMonster;
private Dungeon dungeon;
private JTextArea log;
private GameScreen gScreen;
public void run() {
try {
runBattle();
}
catch(Exception e) { System.out.println(e);}
}
public BattleHandler(Player AttackingPlayer, JTextArea log, GameScreen gScreen) {
this.player = AttackingPlayer;
this.log = log;
this.gScreen = gScreen;
}
public void setDungeon(Dungeon dungeon) {
this.dungeon = dungeon;
}
public Dungeon getDungeon() {
return dungeon;
}
public Monster getEnemyMonster() {
return enemyMonster;
}
public void setMonster() {
// First check if dungeon have been init, if not we can't generate the mob
if(dungeon != null) {
enemyMonster = new Monster();
// Generate monster stats
enemyMonster.generateStats(dungeon);
}else {
System.out.println("Dungeon was not initialized");
}
}
public void runBattle() throws InterruptedException {
// Start battle, and run until a contester is dead.
while(player.getHealth() > 0 && enemyMonster.getHealth() > 0) {
int playerStrikeDmg = player.strike();
if(enemyMonster.blockDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else if(enemyMonster.dodgeDefend()) {
log.setText( log.getText() + "\n" + player.getName() +" tried to strike " + enemyMonster.getName()+ ", but " + enemyMonster.getName() + " Blocked.");
}else {
enemyMonster.defend(playerStrikeDmg);
log.setText( log.getText() + "\n" + player.getName() +" strikes " + enemyMonster.getName()+ " for: " + playerStrikeDmg + " left: "+ enemyMonster.getHealth());
}
if(enemyMonster.getHealth() < 1) break;
Thread.sleep(3000);
// Monster Turn
int monsterDmg = enemyMonster.strike();
if(player.blockDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Blocked.");
}else if(player.dodgeDefend()) {
log.setText( log.getText() + "\n" + enemyMonster.getName() +" tried to strike " + player.getName()+ ", but " + player.getName()+ " Dodged.");
}else {
player.defend(monsterDmg);
log.setText( log.getText() + "\n" + enemyMonster.getName() +" strikes " + player.getName()+ " for: " + monsterDmg + " left: "+ player.getHealth());
}
gScreen.updateBot();
Thread.sleep(3000);
}
When i coded this i thought it was cool, but i have seen some make a class just for controlling the Thread itself. I have just made the class who uses the Sleep runable(Which is not shown in the code, but its a big class).
Would be good to get this straight, so i can point i out before they ask me about it, you know take away there ammunition. :D
Hope you guys can help me :).
Thx
Threads have more than 4 states. Also, I recommend reading Lesson: Concurrency for more information regarding threads.
Note that if you're looking to execute a task at a set interval, I highly recommend using the Executors framework.
Blocked - it will not run at all until timeout. Ready is 'runnable now but there is no processor available to run it - will run as soon as a processor becomes available'.
As all the other guys state, there are more than those, here's a simple listing:
Running - Guess what, it's running
Waiting - It waits for another thread to complete its calculation (that's the wait() method in Java). Basically such a thread can also be run by the scheduler, like the "ready" state threads.
Ready - Means that the Thread is ready for execution, once the OS-Scheduler turns to this Thread, it will execute it
Blocked - Means that there is another operation, blocking this threads execution, such as IO.
Terminated - Guess what, it's done and will be removed by the OS-Scheduler.
For a complete listing, look at the famous Wikipedia ;)
http://en.wikipedia.org/wiki/Process_state

Java script add element without reload

I have this div in which I add more divs with javascript.
However, everytime I add a new div the to div with javascript, it refreshes so for example a youtube video in one of those divs will stop playing.
Can I put these divs into the div without reloading it?
My current code for putting in thing is
m += "new thing <a> and other stuff </a>"
I NEED it to put the new thing I want without reload.
I currently put them in using href="javascript: addMessage('current time', 'user', 'message')"
The addMessage code:
function addMessage(time, user, msg) {
if (msg == "") {
return false;
}
var m = document.getElementById('message-panel');
m.innerHTML += "<div class='sentMessage'><span class='time'>" + time + "</span><span class='name'><a>" + user + "</a></span><span class='message'>" + msg + "</span></div>";
pageScroll();
if (user != "SERVER") {
if (user != "ERROR") {
playAudio('new-message-sound');
}
}
return false;
}
My only solution to putting new messages in if with href="javascript:addMessage()". I CAN NOT DO ONCLICK="" because I'm using java to controll the javascript!
My javacode for putting in the messages:
public void addMessage(String user, String msg) {
try {
getAppletContext().showDocument(new URL("javascript:addMessage(\"" + Time.now("HH:mm") + "\", \"" + user + "\", \"" + msg + "\")"));
}
catch (MalformedURLException me) {}
}
Thanks in advance, enji
Create the element with document.createElement('tag name here');, then insert it with m.appendChild(newelement);. This leaves any elements before it unaffected.

Categories