listcell disappears when updating image - javafx-8

When I update the status of the object in a list, a icon in the listCell object in a ListView should change. The progress and ok png works as it should, but when changing to any other png, the listCell object is removed.
Lets say the status changes from progress to critical, then the listcell is removed, but using the ok.png instead, then it won't be removed. So it seems to be something with the images.
critical pictue
ok picture
package MMaaSCollector.windows;
import java.io.IOException;
import MMaaSCollector.Log;
import MMaaSCollector.systems.Host;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
public class HostCellData {
#FXML private AnchorPane bg;
#FXML private Label displayName;
#FXML private Label type;
#FXML private ImageView status = new ImageView();
public HostCellData()
{
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/MMaaSCollector/windows/HostListCell.fxml"));
fxmlLoader.setController(this);
try
{
fxmlLoader.load();
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
public void setInfo(Host host, double width) {
displayName.setText(host.getDisplayName());
type.setText(host.getType());
bg.setPrefWidth(width-17.0-17.0);
if (host.isStatusGathering()) {
Image progress = new Image("/MMaaSCollector/images/progress.gif");
status.setImage(progress);
Log.debugInfo(host.getDisplayName() + " has progress indicator.", 96);
} else if (host.isStatusFailed()) {
Image failed = new Image("/MMaaSCollector/images/fail.png");
status.setImage(failed);
Log.debugInfo(host.getDisplayName() + " has failed indicator.", 96);
} else if (host.isStatusOK()) {
Image ok = new Image("/MMaaSCollector/images/ok.png");
status.setImage(ok);
Log.debugInfo(host.getDisplayName() + " has ok indicator.", 96);
} else if (host.isStatusInfo()) {
Image info = new Image("/MMaaSCollector/images/info.png");
status.setImage(info);
Log.debugInfo(host.getDisplayName() + " has info indicator.", 96);
} else if (host.isStatusLow()) {
Image low = new Image("/MMaaSCollector/images/low.png");
status.setImage(low);
Log.debugInfo(host.getDisplayName() + " has low indicator.", 96);
} else if (host.isStatusWarning()) {
Image warning = new Image("/MMaaSCollector/images/warning.png");
status.setImage(warning);
Log.debugInfo(host.getDisplayName() + " has warning indicator.", 96);
} else if (host.isStatusCritical()) {
Image critical = new Image("/MMaaSCollector/images/critical.png");
status.setImage(critical);
Log.debugInfo(host.getDisplayName() + " critical indicator.", 96);
}
}
public AnchorPane getBg() {
return bg;
}
}

Found the reason for why it's not working. Had to update the project in eclipse.
Now when the images are in sync, it works as it should.

Related

How to read datamatrix embedded in document?

I try to read a datamatrix which is embedded into a document.
This is for an opensource project which helps to create and read 2DCODE standard.
I try with this code :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ZxingTest {
#Test
public void test() {
readQRCode("sfr-facture-1048469311-1.jpg");
readQRCode("sfr-facture-1048469311-1.png");
}
public static void readQRCode(String fileName) {
System.out.println("Try reading " + fileName);
File file = new File(fileName);
BufferedImage image = null;
try {
image = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image == null)
return;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
// hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(BarcodeFormat.DATA_MATRIX));
decode(image, hints);
}
public static void decode(BufferedImage tmpBfrImage, Hashtable<DecodeHintType, Object> hintsMap) {
if (tmpBfrImage == null)
throw new IllegalArgumentException("Could not decode image.");
LuminanceSource tmpSource = new BufferedImageLuminanceSource(tmpBfrImage);
BinaryBitmap tmpBitmap = new BinaryBitmap(new HybridBinarizer(tmpSource));
MultiFormatReader tmpBarcodeReader = new MultiFormatReader();
Result tmpResult;
String tmpFinalResult;
try {
if (hintsMap != null && !hintsMap.isEmpty())
tmpResult = tmpBarcodeReader.decode(tmpBitmap, hintsMap);
else
tmpResult = tmpBarcodeReader.decode(tmpBitmap);
// setting results.
tmpFinalResult = String.valueOf(tmpResult.getText());
System.out.println("tmpFinalResult=" + tmpFinalResult);
} catch (Exception tmpExcpt) {
tmpExcpt.printStackTrace();
}
}
}
and those images found on the net :
sfr-facture-1048469311-1.jpg
sfr-facture-1048469311-1.png
But I get this exception regardless of the image format: com.google.zxing.NotFoundException
May you advise me an lib which parses the page and detect the datamatrix coordinates for a pre-processing cropping?
Or a better a example of code which read the datamatrix?
I have a solution to my problem. I use opencv to locate any barcode then, after extraction according to the returned coordinates, I read them with zxing.
I based my solution the work of http://karthikj1.github.io/BarcodeLocalizer/
this the code i use :
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Reader;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import barcodelocalizer.Barcode;
import barcodelocalizer.CandidateResult;
import barcodelocalizer.ImageDisplay;
import barcodelocalizer.MatrixBarcode;
import barcodelocalizer.TryHarderFlags;
public class OpencvUtils {
private static boolean SHOW_INTERMEDIATE_STEPS = false;
private static boolean showImages = false;
public static String process_bufferedImage(BufferedImage bufferedImage) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(bufferedImage, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding buffered image " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
public static String process_image(String imgFile) {
Barcode barcode;
String barcodeText = null;
// instantiate a class of type MatrixBarcode with the image filename
try {
barcode = new MatrixBarcode(imgFile, SHOW_INTERMEDIATE_STEPS, TryHarderFlags.VERY_SMALL_MATRIX);
// locateBarcode() returns a List<CandidateResult> with all possible candidate
// barcode regions from
// within the image. These images then get passed to a decoder(we use ZXing here
// but could be any decoder)
List<CandidateResult> results = barcode.locateBarcode();
System.out.println("Decoding " + imgFile + " " + results.size() + " candidate codes found");
String barcodeName = barcode.getName();
barcodeText = decodeBarcode(results, barcodeName, "Localizer");
} catch (IOException ioe) {
System.out.println("IO Exception when finding barcode " + ioe.getMessage());
}
return barcodeText;
}
private static String decodeBarcode(List<CandidateResult> candidateCodes, String filename, String caption) {
// decodes barcode using ZXing and either print the barcode text or says no
// barcode found
BufferedImage decodedBarcode = null;
String title = null;
Result result = null;
String barcodeText = null;
for (CandidateResult cr : candidateCodes) {
BufferedImage candidate = cr.candidate;
decodedBarcode = null;
LuminanceSource source = new BufferedImageLuminanceSource(candidate);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
try {
result = reader.decode(bitmap, hints);
decodedBarcode = candidate;
title = filename + " " + caption + " - barcode text " + result.getText() + " " + cr.getROI_coords();
} catch (ReaderException re) {
}
if (decodedBarcode == null) {
title = filename + " - no barcode found - " + cr.getROI_coords();
if (showImages)
ImageDisplay.showImageFrame(candidate, title);
} else {
if (showImages)
ImageDisplay.showImageFrame(decodedBarcode, title);
System.out.println("Barcode text for " + filename + " is " + result.getText());
barcodeText = result.getText();
}
}
return barcodeText;
}
}
i added the method process_bufferedImage which process a java.awt.image.BufferedImage of a String filename.
And this sub-method to get the matrix of the BufferedImage bi.
protected Mat loadBufferedImage(BufferedImage bi) throws IOException {
// reads the BufferedImage passed in parameter
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bi, "png", byteArrayOutputStream);
byteArrayOutputStream.flush();
Mat mat = Imgcodecs.imdecode(new MatOfByte(byteArrayOutputStream.toByteArray()), Imgcodecs.IMREAD_UNCHANGED);
return mat;
}

Send Message to All in Client Server Chat Application in JavaFX

I was able to send message to clients connected to server but when
When Client Bunny sends message to Joel(receives message) and vice versa.
When second time Bunny sends message to Joel (doesn't receive message).
How do I iterate hashtable loop again to send and receive messages.
Server Class
import java.io.*; //Input and output to read and write data.
import java.net.*; //serversocket and initaddress
import java.util.Date; //to get date
import java.util.Enumeration; //enumeration
import java.util.Hashtable; // hashtable
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javafx.application.Application; //
import javafx.application.Platform; //platformrun later to append text
import javafx.event.EventHandler; // on click actions
import javafx.geometry.Insets; //insets
import javafx.geometry.Pos; //position
import javafx.scene.Scene; //scene
import javafx.scene.control.TextArea; //textarea
import javafx.scene.layout.StackPane; //stackpane
import javafx.stage.Stage; //stage
import javafx.stage.WindowEvent; //event close
public class Server extends Application { //class server
static InetAddress inetAddress; //inetaddress
private final Hashtable<Object, Object> outputStreams = new Hashtable(); //hashtable
TextArea textarea = new TextArea(); //textarea
static DataInputStream inputFromClient = null; //datainputstream
static DataOutputStream outputToClient = null; //dataoutputstream
static int clientNo = 0; //client connected
static ServerSocket serverSocket; //server socket
Hashtable<Object, Object> hmap = new Hashtable<>();
#Override // Override the start method in the Application class
public void start(Stage primaryStage) { //Stage to show everything
StackPane root = new StackPane(); //root add all the elements
root.setPadding(new Insets(10, 10, 10, 10)); //padding
root.setAlignment(textarea, Pos.CENTER); //positioning textarea to center
textarea.setMaxSize(400, 400); //maxsize of textarea
textarea.setWrapText(true); //wraptext for the textarea
new Thread(() -> { //thread to hold the server for the connections
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8001); //The server creates a server socket and, once a connection to a client is established, connects to the client with a client socket.
textarea.appendText("MultiThreadServer started at " + new Date() + '\n'); //server started with date.
while (true) { //accept multiple connections
// Listen for a new connection request
Socket socket = serverSocket.accept(); //listening for new connection from server port.
// inputFromClient = new DataInputStream(socket.getInputStream());
outputToClient = new DataOutputStream(socket.getOutputStream()); //outputstream to output to client
// Increment clientNo
clientNo++;
Platform.runLater(() -> {
// Display the client number
textarea.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');
// Find the client's host name, and IP address
InetAddress inetAddress = socket.getInetAddress();
textarea.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
textarea.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");
});
HandleAClient hd = new HandleAClient(socket);
hmap.put(socket, outputToClient);
hd.start();
// outputStreams.put(socket, outputToClient); //using hashtable to store client socket and outputstream
// Create and start a new thread for the connection
// new HandleAClient(this, socket);
}
} catch (IOException ex) {
textarea.appendText(ex + " \n");
}
}).start();
root.getChildren().addAll(textarea); // add UI elements to the root
Scene scene = new Scene(root, 450, 400); // creating scene of size 450 width and height 500
primaryStage.setTitle("Server"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { //close scene
#Override
public void handle(WindowEvent t) {
primaryStage.close();
Platform.exit();
System.exit(0);
}
});
}
// Used to get the output streams
Enumeration getOutputStreams() {
return outputStreams.elements();
}
// Used to send message to all clients
void sendToAll(String message) {
// Go through hashtable and send message to each output stream
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
DataOutputStream dout = (DataOutputStream) e.nextElement();
try {
// Write message
dout.writeUTF(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class HandleAClient extends Thread {
private Socket socket; // A connected socket
private String text = "";
/**
* Construct a thread
*/
public HandleAClient(Socket socket) throws IOException {
this.socket = socket;
}
/**
* Run a thread
*/
public void run() {
try {
// Create data input stream
inputFromClient = new DataInputStream(socket.getInputStream()); //receive input from client
textarea.appendText(new Date() + " Connection from " + socket + "\n");//showing connection from client
text = inputFromClient.readUTF(); // read string or message from client
// serversocket.sendToAll(text);
Set set = hmap.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("key " + entry.getKey() + " : " + entry.getValue());
DataOutputStream dout = (DataOutputStream) entry.getValue();
dout.writeUTF(text);
dout.flush();
}
Platform.runLater(() -> {
textarea.appendText(new Date() + " " + text + "\n");//append text
});
} catch (IOException e) {
textarea.appendText("Error " + e + " \n");
try {
this.socket.close(); //socket close
} catch (IOException ex) {
textarea.appendText("Error " + e + " \n");
}
e.printStackTrace();
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
Client Class
import java.io.*; //Input and output to read and write data.
import java.net.*; //serversocket and initaddress
import javafx.application.Application; //
import javafx.application.Platform; //platformrun later to append text
import javafx.event.EventHandler; // on click actions
import javafx.geometry.Insets; //insets
import javafx.geometry.Pos; //position
import javafx.scene.Scene; //scene
import javafx.scene.control.TextArea; //textarea
import javafx.scene.layout.StackPane; //stackpane
import javafx.stage.Stage; //stage
import javafx.stage.WindowEvent; //event close
import javafx.scene.control.Button; // button
import javafx.scene.control.Label; //label
import javafx.scene.control.TextField; //textfield
public class Client extends Application {
// IO streams
static DataOutputStream toServer = null; //datainputstream
static DataInputStream fromServer = null; //dataoutputstream
Label usernamelabel = new Label("Set your name :"); //set name label
Label textarealabel = new Label("Type your message in the textarea"); //text label
Label textlabel = new Label("Enter Text :"); //enter text
TextField textfield = new TextField(); //textfield
TextField namefield = new TextField(); //name field
Button send = new Button("Send"); //sendbutton
TextArea messagefield = new TextArea(); //textarea
static ServerSocket serverSocket; //serversocket
// Override the start method in the Application class
public void start(Stage primaryStage) throws IOException {
StackPane root = new StackPane(); //stacpane
root.setPadding(new Insets(10, 10, 10, 10));
StackPane.setAlignment(usernamelabel, Pos.TOP_LEFT);
namefield.setMaxWidth(200);
StackPane.setAlignment(namefield, Pos.TOP_CENTER);
StackPane.setMargin(textlabel, new Insets(30, 0, 0, 0));
StackPane.setMargin(textfield, new Insets(30, 0, 0, 0));
StackPane.setAlignment(textlabel, Pos.TOP_LEFT);
textfield.setMaxWidth(200);
StackPane.setAlignment(textfield, Pos.TOP_CENTER);
StackPane.setAlignment(send, Pos.BOTTOM_CENTER);
messagefield.setMaxSize(450, 250);
StackPane.setAlignment(textarealabel, Pos.BOTTOM_CENTER);
StackPane.setMargin(textarealabel, new Insets(0, 0, 35, 0));
StackPane.setAlignment(messagefield, Pos.CENTER);
root.getChildren().addAll(usernamelabel, namefield, send, messagefield, textarealabel, textlabel, textfield); //adding all the UI elements
// Create a scene and place it in the stage
Scene scene = new Scene(root, 500, 400);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
send.setOnAction(e -> { //send button action
try {
if (namefield.getText().trim().length() == 0) { //name field is empty
messagefield.appendText("Name field is empty. Please enter your name\n");
} else if (textfield.getText().trim().length() == 0) { //message field is empty
messagefield.appendText("Message field is empty. Please enter your message to send\n");
}
// Send the radius to the server
if (namefield.getText().trim().length() > 0 && textfield.getText().trim().length() > 0) {
toServer.writeUTF(namefield.getText().trim() + " : " + textfield.getText().trim());
toServer.flush();
}
} catch (IOException ex) {
messagefield.appendText(ex+" \n");
}
});
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8001); //socket with port number to connect server
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
new ReceiveMessage(socket); // send socket receieve class
// }
} catch (Exception ex) {
messagefield.setText(ex.toString() + '\n');
}
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() { //scene close
#Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
}
class ReceiveMessage implements Runnable { //class receive message
private final Socket socket;//socket
public ReceiveMessage(Socket socket) { // constructor
this.socket = socket; //socket intializes
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start();
}
public void run() {
try {
fromServer = new DataInputStream(socket.getInputStream()); //to read from server
while (true) { // to continously receieve messages
// Get area from the server
String textmessage = fromServer.readUTF(); //read message from server
toServer.flush(); // flush
Platform.runLater(() -> {
messagefield.appendText(textmessage + " \n"); //append to textarea
});
}
} catch (IOException e) {
messagefield.appendText("Error " + e);
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}
Server class executed and taking clients
Client one connected
Client Two connected
Thank you.
The mistake I made in the code was after client sends message to server and sends message to all the clients connected to the server after that server connection is paused or halted I don't know why. I have used enumeration method to send messages to all the clients connected to the server. This is how I solved the issue. Hope my answer will help someone who is trying to implement client-server (multiple clients) chat application using thread.
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Server extends Application {
static InetAddress inetAddress;
private final Hashtable<Object, Object> outputStreams = new Hashtable();
TextArea textarea = new TextArea();
static int clientNo = 0;
static ServerSocket serverSocket;
Hashtable<Object, Object> hmap = new Hashtable<>();
ArrayList<Object> clients = new ArrayList<Object>();
public void start(Stage primaryStage) {
StackPane root = new StackPane();
root.setPadding(new Insets(10, 10, 10, 10));
root.setAlignment(textarea, Pos.CENTER);
textarea.setMaxSize(400, 400);
textarea.setWrapText(true);
root.getChildren().addAll(textarea);
Scene scene = new Scene(root, 450, 400);
primaryStage.setTitle("Server");
primaryStage.setScene(scene);
primaryStage.show(); // Display the stage
primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
primaryStage.close();
Platform.exit();
System.exit(0);
}
});
new Thread(() -> {
listen();
}).start();
}
private void listen() {
try {
// Create a server socket
serverSocket = new ServerSocket(8001);
textarea.appendText("MultiThreadServer started at " + new Date() + '\n');
while (true) {
Socket socket = serverSocket.accept();
inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
clientNo++;
Platform.runLater(() -> {
textarea.appendText("Starting thread for client " + clientNo + " at " + new Date() + '\n');
InetAddress inetAddress = socket.getInetAddress();
textarea.appendText("Client " + clientNo + "'s host name is " + inetAddress.getHostName() + "\n");
textarea.appendText("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress() + "\n");
});
hmap.put(socket, outputToClient);
new HandleAClient(socket);
}
} catch (IOException ex) {
textarea.appendText(ex + " \n");
}
}
Enumeration getOutputStreams() {
return hmap.elements();
}
void sendToAll(String message) {
for (Enumeration e = getOutputStreams(); e.hasMoreElements();) {
DataOutputStream dout = (DataOutputStream) e.nextElement();
try {
dout.writeUTF(message);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
void All(String text) throws IOException {
Set set = hmap.entrySet();
Iterator it = set.iterator();
System.out.println("Text " + text);
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("key " + entry.getKey() + " : " + entry.getValue());
DataOutputStream dout = (DataOutputStream) entry.getValue();
dout.writeUTF(text);
dout.flush();
}
}
class HandleAClient extends Thread {
private final Socket socket; // A connected socket
private String text = "";
/**
* Construct a thread
*/
public HandleAClient(Socket socket) throws IOException {
this.socket = socket;
start();
}
/**
* Run a thread
*/
public void run() {
try {
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); //receive input from client
while (true) {
textarea.appendText(new Date() + " Connection from " + socket + "\n");
text = inputFromClient.readUTF();
serversocket.sendToAll(text);
All(text);
Platform.runLater(() -> {
textarea.appendText(new Date() + " " + text + "\n");
});
}
} catch (IOException e) {
textarea.appendText("Error " + e + " \n");
try {
this.socket.close();
} catch (IOException ex) {
textarea.appendText("Error " + e + " \n");
}
e.printStackTrace();
}
}
}
public static void main(String[] args) { //The keyword void simply tells the compiler that main( ) does not return a value.
launch(args);
}
}

Changing scenes with Alert Boxes

I am writing a quiz application which will feature multiple different classes including a separate class for each question. I want to use Alert Boxes to give the user the option to move onto the next question, so when I press proceed to move onto the first question, however it wont change to the next scene and I dont quite understand how the buttonType works?
Any help would be appreciated
package pkg1;
import java.io.*;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Alert.*;
import javafx.scene.layout.*;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
import javafx.stage.Window;
public class Register {
Stage stage;
public Register (Stage b){
stage = b;
}
public void start(Stage stage){
stage.setTitle("Registration");
GridPane gridPane = createRegisterPane();
addUIControls(gridPane);
Scene scene = new Scene(gridPane, 800, 500);
stage.setScene(scene);
stage.show();
}
private GridPane createRegisterPane() {
GridPane gridPane = new GridPane();
gridPane.setAlignment(Pos.CENTER);
gridPane.setPadding(new Insets(40, 40, 40, 40));
gridPane.setHgap(10);
gridPane.setVgap(10);
return gridPane;
}
private void addUIControls(GridPane gridPane) {
// Add Header
Label headerLabel = new Label("Registration");
headerLabel.setFont(Font.font("Arial", FontWeight.BOLD, 24));
gridPane.add(headerLabel, 0,0,2,1);
GridPane.setHalignment(headerLabel, HPos.CENTER);
GridPane.setMargin(headerLabel, new Insets(20, 0,20,0));
// FULL NAME
Label fnamelabel = new Label("Full Name : ");
gridPane.add(fnamelabel, 0,1);
// FULL NAME TEXT
TextField fnamefield = new TextField();
fnamefield.setPrefHeight(40);
gridPane.add(fnamefield, 1,1);
fnamefield.setPromptText(" - Enter your full name - ");
// EMAIL
Label emaillabel = new Label("Email: ");
gridPane.add(emaillabel, 0, 2);
// EMAIL TEXT
TextField emailfield = new TextField();
emailfield.setPrefHeight(40);
gridPane.add(emailfield, 1, 2);
emailfield.setPromptText(" - Enter your Email - ");
// USERNAME
Label usernamelabel = new Label("Username: ");
gridPane.add(usernamelabel, 0, 3);
// USERNAME TEXT
TextField usernamefield = new TextField();
usernamefield.setPrefHeight(40);
gridPane.add(usernamefield, 1, 3);
usernamefield.setPromptText(" - Enter your username - ");
// PASSWORD
Label passwordlabel = new Label("Password: ");
gridPane.add(passwordlabel, 0, 4);
// PASSWORD TEXT
PasswordField passwordfield = new PasswordField();
passwordfield.setPrefHeight(40);
gridPane.add(passwordfield, 1, 4);
passwordfield.setPromptText(" - Enter your password - ");
// SUBMIT BUTTON
Button submitButton = new Button("Submit");
submitButton.setPrefHeight(40);
submitButton.setDefaultButton(true);
submitButton.setPrefWidth(100);
gridPane.add(submitButton, 0, 5, 4, 2);
GridPane.setHalignment(submitButton, HPos.CENTER);
GridPane.setMargin(submitButton, new Insets(20, 0,20,0));
submitButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if(fnamefield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your full name.");
return;
}
if(usernamefield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your username");
return;
}
if(emailfield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your Email");
return;
}
if(passwordfield.getText().isEmpty()) {
ErrorAlert(Alert.AlertType.ERROR,
gridPane.getScene().getWindow(), "Error!", "Please enter your password");
return;
}
String fullname = fnamefield.getText();
String email = emailfield.getText();
String username = usernamefield.getText();
String password = passwordfield.getText();
String all = fullname + "," + email + "," + username + "," + password;
try{
FileWriter fw = new FileWriter ("F:/NEW/1/src/pkg1/Register.txt",true);
PrintWriter out = new PrintWriter (fw);
out.println(all);
out.close();
}
catch (Exception e){
System.out.println("Error " + e);
}
showAlert(Alert.AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Registration Succesful!", "Welcome " + fnamefield.getText());
}
});
}
//alert box which is called
private void ErrorAlert(Alert.AlertType alertType, Window owner, String
title, String message){
Alert AlertError = new Alert (AlertType.ERROR);
AlertError.setTitle(title);
AlertError.setHeaderText(null);
AlertError.setContentText(message);
AlertError.initOwner(owner);
AlertError.show();
}
private void showAlert(Alert.AlertType alertType, Window owner, String title, String message) {
Alert alert = new Alert(alertType.CONFIRMATION);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(message);
alert.initOwner(owner);
alert.show();
ButtonType b1 = new ButtonType ("Proceed");
ButtonType b2 = new ButtonType ("Cancel");
ButtonType b3 = new ButtonType ("Back to Main Menu");
alert.getButtonTypes().setAll(b1,b2,b3);
if (alert.getResult() == b1) {
new QuestionOne(stage).start(stage);
}else if (alert.getResult() == b2){
new Register(stage).start(stage);
}else {
new Register(stage).start(stage);
//new Main (stage).start(stage);
}
}
public static void main(String[] args) {
launch(args);
}
}
Set the button types before showing the alert and use Dialog.showAndWait to "wait" for the result:
...
alert.initOwner(owner);
ButtonType b1 = new ButtonType("Proceed");
ButtonType b2 = new ButtonType("Cancel");
ButtonType b3 = new ButtonType("Back to Main Menu");
alert.getButtonTypes().setAll(b1,b2,b3);
Optional<ButtonType> result = alert.showAndWait();
ButtonType resButton = result.orElse(null);
if (resButton == b1) {
...
} else if (resButton == b2) {
...
} else if (resButton == b3) {
...
}
Also as mentioned previously: A Application class without a constructor that takes no parameters cannot be launched. Your main method won't work.

Image from clipboard not correctly displayed in JavaFX 8 application

This program shall paste an image from clipboard into an ImageView (on Windows 10). Unfortunately the image is not correctly displayed.
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
Clipboard cb = Clipboard.getSystemClipboard();
if (cb.hasImage()) {
Image image = cb.getImage();
imageView.setImage(image);
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
}
Steps to reproduce:
Start cmd.exe
Press ALT-Print to copy the cmd window into the clipboard
Start program PasteImageFromClipboard
Press "Paste" button in PasteImageFromClipboard
This result is displayed on my computer:
It should be like this:
Is there more code required to draw the image correctly?
found this solution by the help of
https://community.oracle.com/thread/2238566
package com.wilutions.jiraddin;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import javax.imageio.ImageIO;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PasteImageFromClipboard extends Application {
ImageView imageView = new ImageView();
Button bnPaste = new Button("Paste");
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) throws Exception {
bnPaste.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
try {
java.awt.Image image = getImageFromClipboard();
if (image != null) {
javafx.scene.image.Image fimage = awtImageToFX(image);
imageView.setImage(fimage);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
});
VBox vbox = new VBox();
vbox.getChildren().addAll(bnPaste, imageView);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.setWidth(400);
stage.setHeight(400);
stage.show();
}
private java.awt.Image getImageFromClipboard() {
Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.imageFlavor)) {
try {
return (java.awt.Image) transferable.getTransferData(DataFlavor.imageFlavor);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
private static javafx.scene.image.Image awtImageToFX(java.awt.Image image) throws Exception {
if (!(image instanceof RenderedImage)) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
image = bufferedImage;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write((RenderedImage) image, "png", out);
out.flush();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
return new javafx.scene.image.Image(in);
}
}

Append text WebEngine - JavaFX

How can I append text to webengine? I tried this:
public TabMessage(String title) {
super(title);
view = new WebView();
engine = view.getEngine();
engine.loadContent("<body></body>");
view.setPrefHeight(240);
}
private void append(String msg){
Document doc = engine.getDocument();
Element el = doc.getElementById("body");
String s = el.getTextContent();
el.setTextContent(s+msg);
}
But document is null
First, Document returns null if webengine fails to load the content or you call engine.getDocument() before the content is fully finished its loading.
Second, doc.getElementById("body") searches for the DOM element with id "body". However the loaded content by you has no such id or any id at all.
To understand these better here is a complete runnable example, click on the button:
package demo;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class Demo extends Application {
private WebView view;
private WebEngine engine;
#Override
public void start(Stage primaryStage) {
view = new WebView();
engine = view.getEngine();
engine.loadContent("<body><div id='content'>Hello </div></body>");
view.setPrefHeight(240);
Button btn = new Button("Append the \"World!\"");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
append(" \"World!\"");
}
});
StackPane root = new StackPane();
root.getChildren().addAll(view, btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
private void append(String msg) {
Document doc = engine.getDocument();
Element el = doc.getElementById("content");
String s = el.getTextContent();
el.setTextContent(s + msg);
}
public static void main(String[] args) {
launch(args);
}
}
Note that I have put a div with id=content in th body so doc.getElementById("content") returns that div.
You can also use JavaScript to do the append.
final WebEngine appendEngine = view.getEngine();
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
appendEngine.executeScript(
"document.getElementById('content').appendChild(document.createTextNode('World!'));"
);
}
});
I sometimes find it simpler to use jQuery to manipulate the DOM rather than the Java Document or native JavaScript DOM interfaces.
final WebEngine appendEngine = view.getEngine();
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
executejQuery(appendEngine, "$('#content').append('World!');");
}
});
...
private static Object executejQuery(final WebEngine engine, String script) {
return engine.executeScript(
"(function(window, document, version, callback) { "
+ "var j, d;"
+ "var loaded = false;"
+ "if (!(j = window.jQuery) || version > j.fn.jquery || callback(j, loaded)) {"
+ " var script = document.createElement(\"script\");"
+ " script.type = \"text/javascript\";"
+ " script.src = \"http://code.jquery.com/jquery-1.7.2.min.js\";"
+ " script.onload = script.onreadystatechange = function() {"
+ " if (!loaded && (!(d = this.readyState) || d == \"loaded\" || d == \"complete\")) {"
+ " callback((j = window.jQuery).noConflict(1), loaded = true);"
+ " j(script).remove();"
+ " }"
+ " };"
+ " document.documentElement.childNodes[0].appendChild(script) "
+ "} "
+ "})(window, document, \"1.7.2\", function($, jquery_loaded) {" + script + "});"
);
}
Whether you use the Java Document API, as Uluk has, or JavaScript or JQuery APIs, all of the other points in Uluk's excellent answer still apply.
Though answer is very old and already accepted, I am putting my finding here.
The trick was to call engine.loadContent in init method of controller and then try to append content on some action like mentioned in example btn.setOnAction(). This way when you have action fired, the page was already loaded. If I put code for loading in setOnAction() itself, I get document as null.