Jar does not run on command line - java

I did search through google and various forums, (this one as well).
I have created an application, a java benchmark, and wanted to create a runnable jar file, to use the program on other machines. Unfortunately, the jar is not working, everything is done perfect with the code to make jar file, the program runs on command line. I tried tricks found on this forum to fix my jar creation, but it didn't work as well.
Strangely enough, when i compile the JavaBenchmark.java file i do not get only one file (JavaBenchmark.class), but also JavaBenchmark$1.class :O (anyone knows why?)
So I ask you to check my code if THERE might be some problems, I must say its a GUI app.
import java.io.*;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaBenchmark implements ActionListener
{
private Frame mainWindow;
private Button exit;
private String dateAndTime;
private TextArea values;
private String stringMaxMemory;
private String stringFreeMemory;
private String stringTotalFreeMemory;
private String stringAllocatedMemory;
public JavaBenchmark(String s)
{
Date myDate = new Date();
dateAndTime = String.format("%tA, %<tF", myDate);
File[] roots = File.listRoots();
mainWindow = new Frame(s);
mainWindow.setSize(640,480);
mainWindow.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent we){System.exit(0);}});
String version = System.getProperty("java.version");
String jvmversion = System.getProperty("java.jvm.version");
String checkedJvmVersion;
if (jvmversion == null)
{
checkedJvmVersion = "Java Virtual Machine version: N/A";
}
else
{
checkedJvmVersion = "Java Virtual Machine version: " + jvmversion;
}
String jvmname = System.getProperty("java.vm.name");
String osname = System.getProperty("os.name");
String osarchitecture = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String processor = System.getenv("PROCESSOR_IDENTIFIER");
int processorCores = Runtime.getRuntime().availableProcessors();
Runtime runtime = Runtime.getRuntime();
double freeMemory = runtime.freeMemory();
double allocatedMemory = runtime.totalMemory();
double maxMemory = runtime.maxMemory();
double totalFreeMemory = (freeMemory + (maxMemory - allocatedMemory));
stringFreeMemory = String.format("%5.2f", (freeMemory)/1024/1024);
stringAllocatedMemory = String.format("%5.2f", (allocatedMemory)/1024/1024);
stringMaxMemory = String.format("%5.2f", (maxMemory)/1024/1024);
stringTotalFreeMemory = String.format("%5.2f", (totalFreeMemory)/1024/1024);
exit = new Button("Exit"); exit.addActionListener(this);
values = new TextArea(30, 120);
Panel exitButton = new Panel();
exitButton.add(exit);
mainWindow.add(values, "North");
mainWindow.add(exitButton);
values.append("Your Java benchmark, as on: " + dateAndTime + "\n\n");
values.append("Java version: " + version + "\n");
values.append("Java Virtual machine version: " + checkedJvmVersion + "\n");
values.append("Java Virtual Machine name: " + jvmname + "\n");
values.append("\n");
values.append("Operating System: " + osname + "\n" + osarchitecture + " os version: " + osversion + "\n");
values.append("\n");
values.append("Processor: " + processor + " (number of cores: " + processorCores + ")\n");
values.append("\n");
values.append("Memory info: \n");
values.append("Maximum RAM memory for JVM: " + stringMaxMemory + " Mb\n");
values.append("Allocated RAM memory for JVM: " + stringAllocatedMemory + " Mb\n");
values.append("Free RAM memory for JVM: " + stringFreeMemory + " Mb\n");
values.append("Total free RAM memory for JVM: " + stringTotalFreeMemory + " Mb\n\n\n");
values.append("HardDrive, and VirtualDrive details:\n");
for (File root : roots) {
if (root.getTotalSpace() == 0)
{
continue;
}
else
{
values.append("Disk: " + root.getAbsolutePath() + " space allocation:\n");
values.append("Total space :");
values.append(String.format("%5.2f", Double.valueOf(root.getTotalSpace())/1024/1024/1024));
values.append(" Gb\n");
values.append("Free space : ");
values.append(String.format("%5.2f", Double.valueOf(root.getFreeSpace())/1024/1024/1024));
values.append(" Gb\n");
values.append("Occupied disk space : ");
values.append(String.format("%5.2f", Double.valueOf(root.getTotalSpace() - root.getFreeSpace())/1024/1024/1024));
values.append(" Gb\n\n");
}
}
mainWindow.pack(); //Creating the window
mainWindow.setLocationRelativeTo(null); //true: position at (0,0) false: position at center
mainWindow.setResizable(false); //Intuitively known commands
mainWindow.setVisible(true); //Intuitively known commands
}
public static void main(String[] args)
{
new JavaBenchmark("Display");
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==exit)
{
System.exit(0);
}
}
}

