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.
Related
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]);
}
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!
I am currently trying to making a custom rules plugin (for minecraft) and I am trying to see if the player has something activated which I stored in the config file. It is in the listener class (which calls the config from the main). Here is my code:
#EventHandler
public void onEvent(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (config.getInt("EditingLine." + player.getName().toLowerCase()) == 1) {
int line = 0;
try {
line = Integer.parseInt(e.getMessage());
} catch (Exception b) {
player.sendMessage(ChatColor.RED + "Invalid Number.");
config.set("EditingLine." + player.getName().toLowerCase(), 0);
}
if (!(line == 0)) {
config.set("EditingLine." + player.getName().toLowerCase(), 0);
config.set("EditingText." + player.getName().toLowerCase(), 1);
e.setCancelled(true);
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.GOLD + "Custom Rules" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enter the text you would now like on that line.");
}
}
}
The, config.getInt() function in the if then statement currently returns nothing. This may be happening because the config in the Listener Class is actually calling a custom made config, called 'playerdata.yml' and not the actual 'config.yml'. If there is any easier way to write this script, also let me know. I'm trying to make this as simple as I can.
The answer has been solved by merging my two configuration files together.
The requirement: show the coordinates of the mouseEvent that triggered the tooltip as its text. For a contextMenu, the location is stored in the contextMenuEvent, so I would listen to contextMenuRequested and update as needed.
Couldn't find anything similar for a tooltip, so played a bit (see example below):
at the time of showing/shown, I could query the tooltip location: for AnchorLocation.CONTENT_TOP_LEFT its x/y seems to be about the last mouse location, though slightly increased. Could be accidental, though, is unspecified (and as such unusable) and definitely off for other anchor types
the brute force method would be to install a mouse-moved handler and store the current mouse location into the tooltip's properties. Wouldn't like to, because that's duplicating functionality, as ToolTipBehaviour already keeps track of the triggering location, unfortunately top secretly, as usual
extending tooltip wouldn't help as well, due to the private scope of the behaviour
Any ideas?
public class DynamicTooltipMouseLocation extends Application {
protected Button createButton(AnchorLocation location) {
Tooltip t = new Tooltip("");
String text = location != null ? location.toString()
: t.getAnchorLocation().toString() + " (default)";
if (location != null) {
t.setAnchorLocation(location);
}
t.setOnShown(e -> {
// here we get a stable tooltip
t.textProperty().set("x/y: " + t.getX() + "/" + t.getY() + "\n" +
"ax/y: " + t.getAnchorX() + "/" + t.getAnchorY());
});
Button button = new Button(text);
button.setTooltip(t);
button.setOnContextMenuRequested(e -> {
LOG.info("context: " + text + "\n " +
"scene/screen/source " + e.getSceneX() + " / " + e.getScreenX() + " / " + e.getX());
});
button.setOnMouseMoved(e -> {
LOG.info("moved: " + text + "\n " +
"scene/screen/source " + e.getSceneX() + " / " + e.getScreenX() + " / " + e.getX());
});
return button;
}
#Override
public void start(Stage stage) throws Exception {
VBox pane = new VBox(createButton(AnchorLocation.CONTENT_TOP_LEFT));
Scene scene = new Scene(pane);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(DynamicTooltipMouseLocation.class.getName());
}
I'm not sure if I've understood your question right, but if you are looking for the screen coordinates of the mouse, right at the position when the tooltip is shown, I think you almost got them.
You have already looked at Tooltip class and its inner class TooltipBehavior.
For starters there are these hardcoded offsets:
private static int TOOLTIP_XOFFSET = 10;
private static int TOOLTIP_YOFFSET = 7;
Then, in the inner class a mouse moved handler is added to the node, tracking the mouse in screen coordinates, and showing the tooltip based on several timers:
t.show(owner, event.getScreenX()+TOOLTIP_XOFFSET,
event.getScreenY()+TOOLTIP_YOFFSET);
Given that it uses this show method:
public void show(Window ownerWindow, double anchorX, double anchorY)
The coordinates you are looking for are just these:
coordMouseX=t.getAnchorX()-TOOLTIP_XOFFSET;
coordMouseY=t.getAnchorY()-TOOLTIP_YOFFSET;
no matter how the tooltip anchor location is set.
I've checked this also in your answer to the question, and these values are the same as the Point2D screen you set to the tooltip.
Anyway, since this solution uses hardcoded fields from private API, I assume you won't like it, since those can change without notice...
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);}}