Divide and update Text Area in JAVAFX at runtime - javafx-2

My application is developed using JavaFX. I send a command from the JavaFX client to a jar file on a solaris machine and take the output of that jar file and display it on text area in my JavaFX application using JSCH. Originally, there was only one thread in the jar file present on the solaris machine, so all output was sequential and there was no confusion. But now i have implemented multithreading in the JAR file present on Solaris AND this caused an issue as below:
I want To display the output of each thread differently in the text area. I want to divide the text area into parts equal to the number of threads used in the solaris machines jar file. I have found the way send the number of threads from solaris to my JavaFX application.
How can I divide the text area into parts?
Below is the code where i am printing output of a thread in the text area:
while ((jarOutput = reader.readLine()) != null) {
this.logger.info("Status Update = " + jarOutput);
bw.write(jarOutput);
bw.newLine();
bw.flush();
outputFromUnix.append(jarOutput).append("\n");
// Display in activity log area in realtime.
if (DeploymentTaskController.actLogTArea != null
&& !taskName.equalsIgnoreCase(connectBundle)) {
final String outputStr = outputFromUnix.toString();
Platform.runLater(new Runnable() {
#Override public void run() {
DeploymentTaskController.actLogTArea.setText(outputStr);
DeploymentTaskController.actLogTArea.end();
}
});
}
}

Related

GTK Data Capturing

I’m working in C on a project to capture data from a sensor and display it as part of a GUI application on the Raspberry Pi. I am using GTK 3.0, plus Cairo for graphing. I have built an application that works, but I want to make a modification to enable me to change the frequency of data capture.
Within my main code section I have a command like:-
gdk_threads_add_timeout (250, data_capture, widgets);
This all works, the data capture routine is triggered every 250mS, but I want to add functionality to the GUI to enable the user to change the speed. If I try to call this function from anywhere else other than main, it fails.
I have looked for other ways to do it, but I can’t find any examples or explanations of how I can do it.
Ideally what I would like is something like:-
void update_speed(button, widgets)
// Button to change speed has been pressed
read speed from GUI
update frequency
return
int main()
...
setup GUI
set default speed
start main GTK loop
Does anyone have any idea how I could achieve this?
Edit: Additional Code Snippet
(This is not the whole program, but an extract of main)
int main(int argc, char** argv) {
GtkBuilder *builder;
GtkWidget *window;
GError *err = NULL; // holds any error that occurs within GTK
// instantiate structure, allocating memory for it
struct app_widgets *widgets = g_slice_new(struct app_widgets);
// initialise GTK library and pass it in command line parameters
gtk_init(&argc, &argv);
// build the gui
builder = gtk_builder_new();
gtk_builder_add_from_file (builder, "../Visual/gui/main_window.glade", &err);
window = GTK_WIDGET(gtk_builder_get_object(builder, "main_application_window"));
// build the structure of widget pointers
widgets->w_spn_dataspeed = GTK_SPIN_BUTTON(gtk_builder_get_object(builder, "spn_dataspeed"));
widgets->w_spn_refreshspeed = GTK_SPIN_BUTTON(gtk_builder_get_object(builder, "spn_refreshspeed"));
widgets->w_adj_dataspeed = GTK_ADJUSTMENT(gtk_builder_get_object(builder, "adj_dataspeed"));
widgets->w_adj_refreshspeed = GTK_ADJUSTMENT(gtk_builder_get_object(builder, "adj_refreshspeed"));
// connect the widgets to the signal handler
gtk_builder_connect_signals(builder, widgets); // note: second parameter points to widgets
g_object_unref(builder);
// Set a timeout running to refresh the screen
gdk_threads_add_timeout(SCREEN_REFRESH_TIMER, (GSourceFunc)screen_timer_exe, (gpointer)widgets);
gdk_threads_add_timeout(DATA_REFRESH_TIMER, (GSourceFunc)data_timer_exe, (gpointer)widgets);
gtk_widget_show(window);
gtk_main();
// free up memory used by widget structure, probably not necessary as OS will
// reclaim memory from application after it exits
g_slice_free(struct app_widgets, widgets);
return (EXIT_SUCCESS);

Separate red color stream from Microsoft Kinect color camera video stream

I want to separate red, green, blue color streams from Microsoft Kinect color camera video stream. So far, to receive the color video stream, I've used the sample code provided with Kinect for Windows SDK 2.0.
An event handler for the color frames writes the frames to a WriteableBitmap object whenever a new frame is received. How can I separate the red color stream from the color frames before they are copied to the WriteableBitmap object?
private void Reader_ColorFrameArrived(object sender, ColorFrameArrivedEventArgs e)
{
// ColorFrame is IDisposable
using (ColorFrame colorFrame = e.FrameReference.AcquireFrame())
{
if (colorFrame != null)
{
FrameDescription colorFrameDescription = colorFrame.FrameDescription;
using (KinectBuffer colorBuffer = colorFrame.LockRawImageBuffer())
{
this.colorBitmap.Lock();
// verify data and write the new color frame data to the display bitmap
if ((colorFrameDescription.Width == this.colorBitmap.PixelWidth) && (colorFrameDescription.Height == this.colorBitmap.PixelHeight))
{
colorFrame.CopyConvertedFrameDataToIntPtr(
this.colorBitmap.BackBuffer,
(uint)(colorFrameDescription.Width * colorFrameDescription.Height * 4),
ColorImageFormat.Bgra);
this.colorBitmap.AddDirtyRect(new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight));
}
this.colorBitmap.Unlock();
}
}
}
}
Daily .NET Tips has an article about this but the code they show here is not clear enough. This is the result I need (and the one Daily .NET Tips show in their article).
Please help.
Using this method - colorFrame.CopyConvertedFrameDataToIntPtr - I was not able to manipulate the actual bytes from the framedata.
You need to do it manually, and process the bytes in a for loop.

