Swing to Javafx conversion - java

I am not sure if this is a dumb question but I need help with this program I was creating. I wanted to make a login screen to this instant messenger app, which I already have created but I made it in javaFX. The problem is that since this instant messenger app is old, I created it with swing. Since there are no scenes in swing and there are in javafx, then when I hit login I would normally change the scene and that's it. That is why I am changing this program to javafx from swing but I am getting a couple of errors, if anyone is kind enough to tell me what I did wrong I would be grateful. Thanks and sorry for being so redundant, remember i'm just a beginner in 9th grade.
The exact error is in the line 56
The method ActionListener(new ActionListener(){}) is undefined for the type TextField
package messengerClient;
import java.io.*;
import java.net.*;
import java.awt.event.*;
import javax.swing.*;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.*;
import javafx.stage.*;
import javafx.stage.Stage;
import javax.swing.JFrame;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import java.awt.*;
import java.awt.event.ActionEvent;
public class ClientFX extends Application {
private TextField userText;
private TextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
Stage window;
Scene scene1,scene2;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
window = primaryStage;
window.setTitle("Client - Instant Messenger!");
ClientFX juan = new ClientFX("127.0.0.1");
juan.startRunning();
}
//CONSTRUCTOR
public ClientFX(String host){
serverIP = host;
ScrollPane sp = new ScrollPane();
sp.setContent(chatWindow);
userText = new TextField();
userText.setEditable(false);
userText.ActionListener(
new ActionListener(){
#Override
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
BorderPane layout1 = new BorderPane();
layout1.setTop(userText);
layout1.setCenter(chatWindow);
chatWindow = new TextArea();
scene2 = new Scene(layout1,500,300);
window.setScene(scene2);
window.show();
}
//CONNECT TO SERVER
public void startRunning(){
try{
connectToServer();
setupStreams();
whileChatting();
}catch(EOFException eofException){
showMessage("\n Client terminated connection");
}catch(IOException ioException){
ioException.printStackTrace();
}finally{
closeCrap();
}
}
//CONNECT TO SERVER
private void connectToServer() throws IOException{
showMessage("Attempting connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage("You have succesfully connected to: " + connection.getInetAddress().getHostName());
}
//SET UP STREAMS TO SEND AND RECIVE MESSAGES
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nYour streams are now ready to go! \n");
}
//WHILE CHATTING WITH THE SERVER
private void whileChatting() throws IOException{
ableToType(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException classnotfoundException){
showMessage("\nI do not know that object type");
}
}while(!message.equals("Server - END"));
}
//CLOSE THE STREAMS AND THE SOCKETS
private void closeCrap(){
showMessage("\nClosing streams and the sockets down...");
ableToType(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException ioException){
ioException.printStackTrace();
}
}
//SEND MESSAGES TO THE SERVER
private void sendMessage(String message){
try{
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException ioException){
chatWindow.appendText("\nThat data type cannot be sent, sorry!");
}
}
//UPDATE CHAT WINDOW
private void showMessage(final String m){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.appendText(m);
}
}
);
}
//GIVES USER PERMISION TO TYPE INTO THE TEXT BOX
private void ableToType(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}

The problem is you are mixing swing and javafx. You are importing both:
import java.awt.event.*;
import javax.swing.*;
import javafx.application.Application;
...
import javafx.scene.Scene;
import javafx.scene.control.Button;
For example in the ClientFX constructor you are trying to add a javax.swing.JTextField (a swing component) to a javafx.scene.BorderPane (a javafx component). The JTextField does not extend javafx.scene.Node, therefore it cannot be given to BorderPane.setTop(Node).
Basically for any swing component (often start with J, JTextField, JTextArea etc.) find the javafx equivalent (for example javafx.scene.control.TextField, javafx.scene.control.TextArea) and learn how to use them (they will have a different api).
In the end you should not have an import statement for java.awt or javax.swing.
Update
As already said you need to learn how to use the new fx apis. Not only the package names, classes and methods change, but also maybe programming concepts.
To port your JTextField behaviour you use a TextField and call the setOnAction method with an EventHandler implementation (very similar to the swing concept):
userText.setOnAction(new EventHandler<javafx.event.ActionEvent>()
{
#Override
public void handle(javafx.event.ActionEvent event)
{
//
}
});

