JavaFX - Why system.out.println doesn't work in my application - javafx

I want to get a console output in my application debugging, but wherever I put println method console doesn't print anything. For example, I want to get "Hi" after clicking the "play" button, everything except println, will invoke normally.
#FXML
protected void handlePlayButton(ActionEvent event) {
System.out.println("hi!");
filePath = cTable.getSelectionModel().getSelectedItem().getFilePath();
index = cTable.getSelectionModel().getSelectedIndex();
player = new Play();
player.player(filePath);
}

There might be an issue with where the stdout is pointing. Are you running it inside an IDE or might it have been redirected somewhere else in your code?

Related

My Windows application freezes using Background worker threads

I have written an application that uses background workers for long running tasks. At times, after the task is completed, the application will freeze. It doesn't do it right away, it will do it after the application sits idle for a little bit of time.
To try to find out where it is hanging, in my development environment I ran it and waited for it to freeze. I then went to Debug > Break All. It is hanging in the Main() method in Program.cs:
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main());
}
}
The Application.Run line is highlighted as where the application is hung. When I hover my cursor over the carat in the left border I get a tool tip saying "This is the next statement to execute when this thread returns from the current function."
In looking at this code I realized that it is calling the "main" form of the application, which I named "Main." So my first question is does this matter since the current method is named "Main" also? If so, what are the ramifications of renaming the form, if that is possible?
If that is not an issue, then it would go back to the background worker I would imagine. The application never freezes if those long running tasks are never ran. I know that you should never try to access the UI thread from a background worker thread and I don't think I'm doing that but here is some code that hopefully someone may spot something:
First I start the thread from the UI thread passing in an argument:
bgwInternal.RunWorkerAsync(clients)
In the DoWork method it calculates and creates invoices for the passed in argument (clients). It creates PDF files and saves them to disk. None of that work tries to access the UI. It does use the ProgressChanged event handler to update a progress bar and a label in the UI:
private void bgwInternal_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pgbProgress.Value = e.ProgressPercentage;
lblProgress.Text = e.ProgressPercentage.ToString();
}
And finally the RunWorkerCompleted event handler:
private void bgwInternal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("Error occurred during invoice creation.\n\r\n\rError Message: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (!e.Cancelled)
{
MessageBox.Show("Invoice Creation Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Invoice Creation Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
btnCreateInv.Enabled = true;
btnClose.Enabled = true;
btnCancel.Enabled = false;
}
Could it be hanging because I'm accessing UI elements in this event handler?
One final note, I was using Application.DoEvents():
while (bgwInternal.IsBusy)
{
Application.DoEvents();
}
But I commented that out to see if it would make a difference and it did not.
Not having a lot of multithreading experience I chose to use background worker threads because they are simple and straightforward. Other than using Debug > Break All I really don't know how to track down the exact reason this is happening.
Any thoughts / ideas would be greatly appreciated.
Thanks.

fxmlLoader.load() will not load object hiearchy

I have 2 windows (login and main) with appropriate controllers.
I got this piece of code. This is located in LoginController.java. When I run app, it will open login window from /fxml/login.fxml where the LoginController is set with fx:controller. Then there is Sign In button. Method signIn() is asociated with this button. When i click it, it will close Login window, get controller of main window and open main window from specific fxml file (/fxml/main.fxml). Meanwhile it will get strings from Login window's text fields and pass them to the MainController (those credentials are used in execution of SQL statements).
public void signIn(ActionEvent event) {
MngApi.closeWindow(btn); //closes parent window of specified node
try{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
Parent root1 = fxmlLoader.load();
Stage stage = new Stage();
stage.setTitle("PrintED");
stage.setScene(new Scene(root1, 1058, 763));//1058, 763
MainController ctrl = fxmlLoader.getController();
ctrl.setCredentials(uName.getText(), uPasswd.getText(),
ipAddress.getText(), dbName.getText());
stage.show();
}catch (IOException e){
}
}//signIn end
Now this is the problem: When i click Sign In button, the signIn() method will execute, Login window will close and SUCCESSFUL BUILD will pop up. No other window will open. After debugging I found out that program will stop at this line (everything before is done)
Parent root1 = fxmlLoader.load();
No error, no information, only successfull build. The most mysterious thing for me is that it worked before! Login wondow got closed and main windows appeared. I only added some new methods, action events and stuff. I made no changes to LoginController and fxml file. I only made changes to MainController (added methods and action event for buttons in main.fxml).
I have no idea what's bad and i am clueless. Please help!
Okay so I found out whats wrong. The error was in initilize() method. There i put a method which should initialize columns in my TreeTableView. I thought that when i run program, initialize wil execute (after Controller constructor) and it will run code line by line. so i put there initializeColumns() method, si it will execute first and only once. Looked like this:
public void initialize(){
initializeOrdersColumns();
//this listener will load (refresh) orders automaticaly when Orders Tab is selected
tabOrders.setOnSelectionChanged((event) -> {
if (tabOrders.isSelected()) {
List<TreeItem<Order>> allOrdersList = new ArrayList<>();
stackItems(allOrdersList, root);
root = new TreeItem<>();
ttwOrders.setRoot(root);
ttwOrders.setShowRoot(false);
}
});
//When we click refresh button, orders tab will reload Orders
btnOrdersRefresh.setOnAction((event) -> {
List<TreeItem<Order>> allOrdersList = new ArrayList<>();
stackItems(allOrdersList, root);
root = new TreeItem<>();
ttwOrders.setRoot(root);
ttwOrders.setShowRoot(false);
});
}//end of initialize()
After I deleted content of initialize() method, everything went well, so it was obvious that error code is in there. Then I commented all code except first method (initializeColumns()) and program went wrong. When I commented only initializeColumns() method the program went well again. So it was clear, initializeColumns() cannot be in initialize() method. Don't know why yet, but i will find out.

Unity - GameObject.Find() works only on server

I am making a simple networking game. The scene has a button named 'ReloadButton' and i am trying to find this button and add a listener to it through my script attached on the player.
private Button reloadBtn;
void Start()
{
GameObject tempGO = GameObject.Find("ReloadButton");
if (tempGO != null)
{
reloadBtn = tempGO.GetComponent<Button>();
reloadBtn.onClick.AddListener(weaponManager.Reload);
}
}
I am doing it this way because direct referencing of 'ReloadButton' to the script through public Buttonvariable is not possible.
The code works fine on the server, the listener is also added correctly. but on the client, the GameObject.Find("ReloadButton") throws a NullReferenceException.
Seems like the client cannot find the Button itself.
I cannot proceed further in my project without solving this problem, I hope some of you can point me towards the problem.

Automatically read a file - easy

This should be a really easy question, but I just cant seem to get it done, I have a section of code calculating X Y points on a graph, then saving them to file.
If a certain condition is met I want to plot the values on a graph, I am using this code to plot the graph- http://www.kodejava.org/examples/805.html
But I don't want it to ask for the user to point to the file location, I just want it to open a file which has a directory hard coded in, and plot it automatically. So basically remove the buttons at the top and carry out the commands of the buttons automatically.
Would be fantastic if somebody could point me in the right direction, I'm a physicist not a coding expert so as much help as possible would be excellent.
Hope I can help one of you in return sometime.
1) Inside public static void main, just above frame.setVisible(true); insert openButton.setVisible(false);
2) Inside class GraphPanel, inside the method public void actionPerformed(ActionEvent e) insert datapanel.actionPerformed(e); as the first line.
3) Inside class DataPanel inside public void actionPerformed comment out from the beginning JFrame fileFrame = new JFrame(); to initialized = readFile(datafile);
4) Just after the comment, insert initialized = readFile(new File("path_to_data_file"));
Now if you open, and press plot, the hard coded file will be read and plot will be drawn.
Heck,, I don't care if this gets downvoted :). I've never touched Java. After reading your problem, specially I'm a physicist not a coding expert first i searched in google how to compile and run a java file. Then started reading the java program. I even made another version which does not need the button press also, Just open and your graph will be drawn. But that's only if needed, then provided. "Welcome to my java attempt" :)
Update:
For doing without pressing plot, in GraphPanel and DataPanel, and rename the actionPerformed methods to something else like GraphPanel::start_working and DataPanel::start_working Now inside GraphPanel::start_working call DataPanel::start_working instead of earlier datapanel.actionPerformed(e); . If compiler cribs, add some empty actionPerformed for compilation. (perhaps we can remove the implements ) Now your flow is ready without any user action. you just need to start it. So you set plotButton.setVisible(false); to hide the plot button and call graphpanel.start_work(); to start the flow in main.
Update:
Inside GraphPanel
public void start_working() {
datapanel.start_working()
if (!datapanel.isInitialized()) {
return;
}
datapanel.refreshData();
panel.setDisplayPlot(true);
panel.update(panel.getGraphics());
frame.setSize(700, 600);
frame.setVisible(true);
frame.pack();
}
And inside DataPanel
public void start_working(ActionEvent e) {
initialized = readFile(new File("PATH_TO_FILE");
panel.update(panel.getGraphics());
frame.pack();
frame.setVisible(true);
}
in main last 5 lines
openButton.setVisible(false);
plotButton.setVisible(false);
graphpanel.start_working();
frame.setVisible(true);
frame.pack();

How can I create a button on a form in a J2ME application?

I attempt to make a simple "hello world" application, where on clicking the button , it prints a string "hello world". How can I add a button on a form?
I need to create a button, on which when I click it can produce a string. How can I add a button without using canvas in j2me?
There is an API for this, but you better think twice whether you really need it.
API is desctibed in the Appearance modes section for lcdui Item objects
The StringItem and ImageItem classes have an appearance mode attribute that can be set in their constructors. This attribute can have one of the values PLAIN, HYPERLINK, or BUTTON. An appearance mode of PLAIN is typically used for non-interactive display of textual or graphical material. The appearance mode values do not have any side effects on the interactivity of the item. In order to be interactive, the item must have one or more Commands (preferably with a default command assigned), and it must have a CommandListener that receives notification of Command invocations...
A StringItem or ImageItem in BUTTON mode can be used to create a button-based user interface...
Note that this section also explains cases when using button appearance might be problematic:
...This can easily lead to applications that are inconvenient to use. For example, in a traversal-based system, users must navigate to a button before they can invoke any commands on it. If buttons are spread across a long Form, users may be required to perform a considerable amount of navigation in order to discover all the available commands. Furthermore, invoking a command from a button at the other end of the Form can be quite cumbersome. Traversal-based systems often provide a means of invoking commands from anywhere (such as from a menu), without the need to traverse to a particular item. Instead of adding a command to a button and placing that button into a Form, it would often be more appropriate and convenient for users if that command were added directly to the Form. Buttons should be used only in cases where direct user interaction with the item's string or image contents is essential to the user's understanding of the commands that can be invoked from that item.
From the class diagram I found in an old J2ME book, and which is online at http://www.stardeveloper.com/articles/display.html?article=2002121101&page=2 it seems that J2ME don't do buttons. Well no need for them on an old mobile phone.
Just create a "hello" command and add it to a menu or form. The system will then put it on whatever button is available on your device. For touch screen devices that probably turns it into something clickable.
Here's the code
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HelloWorld extends MIDlet implements CommandListener {
private static final String HELLO_WORLD = "Hello, World!!";
private Form form= new Form ("");
private Command exit= new Command("Exit", Command.EXIT, 0x01);
private Command ok= new Command("OK", Command.OK, 0x01);
private Command hello= new Command("HELLO", Command.SCREEN, 0x01);
private TextBox textBox= new TextBox("Hello World", HELLO_WORLD, HELLO_WORLD.length(), TextField.UNEDITABLE);
public HelloWorld() {
this.form.addCommand(exit);
this.form.addCommand(hello);
this.form.setCommandListener(this);
this.textBox.addCommand(ok);
this.textBox.addCommand(exit);
this.textBox.setCommandListener(this);
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException { }
protected void pauseApp() { }
protected void startApp() throws MIDletStateChangeException {
Display.getDisplay(this).setCurrent(this.form);
}
public void commandAction(Command c, Displayable d) {
if (c == this.exit) {
this.notifyDestroyed();
}
if(c == this.ok) {
Display.getDisplay(this).setCurrent(this.form);
}
if(c == this.hello) {
Display.getDisplay(this).setCurrent(this.textBox);
}
}
}

Resources