Wait() & Sleep() Not Working As Thought

Using JavaFX 8.0 and JRE 1.8.0 u45 in IntelliJ, I created a basic pixel editor app. I have two windows(stages). One is a 32x128 matrix of Circle Objects placed in a Grid Pane and the other, a Tools widow; I have one Controller.java. Using the mouse, the Tools window provides tools to draw lines, rectangles, etc. and a menu for Setup, Files and Playlists. The Files menu presents the user with Open, SaveAs and Delete. To view a saved pixel art file, the user clicks Open and via the JFileChooser, the selected file is opened and each Circle’s assigned color is displayed using the following method:
public static void openFile( String pathName) throws IOException {
path = Paths.get(pathName);
pixelByteArray = Files.readAllBytes(path);
int cnt = 0;
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
String hexRGB = String.format("#%02X%02X%02X",
pixelByteArray[cnt++], //red
pixelByteArray[cnt++], //green
pixelByteArray[cnt++]); //blue
Color color = Color.valueOf(hexRGB);
pixelArray[r][c].setFill(color);
}
}
String fileName = path.getFileName().toString();
window.setTitle(MessageFormat.format("Pixel Array {0} x {1} File: {2}", Integer.toString(row), Integer.toString(col), fileName));
} // openFile
The Circle’s color is updated with for loops using setFill(color).
Next I created a class to test a basic slide show. I would use JFileChooser to select multiple files, put them in an ArrayList<file> and use the openFile(pathname) in a for loop to display each, pausing 5 secs between each openFile(pathname) as shown below:
public class PlayPlaylist {
public static void playPlaylist() throws IOException, InterruptedException {
FileChooser fileChooser = new FileChooser();
fileChooser.setInitialDirectory(new File("C:\\ProgramData\\L1 Art Files\\"));
fileChooser.setTitle("Play One or More Pixel Art Files");
java.util.List<File> selectedFiles = fileChooser.showOpenMultipleDialog(null);
for (File selectedFile : selectedFiles) {
openFile(selectedFile.getPath());
sleep(5000);
}
} //Method playPlaylist()
I first used wait(5000) but couldn’t compile because I have a static method, which I need. The wait() method won’t run in a static method. I then tried sleep(5000) which compiles but to my confusion only the last file in the ArrayList<file> will be displayed. All the pixel art files will display the setTitle() correctly and pause for about 5 secs but the Circle’s will not change to the assigned color except for the last file, after the 5 secs have passed. The for loop, setFill(color) process in openFile() seems to be paused even though the setTitle() is executed correctly, which is after the setFill(color) process?
I’m new to Java and JavaFX and have never created any threads directly in this program or any other but researching possible problems implies the problem may be related to threads.
Is there a classic fix to this problem? Thanks for any help
After studying the references and suggested solutions below, I am unable to fix the problem. I tried two code changes. The first was to the for loop code above:
for (File selectedFile : selectedFiles) {
Platform.runLater(() -> {
try {
openFile(selectedFile.getPath());
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
});
The second change was to the openFile(pathname) above:
final int finalR = r;
final int finalC = c;
Platform.runLater(() -> pixelArray[finalR][finalC].setFill(color));
I get the same results as described above with only the last file being displayed. If I simply select one file in the Arraylist<File> it will display, i.e.:
if (selectedFiles != null) {
File playFile = selectedFiles.get(0);
openFile(playFile.getPath());
System.out.println("\n File 1 = " + playFile.getPath());
}
Now if I add Sleep(5000):
if (selectedFiles != null) {
File playFile = selectedFiles.get(0);
openFile(playFile.getPath());
System.out.println("\n File 1 = " + playFile.getPath());
sleep(5000);
}
It will display the pixel art file after 5 secs. What I don't understand is why it appears to "skip" over the pixelArray[r][c].setFill(color)); which sets all the Circle's to the saved colors but does execute the following and last statement in the openFile(pathname) which is setTitle(...)? It's like sleep(5000) blocks the pixelArray[r][c].setFill(color));but nothing else?
Why can I openFile(pathname) for just one file with proper results but not two or more in sequence?
I also have the two UI windows posted on the web at: Virtual Art. I think the pixel art shown in the Pixel Array window clarifies the goal of creating a user-defined slide show.
***This question was answered elegantly by jewelsea at:
How to avoid Thread.sleep() in a for loop from interrupting the UI Thread?***
You have two problems here, your understanding of wait(), and a GUI multithreading issue.
About the GUI multithreading... You will find more informations here about Platform.runLater(...):
Platform.runLater and Task in JavaFX
Now about Wait... It will pause your Thread until a Notify event is received through its monitor. To be able to call notify() you need to synchronize on the same object (the monitor).
synchronized (someObject) {
someObject.wait();
}
/* different thread / object */
synchronized (someObject) {
someObject.notify();
}
If you want to use Wait, you will need another Thread (a Timer?), to wakeup/notify you. Sleep should work fine in your case, as long as you use Platform.runlater(...)

How to change cursor image size in JavaFX 2.1?

I changed image of cursor. I am trying to change size of cursor image but i couldnt. How can i change it's size? Thanks in advance.
You can change the cursor by using one of the predefined cursor types or supplying an image to have your own cursor, but the system will automatically resize your supplied image based upon the cursor size support of the underlying platform. See the documentation for ImageCursor.getBestSize() and ImageCursor.chooseBestCursor() for details of the algorithm used to choose determine the actual cursor size used.
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.stage.*;
public class ResizableCursor extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
StackPane layout = new StackPane();
layout.setCursor(Cursor.cursor("http://icons.iconarchive.com/icons/artua/star-wars/256/Death-Star-icon.png"));
stage.setScene(new Scene(layout, 200, 200));
stage.show();
}
}
If you want to have an arbitrarily sized node which moves with the mouse and looks and acts like a cursor (but is not a cursor), you can set the cursor to Cursor.NONE, then translate a node to follow the mouse location (as is done in this example when you click on a circle to move it around). Using this strategy it will seem as though the user has a custom cursor of arbitrary size, even though they don't.
Copy of relevant documentation for ImageCursor.getBestSize():
Gets the supported cursor size that is closest to the specified
preferred size. A value of (0,0) is returned if the platform does not
support custom cursors.
Note: if an image is used whose dimensions don't match a supported
size (as returned by this method), the implementation will resize the
image to a supported size. This may result in a loss of quality.
Note: These values can vary between operating systems, graphics cards
and screen resolution, but at the time of this writing, a sample
Windows Vista machine returned 32x32 for all requested sizes, while
sample Mac and Linux machines returned the requested size up to a
maximum of 64x64. Applications should provide a 32x32 cursor, which
will work well on all platforms, and may optionally wish to provide a
64x64 cursor for those platforms on which it is supported.
VBox vBoxMainLayout = new VBox();
Scene scene = new Scene(vBoxMainLayout);
Image img = newImage(getClass().getResourceAsStream("image.png"));
ImageCursor cursor = new ImageCursor(img, 30, 30);
scene.setCursor(cursor);
import java.awt.Toolkit;
import javafx.scene.Cursor;
import javafx.scene.image.Image;
public class ColorChooser extends Cursor
{
public override function impl_getAWTCursor(): java.awt.Cursor {
def url = "{__DIR__}eyedropper.png";
var toolkit = Toolkit.getDefaultToolkit();
var image = Image{width:32 height:32 url:url}.bufferedImage;
var hotspot = new java.awt.Point(0,15);
var cursor = toolkit.createCustomCursor(image, hotspot "colorpicker");
return cursor;
}
}

How to limit frame resizing based on view's size? MFC doc/view architecture

MFC doc/view architecture, sdi (more precisely multiple top-level windows).
In my view class, I set my "playground" (i.e. logical space) with SetScrollSizes(); Then I want to limit maximum frame window size to that of view's maximum size.
Here is what I'm doing but I think there might be better solution, please advice:
I'm implementing OnGetMinMaxInfo() in my CMainFrame. There I try to get active view's scroll sizes, and set lpMMI->ptMaxTrackSize appropriately. Below is the code:
void CMainFrame::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
// Call base version:
CFrameWndEx::OnGetMinMaxInfo(lpMMI);
// Get active view:
CScrollView *pScrollView = (CScrollView *)GetActiveView();
if (pScrollView && pScrollView->IsKindOf(RUNTIME_CLASS(CMyFckinView)))
{
// Get total size of playground:
CSize sizePlayground = pScrollView->GetTotalSize();
// Test if the size is non-zero, i.e. there is at least one node displayed:
if (sizePlayground.cx && sizePlayground.cy/* && !IsPrintPreview()*/)
{
// Set maximum window size to match our playground size:
CRect rectClient, rectWindow;
pScrollView->GetClientRect(&rectClient);
this->GetWindowRect(&rectWindow);
if (rectWindow.top > -5000 && rectWindow.left > -5000) // Avoid when minimized...
{
lpMMI->ptMaxTrackSize.x = sizePlayground.cx + (rectWindow.Width() - rectClient.Width());
lpMMI->ptMaxTrackSize.y = sizePlayground.cy + (rectWindow.Height() - rectClient.Height());
return;
}
}
}
}
This works but has one problem: When print preview is displayed (standard MFC print preview), I obviously want to allow free window resizing, so I use runtime info GetActiveView()->IsKindOf(...) to determine that active view is really my view, and not print-preview's view (which is CPreviewViewEx). But when I close the print preview, OnGetMinMaxInfo is not called, so I'm unable to adjust frame size according to my view again. As soon as I move the window OnGetMinMaxInfo gets called again and correctly adjusts frame size, but without manually moving the window old size (to which the print preview was sized to) is retained and has ugly artifact.
What can I do? Basically if I could trap the moment when print preview is closed, I could use following trick:
// Trigger the WM_MINMAXINFO message:
CFrameWnd *pFrame = GetParentFrame();
RECT rectWindow;
pFrame->GetWindowRect(&rectWindow);
pFrame->MoveWindow(&rectWindow);
But I don't know how to trap print-preview closure.
What I'm trying to accomplish seems quite standard: who would want to have frame window resized bigger than view's logical size (set by SetScrollSizes())? So there should be some more natural solution maybe?
In your CMyFckinView, handle a message that is reliably sent when the print preview is closed and then post a user message to the mainframe which will trigger your "force minmax" code. Perhaps WM_FOCUS or WM_ACTIVATE?

Resources