Related

Get Real-time data from server socket and Display it in javafx

Hello I need to get Some data from a server socket i created and display it in a javafx application
fx application ie the display refresh the data every 250ms, and server sends data every 2 seconds
My code/plan have mainly 3 Parts
1. The server generates the data and sends it to the port every 2 sec
2. The Clint code gets the data from the server and updates its global variables
3. Every 250ms Schedule executioner reach out to the global varibles in clint and update the text fields
// Sadly this doesn't seems to work
i always starts server then clint then runs the application
so the Codes i written are as follows
Server Code
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket;
try (ServerSocket serverSocket = new ServerSocket(5555)) {
System.out.println("A");
socket = serverSocket.accept();
System.out.println("B");
if(socket.isConnected())System.out.println("Connected");
DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
while (socket.isConnected()) {
String T=DataStructureMaker();
dout.writeUTF(T);
System.out.println(T);
TimeUnit.SECONDS.sleep(2);
dout.flush();
}
}
socket.close();
}
public static String DataStructureMaker()
{
float RV_Phase=0,RI_Phase=0,RI_Grid=0,RV_Grid=0;String s="";
DecimalFormat df = new DecimalFormat("#.00");
s="";
RV_Phase=Float.parseFloat(df.format((Math.random()*10)));
s=s+Float.toString(RV_Phase)+"#";
RI_Phase=Float.parseFloat(df.format((Math.random()*10)));
s=s+Float.toString(RI_Phase)+"#";
RI_Grid=Float.parseFloat(df.format((Math.random()*10)));
s=s+Float.toString(RI_Grid)+"#";
RV_Grid=Float.parseFloat(df.format((Math.random()*10)));
s=s+Float.toString(RV_Grid)+"#";
return s;
}
}
The clint code is
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class Clint {
public static String RV_Grid;
public static String RI_Grid;
public static String RI_Phase;
public static String RV_Phase;
public static void main(String[] args) throws IOException, InterruptedException {
Socket s=new Socket("localhost",5555);
String S;
DataInputStream dIn=new DataInputStream(s.getInputStream());
while (s.isConnected()) {
S=dIn.readUTF();
setData(S);
}
}
public static void setData(String S) // Decryt data and set global values
{
char[] A=S.toCharArray();
int HC=0;
String R="";
if(A.length>2)
for(char x:A)
{
if(x=='#')
{
switch(HC)
{
case 0:
HC++;
RV_Phase=R;
R="";
break;
case 1:
HC++;
RI_Phase=R;
R="";
break;
case 2:
HC++;
RI_Grid=R;
R="";
break;
case 3:
HC++;
RV_Grid=R;
R="";
break;
}
}else{
R=R+x;
}
}
}
}
and Finally my fxml controller
import java.util.ResourceBundle;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
public class FXMLDocumentController implements Initializable {
#FXML
private TextField Text1;
#FXML
private TextField Text2;
#FXML
private TextField Text3;
#FXML
private TextField Text4;
static ScheduledExecutorService scheduledExecutorService;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(() -> {
setData();
}, 0, 250, TimeUnit.MILLISECONDS);
}
public void setData()
{
Text1.setText(Clint.RI_Grid);
Text2.setText(Clint.RI_Phase);
Text3.setText(Clint.RV_Grid);
Text4.setText(Clint.RV_Phase);
}
}
The Above code have All impotent data needed for my program Encryption, Decryption Send Receive and Display
The code following is aimed to serve two purposes:
The one is to demonstrate an mre for the question asked.
The other being a solution for dynamic update the GUI with data received by the client.
The code is not aimed to show how to correctly implement the client and server.
There are a few things to note about MRE:
1. It should not represent your specific application but a focused specific problem you
are trying to solve.
2. It should be M: remove all what is not essential. Bare minimum.
3. It should be R: reproduce the problem.
4. It should be complete.Independent on data-base, files or other unavailable resources.
5. It should be easy to use (copy-past).
To dynamically update the GUI with data received by the client, I used a shared model, that it is updated by the client.
Any change in the model ifs reflected in the GUI by using binding.
For simplicity and ease of use I have the controller, the model, the server and the client all in one file FXMLDocumentController.java:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ResourceBundle;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
public class FXMLDocumentController implements Initializable {
private static int PORT_NUMBER = 5555;
#FXML
private TextField text1;
#FXML
Button stopButton, startButton;
private ScheduledExecutorService scheduledExecutorService;
private Model model;
private Client client;
private Server server;
#Override
public void initialize(URL url, ResourceBundle rb) {
startButton.setDisable(false);
stopButton.setDisable(true);
scheduledExecutorService = Executors.newScheduledThreadPool(2);
model = new Model();
text1.textProperty().bind(model.getTextProperty());
}
private void startServer(){
try {
server = new Server(PORT_NUMBER);
server.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void startClient(){
try {
client = new Client(PORT_NUMBER, model);
client.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void start(){
scheduledExecutorService.submit(() -> startServer());
scheduledExecutorService.submit(() -> startClient());
startButton.setDisable(true);
stopButton.setDisable(false);
}
public void stop(){
client.stop();
server.stop();
scheduledExecutorService.shutdown();
stopButton.setDisable(true);
}
}
class Model {
private final ReadOnlyStringWrapper textProperty;
Model() {
textProperty = new ReadOnlyStringWrapper();
}
synchronized void setText(String s){
Platform.runLater(()->textProperty.set(s));
}
ReadOnlyStringWrapper getTextProperty(){
return textProperty;
}
}
class Server {
private final int portNumber;
private volatile boolean stop = false;
private static long REFRESH_TIME = 2;
Server(int portNumber) {
this.portNumber = portNumber;
}
void start() throws IOException {
Socket socket;
try (ServerSocket serverSocket = new ServerSocket(portNumber)) {
socket = serverSocket.accept();
DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
while (socket.isConnected() && ! stop) {
dout.writeUTF(randomText());
try {
TimeUnit.SECONDS.sleep(REFRESH_TIME);
} catch (InterruptedException ex) {
break;
}
dout.flush();
}
}
}
private String randomText()
{
DecimalFormat df = new DecimalFormat("#.00");
StringBuilder sb = new StringBuilder(df.format(Math.random()*10));
sb.append("#")
.append(df.format(Math.random()*10)) ;
return sb.toString();
}
void stop(){
stop = true;
}
}
class Client {
private final int portNumber;
private final Model model;
private volatile boolean stop = false;
Client(int portNumber, Model model) {
this.portNumber = portNumber;
this.model = model;
}
void start() throws IOException {
Socket socket = new Socket("localhost",portNumber);
DataInputStream dIn=new DataInputStream(socket.getInputStream());
while (socket.isConnected() && ! stop) {
model.setText(dIn.readUTF());
}
socket.close();
}
void stop(){
stop = true;
}
}
The controller is used by FXMLDocument.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.VBox?>
<VBox alignment="CENTER" prefHeight="113.0" prefWidth="232.0" spacing="10" xmlns="http://javafx.com/javafx/10.0.1"
xmlns:fx="http://javafx.com/fxml/1" fx:controller="fx_tests.FXMLDocumentController">
<TextField fx:id="text1" alignment="CENTER" promptText="Press START " />
<GridPane>
<Button fx:id="startButton" maxWidth="Infinity" onAction="#start" text="START" GridPane.columnIndex="0" />
<Button fx:id="stopButton" maxWidth="Infinity" onAction="#stop" text="STOP" GridPane.columnIndex="2" />
</GridPane>
</VBox>
Test it with :
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class FxmlTest extends Application {
#Override
public void start(Stage primaryStage) throws IOException {
Pane root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(null);
}
}

Connection timed out error in java client-server project

I'm learning some basic java networking stuff and I'm trying to make what I learned come to life, so when I run my server and client classes on the same computer it runs without errors, but when I take the client project to another computer and run the project after running the server it freezes and prints a connection timed out statement.
here is my server code
package sample;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
TextArea ta = new TextArea();
primaryStage.setTitle("server");
primaryStage.setScene(new Scene(new ScrollPane(ta), 450, 200));
primaryStage.show();
new Thread(()->{
try {
ServerSocket ss = new ServerSocket(8000);
Platform.runLater(() ->
ta.appendText("Server started at " + new Date() + '\n'));
Socket s = ss.accept();
DataInputStream inputFromClient = new DataInputStream(s.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(s.getOutputStream());
while (true) {
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
outputToClient.writeDouble(area);
Platform.runLater(() -> {
ta.appendText("Radius received from client: "
+ radius + '\n');
ta.appendText("Area is: " + area + '\n');
});
}
} catch (Exception e){
e.printStackTrace();
}
}).start();
}
public static void main(String[] args) {
launch(args);
}
}
and this is my client
package sample;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Main extends Application {
DataOutputStream toServer = null;
DataInputStream fromServer = null;
public void start(Stage primaryStage) {
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(5, 5, 5, 5));
pane.setStyle("-fx-border-color: green");
pane.setLeft(new Label("Enter a radius: "));
TextField tf = new TextField();
tf.setAlignment(Pos.BOTTOM_RIGHT);
pane.setCenter(tf);
BorderPane mainPane = new BorderPane();
TextArea ta = new TextArea();
mainPane.setCenter(new ScrollPane(ta));
mainPane.setTop(pane);
Scene scene = new Scene(mainPane, 450, 200);
primaryStage.setTitle("Client"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
tf.setOnAction(e -> {
try {
Socket socket = new Socket("server IP address", 8000);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) {
ta.appendText(ex.toString() + '\n');
}
try {
double radius = Double.parseDouble(tf.getText().trim());
toServer.writeDouble(radius);
toServer.flush();
double area = fromServer.readDouble();
ta.appendText("Radius is " + radius + "\n");
ta.appendText("Area received from the server is "
+ area + '\n');
} catch (IOException ex) {
System.err.println(ex);
}
});
}
}
problem solved
I just had to change the network settings on my server so that it will be discoverable on my network
Within the server class you create a server socket on the port 8000, which is fine for both internal and external connections. However your client class attempts to create a socket with no given IP Address
Socket socket = new Socket("server IP address", 8000);
By passing the string "Server ip address", you're essentially telling java to look for a local server, as you did not pass in a proper IP Address.
So when both classes are running on the same system only the port matters, but you need to identify the IP Address of the server for the client to know where to look for its connection if they're not on the same system.

FXML client-server GUI Application [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I used to work on Swing but now saw that it's pretty obsolete and JX8 is the future for Java applications so I started from YouTube tutorials on FXML GUI from ScreenBuilder. And integrated my RDT 3.0 TCP Server-Client code into FXML GUI.
But I have a lot of errors; I tried solving most of them but every time I get nullPointerException and I know it's because memory is not allocated. How can I get rid of them, and how to get my application running?
Here is the code:
ClientFXMLController.java:
package rdt_app;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.Initializable;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import static java.lang.Thread.sleep;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
/**
* FXML Controller class
*
* #author Dell
*/
public class ClientFXMLController implements Initializable {
ToggleGroup group = new ToggleGroup();
#FXML
RadioButton case1;
#FXML
RadioButton case2;
#FXML
RadioButton case3;
#FXML
RadioButton case4;
#FXML
RadioButton case5;
boolean buttonPressed=false;
String str=null;
#FXML
TextArea msg_rcv;
#FXML
Button send_button;
Socket s;
DataInputStream in;
// DataInputStream inn;
PrintStream ps;
String pre = "";
#FXML
private void handleButtonAction(ActionEvent event) {
// buttonPressed=true;
if(s!=null){
if(case1.isSelected())
str= "1";
else if(case2.isSelected())
str= "2";
else if(case3.isSelected())
str= "3";
else if(case4.isSelected())
str= "4";
else if(case5.isSelected())
str= "5";
}
else{
// Alert alert = new Alert(Alert.AlertType.ERROR); //AlertType.WARNING
// alert.setTitle("Error!");
// alert.setHeaderText("Message Cannot be send at this moment!");
// alert.setContentText("Please wait for response from Client or timeout and then proceed");
//
// alert.showAndWait();
}
}
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
try {
sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(ClientFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
try {
// TODO
case1.setToggleGroup(group);
case1.setSelected(true);
case2.setToggleGroup(group);
case3.setToggleGroup(group);
case4.setToggleGroup(group);
case5.setToggleGroup(group);
msg_rcv.appendText("Key:\n1:Operation with no Loss\n2:Lost Packet\n3:Lost ACK\n4:Premature Timeout\nNull:No Response\n");
s = new Socket("localHost",8100);
in = new DataInputStream(s.getInputStream());
// inn = new DataInputStream(System.in);
ps = new PrintStream(s.getOutputStream());
pre = "";
while (true)
{
str = in.readLine();
if (!str.equalsIgnoreCase("fin") && str!=null)
{
msg_rcv.appendText("Sender just sended a Message: "+str+"\n");
if (pre.equalsIgnoreCase("3") || pre.equalsIgnoreCase("null"))
{
msg_rcv.appendText("Duplicate Detected!\n");
}
msg_rcv.appendText("Enter a Response: \n");
if(str.equalsIgnoreCase("1") || str.equalsIgnoreCase("2") || str.equalsIgnoreCase("3") || str.equalsIgnoreCase("4") ||
str.equalsIgnoreCase("5")){
pre=str;
ps.println(str);
// buttonPressed=false;
}
// str = inn.readLine();
}
else if(str==null){
// do nothing carry on with loop
}
else
{
s.close();
break;
}
}
} catch (IOException ex) {
Logger.getLogger(ClientFXMLController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
FXMLDocumentController (Server):
package rdt_app;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import static java.lang.Thread.sleep;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
*
* #author Dell
*/
public class FXMLDocumentController implements Initializable {
#FXML
private Label info_label;
#FXML
private Label waitingLabel;
#FXML
private Button send_button;
#FXML
private TextField msg_send;
#FXML
private TextArea msg_rcv;
#FXML
private ProgressBar pbar;
String str =null;
ServerSocket ss;
int correct = 0;
Socket s;
DataInputStream in;
DataInputStream inn;
PrintStream ps;
#FXML
private AnchorPane rootPane;
#FXML
private void handleButtonAction(ActionEvent event) {
if(ss!=null && msg_send.getText()!=null){
if(correct==0)
str= msg_send.getText();
else{
Alert alert = new Alert(AlertType.ERROR); //AlertType.WARNING
alert.setTitle("Error!");
alert.setHeaderText("Message Cannot be send at this moment!");
alert.setContentText("Please wait for response from Client or timeout and then proceed");
alert.showAndWait();
}
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
try {
// TODO
// AnchorPane pane = FXMLLoader.load(getClass().getResource("clientFXML.fxml"));
// rootPane.getChildren().setAll(pane);
pbar.setProgress(0.0);
send_button.setVisible(false);
info_label.setVisible(false);
msg_send.setVisible(false);
msg_rcv.setVisible(false);
for(int i=0;i<100;i++){
pbar.setProgress(i/100.0);
sleep(20);
}
pbar.setProgress(0.0);
send_button.setVisible(true);
info_label.setVisible(true);
msg_send.setVisible(true);
msg_rcv.setVisible(true);
pbar.setVisible(false);
waitingLabel.setVisible(false);
ss=new ServerSocket(8100);
s=ss.accept();
int ack = 0;
in = new DataInputStream(System.in);
inn = new DataInputStream(s.getInputStream());
ps = new PrintStream(s.getOutputStream());
while (true)
{
// if (correct==0)
// {
// System.out.println("Enter a Message: ");
// str = in.readLine();
// }
if (str.equalsIgnoreCase("fin"))
{
ss.close();
break;
}
if(correct ==0 && str!=null){
ack = ack % 2;
ps.println(str);
str=null;
}
String str2 = inn.readLine();
int reply=0;
if (str2.equalsIgnoreCase("1") || str2.equalsIgnoreCase("2") || str2.equalsIgnoreCase("3") || str2.equalsIgnoreCase("4"))
{
reply = Integer.parseInt(str2);
}
if (!str2.equalsIgnoreCase("fin"))
{
if (reply==1) //operation with no loss
{
// System.out.println("Sender received a valid ACK for "+ack+" , send next message!");
msg_rcv.appendText("Sender received a valid ACK for "+ack+" , send next message!\n");
ack++;
correct=0;
}
if (reply==2) //Lost Packet
{
// System.out.println("Sender didn't recieve a ACK!");
msg_rcv.appendText("Sender didn't recieve a ACK!\n");
for (int i=0;i<5;i++)
{
msg_rcv.appendText("Waiting\n");
}
msg_rcv.appendText("Timeout! Sending Message Again\n");
correct++;
}
if (reply==3) //Lost ACK
{
msg_rcv.appendText("Sender received a corrupted ack (ACK is lost), keep waiting!\n");
for (int i=0;i<5;i++)
{
msg_rcv.appendText("Waiting\n");
}
msg_rcv.appendText("Timeout! Sending Message Again\n");
correct++;
}
if (reply==0 || reply==4) //Premature Timeout
{
if (reply==0)
{
msg_rcv.appendText("Sender didn't recieve a ACK because of Timeout!\n");
for (int i=0;i<5;i++)
{
msg_rcv.appendText("Waiting\n");
}
msg_rcv.appendText("Timeout! Sending Message Again\n");
correct++;
}
else if (reply==4)
{
msg_rcv.appendText("Sender received a valid ACK for "+ack+" , send next message!\n");
msg_rcv.appendText("Sender recieved a Duplicate ACK for "+ack+" , ACK ignored\n");
correct=0;
ack++;
}
}
}
else
{
ss.close();
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Now for running them i use this code:
Rdt_App.java:
package rdt_app;
import static java.lang.Thread.sleep;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
/**
*
* #author Dell
*/
public class Rdt_App extends Application {
#Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
The errors i get :
Apr 14, 2018 3:59:54 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.101
java.lang.NullPointerException
at rdt_app.FXMLDocumentController.initialize(FXMLDocumentController.java:114)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2548)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3214)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3175)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3148)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3124)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3104)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3097)
at rdt_app.Rdt_App.start(Rdt_App.java:24)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Did you set your controller in your FXML document? If you don't set controller class for an FXML, FXML components never gets initialized and hence you get a NullPointerException. Besides you don't need to implement Initializable interface. Change #Override to #FXML for intialize () function.

Playing sound in Java using java.applet class

I am building a simple program with one button. I want to play the "zvuk.wav" file after I click on the button. It's not working though and I cant solve why. When I click the button, nothing happens. The zvuk.wav file is in the src file with the classes.
Here is my first class which imports java.applet:
package Music;
import java.net.MalformedURLException;
import java.net.URL;
import java.applet.*;
public class Music {
private URL soubor;
public Music(String cesta){
try {
soubor = new URL("file:"+cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button:
package Music;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame{
public static final int WIDTH = 480;
public static final int HEIGHT = 600;
private String file;
public MainFrame(){
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
JButton bPlay = new JButton("PLAY");
jPanel.setLayout(null);
add(jPanel);
jPanel.add(bPlay);
bPlay.setBounds(200, 250, 100, 50);
bPlay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Music music = new Music("zvuk.wav");
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Please note that Applet.newAudioClip(url).play() does not throw an error if it fails for whatever reason (for example nothing will happen if the project cannot find the wav file).
Try this stand alone test app. Does it work?
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;
public class MainClass {
public static void main(String[] args) {
try {
URL url = new URL("file:zvuk.wav" );
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
System.in.read();
ac.stop();
} catch (Exception e) {
System.out.println(e);
}
}
}
If this small sample works, then it should be a small matter to modify it for your purposes.
However if it doesn't work then we almost certainly know that you project is unable to find the wav file.
Try add this to the code above:
//existing line
URL url = new URL("file:zvuk.wav" );
//new lines to debug wav file location
File myMusicFile = new File(url.getPath());
if(myMusicFile.exists() && !myMusicFile.isDirectory()) {
System.out.println("File exists and is not a directory");
}
If the file does not exist then that's your problem, and you need to point your URL to the correct location.
However if the file does exist and it still doesn't work then we have another possible issue outside of code.
It is possible that .play() is completing too quickly, see below for an example of how to keep it alive.
It is possible that your wav file is not a type that can be played, or it requires an unsupported codec. This is a far bigger topic and needs a new question, and a little bit of research on your part.
Here is the example to keep it alive from the sample code:
//load and start audio
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
//keep thread alive until a key is pressed
System.in.read();
ac.stop();
Sources:
http://www.java2s.com/Code/JavaAPI/java.applet/AppletnewAudioClipURLaudioFileURL.htm
http://docs.oracle.com/javase/7/docs/api/java/applet/AudioClip.html#play%28%29
I do this using NetBeans. This is the code.
Music.java file
package sound.play;
import java.applet.Applet;
import java.net.MalformedURLException;
import java.net.URL;
public class Music {
private URL soubor;
public Music(String cesta) {
try {
soubor = new URL("file:" + cesta);
} catch (MalformedURLException vyjimka) {
System.err.println(vyjimka);
}
Applet.newAudioClip(soubor).play();
}
}
MainFram which extends JFrame and has one Button
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainFrame extends javax.swing.JFrame {
public static final int WIDTH = 200;
public static final int HEIGHT = 200;
private String file;
public MainFrame() {
initComponents();
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setTitle("Přehrávač");
setResizable(false);
JPanel jPanel = new JPanel();
jPanel.setLayout(null);
add(jPanel);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Music music = new Music("zvuk.wav");
String filename = "zvuk.wav";
URL url = this.getClass().getResource(filename);
File myMusicFile = new File(url.getPath());
AudioClip ac = Applet.newAudioClip(url);
ac.play();
System.out.println("Press any key to exit.");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainFrame().setVisible(true);
}
});
}

send screenshots over network

I am trying to send continuous screenshots to another PC on same network.
I googled it also but i didn't find things relevant to me.
Below is my code of sender and receiver. Problem is only first image is being received and then struck.
If i turn on JFrame then not a single image is updating in JPanel. Please help me :-(
imagesender.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
class imagesender
{
imagesender()throws Exception
{
Socket soc=new Socket("127.0.0.1",5555);
OutputStream os=soc.getOutputStream();
while(true)
{
try
{
Dimension dim=Toolkit.getDefaultToolkit().getScreenSize();
Rectangle rec=new Rectangle(dim);
Robot bot=new Robot();
BufferedImage image=bot.createScreenCapture(rec);
ImageIO.write(image,"jpeg",os);
System.out.println("Image Sent");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String aerg[])throws Exception
{
new imagesender();
}
}
imagereciever.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
class imagereciever extends JPanel
{
static BufferedImage image;
imagereciever()throws Exception
{
ServerSocket ss=new ServerSocket(5555);
Socket soc=ss.accept();
JFrame frame=new JFrame();
frame.setSize(500,500);
frame.setContentPane(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setVisible(true);
InputStream is=soc.getInputStream();
while(true)
{
try
{
image=ImageIO.read(is);
//this.repaint();
ImageIO.write(image,"jpeg",new File("C:\\Users\\Arpit Jindal\\Desktop\\screenshot.jpeg"));
System.out.println("Image Recieved");
}
catch(Exception e)
{e.printStackTrace()}
}
}
public static void main(String aerg[])throws Exception
{
new imagereciever();
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(image,0,0,null);
}
}
imagereciever.java recieves one image and then gives this error infinite times and imagesender.java keeps on sending images:-
java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1592)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
at imagereciever.<init>(imagereciever.java:26)
at imagereciever.main(imagereciever.java:37)
Your GUI completely ignores Swing threading rules, so I'm not surprised that it might be getting stuck. Suggestions:
Use a SwingWorker to do long-running background tasks such as reading in images. In your case, perhaps a SwingWorker<Void, BufferedImage> is what you want so that you can pass the BufferedImage to the GUI via the publish/process method pair. The Concurrency in Swing tutorial will tell you the details on how to use this tool.
Don't draw with the paint method.
Instead draw in the paintComponent method of a JPanel that is displayed in JFrame. Be sure to call the super's paintComponent method within your override.
Stop to consider -- do you really need images transmitted in this way as you're passing in a lot of information, perhaps more than is needed? Better would be to pass a data model over the socket and then recreate a view with the data, if possible.
Never blatantly ignore exceptions as your code is doing. At least catch the exception's stacktrace.
The example #MadProgrammer gave to me solved my problem. This is my new Code:-
imagesender.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
class imagesender
{
imagesender()throws Exception
{
Socket soc=new Socket("127.0.0.1",5555);
OutputStream os=soc.getOutputStream();
while(true)
{
try
{
BufferedImage image=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(image,"png",baos);
baos.close();
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(baos.size()+"");
os.write(baos.toByteArray());
//System.out.println("Image Sent");
}
catch(Exception e)
{
System.exit(1);
}
}
}
public static void main(String aerg[])throws Exception
{
new imagesender();
}
}
imagereciever.java
import java.awt.*;
import java.awt.image.*;
import java.net.*;
import javax.imageio.*;
import java.io.*;
import javax.swing.*;
class imagereciever extends JPanel
{
static BufferedImage image;
static Socket soc;
static InputStream is;
imagereciever()throws Exception
{
ServerSocket ss=new ServerSocket(5555);
soc=ss.accept();
is=soc.getInputStream();
JFrame frame=new JFrame();
frame.setSize(500,500);
frame.setContentPane(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
while(true)
{
try
{
ObjectInputStream ois=new ObjectInputStream(is);
int size=Integer.parseInt(ois.readObject().toString());
ByteArrayOutputStream baos=new ByteArrayOutputStream(size);
int sizeread=0,bytesin=0;
byte[] buffer=new byte[1024];
while(sizeread<size)
{
bytesin=is.read(buffer);
sizeread+=bytesin;
baos.write(buffer,0,bytesin);
}
baos.close();
ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
image=ImageIO.read(bais);
this.repaint();
}
catch(Exception e)
{
System.exit(1);
}
}
}
public static void main(String aerg[])throws Exception
{
new imagereciever();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image,0,0,null);
}
}

Categories