The JavaBenchmark$1.class is an anonymous class you create for WindowAdapter when you add a window listener.
As far as the Jar not working, you'd have to describe what you're doing to create the Jar to identify where you're going wrong. Chances are you're simply issuing the wrong command.

JavaBenchmark$1.class is the anonymous class defined as follows:
new WindowAdapter(){public void windowClosing(WindowEvent we){System.exit(0);}}

Related

.jar program not operating the same as compiled program

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

Why do I get, and how do I solve this "String to object of type <objecttype>" error

I am (being an absolute beginner), trying to create a simple tool, that creates some objects and links them.
The objects are:
Customers
Licenses (2 types, extends class)
The idea is to use (one of) the customer company name when creating a license, so the license is linked to a customer.
I use ArrayLists to store the data.
I tried to use the getter for Customer cCompany, but when I try to actually create a new license object, I get errors about incompatible types (String to object of type customer)
How can I fix that error?
Any help is highly appreciated, but please explain well, me being an absolute beginner. I probably overcomplicate stuff....
Some code extracts:
From Main:
public class Main {
public static void main(String[] args) {
//Create customers
List <Customer> customers = new ArrayList <> (10);
customers.add(new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
....
//Create Elvis licenses (based on superclass License)
List <ElvisLicense> ellicenses = new ArrayList <> (10);
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
Class: Customer:
class Customer {
String cCompany;
private String cName;
private int cPhone;
private String cEmail;
public Customer( String cCompany, String cName,int cPhone, String cEmail)
{
this.cCompany = cCompany;
this.cName = cName;
this.cPhone = cPhone;
this.cEmail = cEmail;
}
//This getter should be used to link the license to the customer (Done in License.java)
public String getcCompany() {
return cCompany;
}
Class License (Superclass)
class License {
// Used no modifier to set access for Class/Package and Subclass inside the package
Customer licenseCompany;
String lVendor;
int lContractNumber;
String lCertificateNumber;
String lProductName;
String lLicenseKey;
int lNumberOfSeats;
public License(Customer cCompany, String lVendor, int lContractNumber, String lCertificateNumber,
String lProductName, String lLicenseKey, int lNumberOfSeats)
{
licenseCompany = cCompany;
this.lVendor = lVendor;
this.lVendor = lVendor;
this.lContractNumber = lContractNumber;
this.lCertificateNumber = lCertificateNumber;
this.lProductName = lProductName;
this.lLicenseKey = lLicenseKey;
this.lNumberOfSeats = lNumberOfSeats;
}
public Customer getLicenseCompany() {
return licenseCompany;
}
public void setLicenseCompany(Customer licenseCompany) {
this.licenseCompany = licenseCompany;
}
//preparations to allow for example printing the content of an arraylist element
#Override
public String toString(){
return "Customer name " + getLicenseCompany() + "\n" + "Vendor name " + getlVendor() + "\n" + "Contract number: " + getlContractNumber() + "\n"
+ "Certificate number: " + getlCertificateNumber() + "\n" +
"Product name " + getlProductName() + "\n" + "Licence key: " + getlLicenseKey() + "\n"
+ "Number of seats: " + getlNumberOfSeats();
}
}
And the extended class:
public class ElvisLicense extends License{
private boolean elIsBundle;
private boolean elIsSubscription;
public ElvisLicense(
Customer licenseCompany,
String lVendor,
int lContractNumber,
String lCertificateNumber,
String lProductName,
String lLicenseKey,
int lNumberOfSeats,
boolean elIsBundle,
boolean elIsSubscription
)
{
super(
licenseCompany,
lVendor,
lContractNumber,
lCertificateNumber,
lProductName,
lLicenseKey,
lNumberOfSeats);
this.elIsBundle = elIsBundle;
this.elIsSubscription = elIsSubscription;
}
.....
#Override
public String toString(){
return "Customer name " + licenseCompany + "\n"
+ "Vendor name " + lVendor + "\n"
+ "Contract number: " + lContractNumber + "\n"
+ "Certificate number: " + lCertificateNumber + "\n"
+ "Product name " + lProductName + "\n"
+ "Licence key: " + lLicenseKey + "\n"
+ "Number of seats: " + lNumberOfSeats + "\n"
+ "Number of seats: " + elIsBundle + "\n"
+ "Number of seats: " + elIsSubscription;
}
}
I expect that the Customername is used when creating a new license.
Below line is wrong.
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
As license need customer object an parameter. Instead, you should create customer object first.
ellicenses.add(new ElvisLicense(new Customer("TestCompany","VendorA",1234,"1234-A"),"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
for reusing that customer list to avoid create company.
for(Customer customer : customers){
// here you need some way to offer other parameters except customer parameter.
License license = new new ElvisLicense(customer,"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true);
ellicenses.add(license);
}
What you need to do is to use one of the Customer objects you have already created when creating the ElvisLicense object. To more easily find that customer by name I suggest you store them in a map instead of a list with the name as a key.
Map<String, Customer> customerMap = new HashMap<>();
Customer customer = new Customer("TestCompany","John Doe",1234567890,"John#testcompany.com"));
customerMap.put(customer.getcCompany(), customer);
so when creating the license you look up the customer
List <ElvisLicense> ellicenses = new ArrayList <> (10);
Customer customer = customerMap.get("TestCompany");
if (customer != null) {
ElvisLicense license = new ElvisLicense(customer,"VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
ellicenses.add(license);
} else {
//If the customer isn't found you need some kind of error handling, better than below :)
System.out.println("Can't create a license, no customer found");
}

How do I fix java.lang.NumberFormatException? [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 3 years ago.
I'm trying to make this "Overall Grade Calculator" using javax.swing.*; that I recently learned. However, I can't find what is wrong with my code. My IDE, which is Ecliple, isn't detecting any error on my codes but it won't run when I try to run my codes. Where did I mess up?
BTW: This is by far my latest knowledge of Java Coding because I am self taught so I might not know any codes that are more advanced that these.
import javax.swing.*;
public class gradeCalcMk3 {
public static double average(double a, double b, double c, double d) {
double ave = a*0.3 + b*0.5 + c*0.1 + d*0.1;
return ave;
}
public static void main(String[] args) {
double grade[] = {0,0,0,0,0};
JTextField name = new JTextField(10);
JTextField q = new JTextField(3);
JTextField ex = new JTextField(3);
JTextField cs = new JTextField(3);
JTextField ilm = new JTextField(3);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("Name:"));
myPanel.add(name);
myPanel.add(new JLabel("Q:"));
myPanel.add(q);
myPanel.add(new JLabel("Ex:"));
myPanel.add(ex);
myPanel.add(new JLabel("CS:"));
myPanel.add(cs);
myPanel.add(new JLabel("ILM:"));
myPanel.add(ilm);
grade[0] = Double.parseDouble(q.getText());
grade[1] = Double.parseDouble(ex.getText());
grade[2] = Double.parseDouble(cs.getText());
grade[3] = Double.parseDouble(ilm.getText());
grade[4] = average(grade[0], grade[1], grade[2], grade[3]);
double confirm = JOptionPane.showConfirmDialog
(null, myPanel, "Enter Values", JOptionPane.OK_CANCEL_OPTION);
if(confirm == JOptionPane.OK_OPTION) {
JOptionPane.showMessageDialog(null, "Name: " + name.getText()
+ "\n\nQuiz: " + grade[0]
+ "\n\nExam: " + grade[1]
+ "\n\nCS: " + grade[2]
+ "\n\nILM: " + grade[3]
+ "Average: " + grade[4]);
}
}
}
Here's the output when I try to run it
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at gradeCalcMk3.main(gradeCalcMk3.java:32)
You will need a bit more to make this work.
Basically all of the code that extracts the values from the text field needs to be placed into a method that is triggered when you click on a button or menu (or something else to activate it). i.e. you need at least two methods, a "setup form" method and a "process the inputs" method.
As posted, your JTextFields contain no text (the constructor you are using does not set the text - it sets the "number of columns").
Once all of the text fields have been created and added to the form, the very next step is to extract the empty strings from them and attempt to parse them as doubles. This will generate the exception you encountered.
Because the code is all contained in a single method, there is zero chance to allow you to enter any values into the fields before they are read and processed.
At the very least, comment out (for now) the code that attempts to extract values, parse them and compute the average. This extract, parse and calculate code can later be moved into the event handler attached to a button or menu that I mentioned above.
I hope this helps.
You're simply using the wrong constructor when creating instances of JTextField
JTextField(int columns)
Constructs a new empty TextField with the specified number of columns.
Instead of providing an int, use a string, for example new JTextField("10")
JTextField(String text)
Constructs a new TextField initialized with the specified text.
Nvm, I found where I messed up and fixed it by doing this:
if(confirm == JOptionPane.OK_OPTION) {
grade[0] = Double.parseDouble(q.getText());
grade[1] = Double.parseDouble(ex.getText());
grade[2] = Double.parseDouble(cs.getText());
grade[3] = Double.parseDouble(ilm.getText());
grade[4] = average(grade[0], grade[1], grade[2], grade[3]);
JOptionPane.showMessageDialog(null, "Name: " + name.getText()
+ "\n\nQuiz: " + grade[0]
+ "\n\nExam: " + grade[1]
+ "\n\nCS: " + grade[2]
+ "\n\nILM: " + grade[3]
+ "Average: " + grade[4]);
}

cannot write in TextArea JavaFX

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

Using ACE with WT

UPDATE 3
Final working code below. YOU NEED THE ace.js FROM THE src FOLDER! It will not work from the libs, you need the pre-packaged version from their site.
WText *editor = new WText(root());
editor->setText("function(){\n hello.abc();\n}\n");
editor->setInline(false);
The above code can set the contents of the ACE window.
MyClass::MyClass(const WEnvironment& env)
: WApplication(env)
{
wApp->require("ace-builds/src/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
editor->resize(500, 500);
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + ".editor = ace.edit(" + editor_ref + ");" +
editor_ref + ".editor.setTheme(\"ace/theme/monokai\");" +
editor_ref + ".editor.getSession().setMode(\"ace/mode/javascript\");";
editor->doJavaScript(command);
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
command = "function(object, event) {" +
jsignal->createCall(editor_ref + ".editor.getValue()") +
";}";
b->clicked().connect(command);
}
void MyClass::textChanged(std::string incoming)
{
}
UPDATE 2
Here is what my project looks like atm, still getting a white screen with a red "Loading..." message from WT in the top right hand corner. More notes below.
MyClass::MyClass(const WEnvironment& env)
: WApplication(env)
{
wApp->require("lib/ace/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
editor->resize(500, 500);
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + ".editor = ace.edit(" + editor_ref + ");" +
editor_ref + ".editor.setTheme(\"ace/theme/monokai\");" +
editor_ref + ".editor.getSession().setMode(\"ace/mode/javascript\");";
editor->doJavaScript(command);
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
command = "function(object, event) {" +
jsignal->createCall(editor_ref + ".editor.getValue()") +
";}";
b->clicked().connect(command);
}
void MyClass::textChanged(std::string incoming)
{
}
"command" variable is equal to the following when it is used for editor->doJavaScript(command)
"Wt3_3_0.$('oy4ycjy').editor = ace.edit(Wt3_3_0.$('oy4ycjy'));Wt3_3_0.$('oy4ycjy').editor.setTheme('ace/theme/monokai');Wt3_3_0.$('oy4ycjy').editor.getSession().setMode('ace/mode/javascript');"
"command" variable is equal to the following when it is used for b->clicked().connect(command);
"function(object, event) {Wt.emit('oy4ycjy','textChanged',Wt3_3_0.$('oy4ycjy').editor.getValue());;}"
UPDATE 1
Added the suggested code to my constructor, however the page does not change from a solid white screen. I am doing nothing else in this WT project, only this code is running.
wApp->require("lib/ace/ace.js");
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(root());
std::string editor_ref = editor->jsRef(); // is a text string that will be the element when executed in JS
editor->doJavaScript(
editor_ref + ".editor = ace.edit('" + editor_ref + "');" +
editor_ref + ".editor.setTheme('ace/theme/monokai');" +
editor_ref + ".editor.getSession().setMode('ace/mode/javascript');"
);
The value of editor_ref is "Wt3_3_0.$('oumvrgm')" minus the quotes.
Also tried adding the code below, and the page is still blanked out.
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, &MyClass::textChanged);
WPushButton *b = new WPushButton("Save", root());
b->clicked().connect("function(object, event) {" +
jsignal->createCall(editor->jsRef() + ".editor.getValue()") +
";}");
I have also found that commenting out
editor_ref + ".editor = ace.edit('" + editor_ref + "');" +
makes the button show up, but there is a red "Loading..." note at the top right of the screen so WT is waiting on something.
I have textChanged as a do nothing function at the moment.
ORIGINAL POST
So, my problem is this. How can I get ACE http://ace.ajax.org/#nav=about in WT http://www.webtoolkit.eu/wt. More specifically, ACE in a WT Wt::WTextArea or Wt::WTabWidget, the text area would be preferred. I have been trying to do this for a few days now and have not had much success.
I've been able to embed ACE in an HTML page no problem, as their site says "just copy and paste it into your page" and it really is that simple. However, I need to load it locally through WT and into a container. I downloaded their repos from GIT to my machine and have tried using
require("lib/ace/ace.js");
and
doJavaScript(...);
with various commands to no success... I am not nearly as strong in Java and HTML as C++ so I will ask for as much detail as possible if this involves a lot of Java/HTML. Thanks in advance mates!
Maybe this puts you in the right direction:
wApp->require("lib/ace/ace.js")
// A WContainerWidget is rendered as a div
WContainerWidget *editor = new WContainerWidget(parent);
// editor->jsRef() is a text string that will be the element when executed in JS
editor->doJavaScript(
editor->jsRef() + ".editor = ace.edit(" + editor->jsRef() + ");" +
editor->jsRef() + ".editor.setTheme('ace/theme/monokai');" +
editor->jsRef() + ".editor.getSession().setMode('ace/mode/javascript');"
);
That should decorate the editor. Wt does not automatically send the modifications to a div to the server, so you do this manually through a JSignal (emits a signal from JS to C++):
JSignal <std::string> *jsignal = new JSignal<std::string>(editor, "textChanged");
jsignal->connect(this, MyClass::textChanged);
WPushButton *b = new WPushButton("Save", parent);
b->clicked().connect("function(object, event) {" +
jsignal->createCall(editor->jsRef() + ".editor.getValue()") +
";}");
(code above is not tested so you may need to adjust a bit)
I have integrated CodeMirror in an earlier JWt (java) project like this:
import eu.webtoolkit.jwt.WApplication;
import eu.webtoolkit.jwt.WContainerWidget;
import eu.webtoolkit.jwt.WTextArea;
public class CodeMirrorTextArea extends WContainerWidget {
private WTextArea textArea;
public CodeMirrorTextArea(WContainerWidget parent) {
super(parent);
textArea = new WTextArea(this);
WApplication app = WApplication.getInstance();
app.require(app.resolveRelativeUrl("codemirror-2.32/lib/codemirror.js"));
app.require(app.resolveRelativeUrl("codemirror-2.32/mode/groovy/groovy.js"));
//TODO:
//We save the editor state to the text area on each key stroke,
//it appears to be not a performance issue,
//however it might very well become one when editing larger fragments of code.
//A better solution would be to save this state to the text area only when
//the form is submitted, currently this is not yet possible in Wt???.
String js =
"var e = " + textArea.getJsRef() + ";" +
"var cm = CodeMirror.fromTextArea(e, {" +
" onKeyEvent : function (editor, event) {" +
" editor.save();" +
" }," +
" lineNumbers: true" +
" });" +
"var self = " + getJsRef() + ";" +
"self.cm = cm;";
this.doJavaScript(js);
}
public CodeMirrorTextArea() {
this(null);
}
public void setText(String text) {
textArea.setText(text);
}
public String getText() {
return textArea.getText();
}
public void setMarker(int line, String htmlMarker) {
String js =
"var self = " + getJsRef() + ";" +
"self.cm.setMarker(" + line + ", " + jsStringLiteral(htmlMarker +
"%N%") + ");";
this.doJavaScript(js);
}
public void clearMarker(int line) {
String js =
"var self = " + getJsRef() + ";" +
"self.cm.clearMarker(" + line + ");";
this.doJavaScript(js);
}
}

Categories