Running a JAVA Program with a Button (GUI) - java

I've been stumped on this all day, despite hours of research. Below is a basic idea of my program. It extracts data from links and puts it into a spreadsheet, and it can run for hours at a time. My intent is to connect this to a GUI with a progress bar. I'm trying to have an "upload" button, then a "Run" button.
For the "Run" button, I cannot figure out how to connect the button to running an instance of the below program.
I have attempted putting
App obj= new App();
obj.main(null);
under actionPerformed with no luck. I receive the following error:
Error:(31, 25) java: unreported exception java.lang.Exception;
must be caught or declared to be thrown
I understand now that we can't exactly call main functions. But in that case, how can I make my program work with a GUI? The main reason behind this is to be able to create a webapp for it in the future so that I can access it anywhere.
public class App {
private static final int[] URL_COLUMNS = { 0, 4, 9 }; // Columns A, E, J
public static void main(final String[] args) throws Exception {
Workbook originalWorkbook = Workbook.getWorkbook(new File("C:/Users/Shadow/Desktop/original.xls"));
WritableWorkbook workbook = Workbook.createWorkbook(new File("C:/Users/Shadow/Desktop/updated.xls"), originalWorkbook);
originalWorkbook.close();
WritableSheet sheet = workbook.getSheet(0);
Cell cell;
for (int i = 0; i < URL_COLUMNS.length; i++) {
int currentRow = 1;
while (!(cell = sheet.getCell(URL_COLUMNS[i], currentRow)).getType().equals(CellType.EMPTY)) {
String url = cell.getContents();
System.out.println("Checking URL: " + url);
if (url.contains("scrapingsite1.com")) {
String Price = ScrapingSite1(url);
System.out.println("Scraping Site1's Price: " + Price);
// save price into the next column
Label cellWithPrice = new Label(URL_COLUMNS[i] + 1, currentRow, Price);
sheet.addCell(cellWithPrice);
}
currentRow++;
}
}
workbook.write();
workbook.close();
}
private static String ScrapingSite1 (String url) throws IOException {
Document doc = null;
for (int i=1; i <= 6; i++) {
try {
doc = Jsoup.connect(url).userAgent("Mozilla/5.0").timeout(6000).validateTLSCertificates(false).get();
break;
} catch (IOException e) {
System.out.println("Jsoup issue occurred " + i + " time(s).");
}
}
if (doc == null){
return null;
}
else{
return doc.select("p.price").text();
}
}
}

At a crude guess I would say that the compiler is prompting you to change:
App obj= new App();
obj.main(null);
To one of several possibilities, this one based on 'must be caught' (try / catch):
try {
App obj= new App();
obj.main(null);
} catch(Exception e) {
e.printStackTrace(); // good fall back if logging not implemented
}
Edit: For more information, see the Exceptions lesson of the Java Tutorial.

Related

How to I access the data of a WMI Query (via JNA) SAFEARRAY result

I use jna to run WMI queries.
The following code queries WMI SELECT Caption,Capabilities from Win32_DiskDrive. The Type of Win32_DiskDrive.Capabilities is uint16[] and result.getValue returns a SAFEARRAY Instance.
System.out.println("Var Type(3 expected): " + value.getVarType().intValue());
returns randomly 0 or 3 if I start the process several times.
System.out.println("Size (>0 expected): " + (value.getUBound(0) - value.getLBound(0)));
is correct, but
Object el = value.getElement(0);
fails.
value.accessData();
returns null which is unexpected as well, so I cannot use OaIdlUtil#toPrimitiveArray (Nullpointer)
Unfortunately, the code does not work, and I have no idea what might be wrong. Any Ideas?
enum Win32_DiskDrive_Values {
Caption,
Capabilities
}
public static void main(String[] args) throws IOException, InterruptedException {
try {
WmiQuery<Win32_DiskDrive_Values> serialNumberQuery = new WmiQuery<Win32_DiskDrive_Values>("Win32_DiskDrive", Win32_DiskDrive_Values.class);
Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED);
WmiResult<Win32_DiskDrive_Values> result = serialNumberQuery.execute();
for (int i = 0; i < result.getResultCount(); i++) {
System.out.println(result.getValue(Win32_DiskDrive_Values.Caption, i));
SAFEARRAY value = (SAFEARRAY) result.getValue(Win32_DiskDrive_Values.Capabilities, i);
// According to https://learn.microsoft.com/en-us/windows/desktop/cimwin32prov/win32-diskdrive, the type of Capabilities
// should be uint16[] which should be Variant.VT_I2 (2-byte integer)
// however, it is not constant. sometimes it is 0, sometimes Variant.VT_I2 (3);
System.out.println("Var Type(3 expected): " + value.getVarType().intValue());
System.out.println("Size (>0 expected): " + (value.getUBound(0) - value.getLBound(0)));
Object el = value.getElement(0);
System.out.println("Element 0 (!=null expected): " + el);
Pointer pointer = value.accessData();
System.out.println("pointer (!=null expected): " + pointer);
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
Ole32.INSTANCE.CoUninitialize();
}
}
The WMI code that I submitted to the JNA project is only set up to handle primitive values and Strings, not arrays. The problem you are encountering is that WMI is returning the pointer address to the array (either an empty array with VT_EMPTY = 0, or a 32-bit poniter with VT_I4 = 3). But the WMI result is released after the iteration, so you cannot use the WmiResult to fetch the object.
You need to write your own code (using the JNA implementation as a starting point) to grab the SAFEARRAY during iteration. You asked this question on the JNA website and #matthiasblaesing posted the following snippet which works for your use case:
public static void main(String[] args) throws IOException, InterruptedException {
Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED);
// Connect to the server
Wbemcli.IWbemServices svc = WbemcliUtil.connectServer("ROOT\\CIMV2");
// Send query
try {
Wbemcli.IEnumWbemClassObject enumerator = svc.ExecQuery("WQL", "SELECT Caption, Capabilities, CapabilityDescriptions FROM Win32_DiskDrive",
Wbemcli.WBEM_FLAG_FORWARD_ONLY | Wbemcli.WBEM_FLAG_RETURN_IMMEDIATELY, null);
try {
IWbemClassObject[] result;
VARIANT.ByReference pVal = new VARIANT.ByReference();
IntByReference pType = new IntByReference();
IntByReference plFlavor = new IntByReference();
while(true) {
result = enumerator.Next(0, 1);
if(result.length == 0) {
break;
}
COMUtils.checkRC(result[0].Get("Caption", 0, pVal, pType, plFlavor));
System.out.println("---------" + pVal.getValue() + "-------------");
OleAuto.INSTANCE.VariantClear(pVal);
COMUtils.checkRC(result[0].Get("CapabilityDescriptions", 0, pVal, pType, plFlavor));
SAFEARRAY safeArray = (SAFEARRAY) pVal.getValue();
for(int i = safeArray.getLBound(0); i<=safeArray.getUBound(0); i++) {
System.out.println("\t" + safeArray.getElement(i));
}
OleAuto.INSTANCE.VariantClear(pVal);
COMUtils.checkRC(result[0].Get("Capabilities", 0, pVal, pType, plFlavor));
safeArray = (SAFEARRAY) pVal.getValue();
for(int i = safeArray.getLBound(0); i<=safeArray.getUBound(0); i++) {
System.out.println("\t" + safeArray.getElement(i));
}
OleAuto.INSTANCE.VariantClear(pVal);
result[0].Release();
}
} finally {
// Cleanup
enumerator.Release();
}
} finally {
// Cleanup
svc.Release();
}
Ole32.INSTANCE.CoUninitialize();
}

How to Copy multiple text line in clipboard and paste in another non java form

I want to copy multiple text line in System clipboard and paste them row by row into another application.
Example to copy:
a
b
c
d
e
Paste:
a, b, c, ...
I then want to paste it in another non java program (this program contains a text box into which I want to paste the text.). It should still be in the same format even after pasting. After each paste, it should automatically press tab and move the focus to another text box. Rinse and repeat for 2 more rows of text.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Robot r = new Robot();
} catch (AWTException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
String toClipBoardText = jTextField1.getText()+"\n"+jTextField2.getText()+"\n"+jTextField3.getText()+"\n"+jTextField4.getText()+"\n"+jTextField5.getText();
StringSelection stringClip = new StringSelection(toClipBoardText);
clip.setContents(stringClip, stringClip);
}
We use a Scanner to traverse through the lines of code. Then we set the next line to the clipboard and press Ctrl + V to paste the data using the Robot class. After clicking your JButton you have 5 seconds to click into the wanted text box. It will then start pasting and tabbing.
There are some sleep(...) statements in there because I don't know the UI you are working with it better save than sorry and give it some time to react.
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.util.Scanner;
import static java.awt.event.KeyEvent.*;
// ...
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String multiLineText = jTextField1.getText()+"\n"+jTextField2.getText()+"\n"+jTextField3.getText()+"\n"+jTextField4.getText()+"\n"+jTextField5.getText();
Scanner textReader = new Scanner(multiLineText);
Robot r = new Robot();
System.out.println("You have 5 seconds to focus the text box into which the text will be pasted!");
for (int i = 0; i < 5; i++) {
System.out.println(5 - i + "...");
Thread.sleep(1000);
}
System.out.println("Start pasting...");
while (textReader.hasNext()) {
String line = textReader.nextLine().trim();
System.out.println("\t> Pasting \"" + line + "\"");
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(
new StringSelection(line),
null);
pressKeys(r, VK_CONTROL, VK_V);
pressKeys(r, VK_TAB);
}
} catch (AWTException | InterruptedException ex) {
throw new RuntimeException(ex);
}
}
public static void pressKeys(Robot robot, int... keys) throws InterruptedException {
for (int i = 0; i < keys.length; i++) {
robot.keyPress(keys[i]);
Thread.sleep(10);
}
for (int i = 0; i < keys.length; i++) {
robot.keyRelease(keys[keys.length - i - 1]);
Thread.sleep(10);
}
Thread.sleep(100);
}

Java using code from method doesn't work

I'm trying to use a specific code but it won't work for some reason. I have to methods in the same class:
public void InputEnter()
{
if(Input.GetKey(getCoords)) {
Move(GetTransform().GetPos());
System.out.println((GetTransform().GetPos()));
}
}
this method gives me some coordinates of Vector3f once I hit enter. The other code writes to a file.
public void ProcessText()
{
System.out.println("ProcessText Operational");
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords file = new ProcessCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2]));
}
}
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("Coordinates Saved!");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
What I wanted to do is to use the InputEnter method in the ProcessText method so I just deleted InputEnter and used the Input code in the ProcessText method:
public void ProcessText()
{
System.out.println("ProcessText Operational");
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords file = new ProcessCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2]));
}
}
if(Input.GetKey(getCoords)) {
Move(GetTransform().GetPos());
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("pressing enter doesn't work!!");
System.out.println((GetTransform().GetPos()));
}
System.out.println("Input.GetKey doesn't work anymore, but why and how to fix it??");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
however now, pressing enter does no longer give me the coordinates as it did before, I really do not understand why and I would need some help.
Thanks a lot!
Okay it took me a while but I've figured it out, It's actually very simple:
As you can see in ProcessText() I've included both the code that reads from a file and the code that writes to a file.
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("Coordinates Saved!");
My idea was then to put the Input method into the ProcessText method as you can see here:
if(Input.GetKey(getCoords)) {
Move(GetTransform().GetPos());
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("pressing enter doesn't work!!");
System.out.println((GetTransform().GetPos()));
This is almost correct but well.. to have the input work for a gameObject I need to add the Input class as a component:
gameObject.addComponent(new InputClass());
All I had to do instead is to take it out from my ProcessText method and move it into my Input class so it looks like this:
public void Input(float delta)
{
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords data = new ProcessCoords(file_name);
if(Input.GetKey(getCoords)) {
data.writeToFile("makeGrass:" + (GetTransform().GetPos()));
System.out.println("Coordinates Saved!");
System.out.println((GetTransform().GetPos()));
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
After that I was able to actually use the input for the respective gameObject and obviously get the apropriate coordinates writen to the text file only if I press enter.
And here's the result: http://www.pic-upload.de/view-27748157/AnotherExample.png.html
I hope my answer will help someone else in the future!

Android - for loop terminating early

I'm trying to manipulate a JSONArray, rawJArr, (taken from the Reddit API), and get the url and a bitmap (taken from the gfycat "API") from each object to create an ArrayList (listing) of Highlight instances which will be converted to a CardView containing a picture, a short description, and a link to the gfycat.
try {
int count = 0;
int highlightMax;
Bitmap bitmap = null;
Highlight curHighlight;
myJSON = new JSONObject(rawJSON);
curJSON = myJSON.getJSONObject("data");
rawJArr = curJSON.getJSONArray("children");
String strHighlightNo = mySPrefs.getString("pref_highlightNo", "notFound");
if(strHighlightNo.equals("notFound")) {
Log.w("FT", "shared pref not found");
return null;
}
highlightMax = Integer.parseInt(strHighlightNo);
Log.w("Arr Length", Integer.toString(rawJArr.length()));
Log.w("Highlight No", Integer.toString(highlightMax));
for(int i=0; i < rawJArr.length(); i++) {
Log.w("Count", Integer.toString(count));
Log.w("I", Integer.toString(i));
if(count == highlightMax) {
Log.w("FT", "Breakpoint reached!");
break;
}
curJSON = rawJArr.getJSONObject(i).getJSONObject("data");
String url = curJSON.getString("url");
String[] parts = url.split("//");
String imageUrl = "http://thumbs." + parts[1] + "-thumb100.jpg";
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
}
// if there is no available picture, then don't include one in the Highlight
if(bitmap == null) {
Log.w("FT", "Null bitmap");
curHighlight = new Highlight(curJSON.getString("title"), url, null);
listing.add(curHighlight);
count++;
} else {
Log.w("FT", "Bitmap Available");
curHighlight = new Highlight(curJSON.getString("title"), url, bitmap);
listing.add(curHighlight);
count++;
}
}
} catch(JSONException e) {
e.printStackTrace();
return listing;
}
However, my for loop terminates way too early. The current JSONArray I'm using has a length of 25, and I've specified a pref_highlightNo of 15, but my for loop terminates after 6 iterations.
My Log.w tests in the for loop all record the same count (Count: 1, Integer: 1 - Count: 6, Integer: 6).
I'm struggling to see why my loop is terminating: there is no stack trace printed to my console, and my app doesn't crash.
Any idea what's going on?
Turns out the issue was specific to the last url I was trying to create to get the required gfycat - I didn't have any code to handle cases where the link began with http://www.

how to reset program to main string args?

I am writing a program and if it catches an Exception I want to reset the whole program is there anyway please tell me I really need to finish it tonight ?
public static void readinfile(ArrayList<ArrayList> table,
int numberOfColumns,ArrayList<String> header,
ArrayList<ArrayList<String>> original,
ArrayList<String> sntypes, ArrayList<Integer> displaySize,
ArrayList<String> writeOut, Scanner inputStream) {
//System.out.print("enter data file: ");
Scanner keyboard = new Scanner(System.in);
System.out.print("enter data file: ");
String fileName = keyboard.nextLine();
try {
System.out.println("try " + fileName);
inputStream = new Scanner(new FileInputStream(fileName));
System.out.println(inputStream);
} catch (FileNotFoundException E) {
System.out.println("Error in opening file ");
//readinfile(table, numberOfColumns, header,
//original, sntypes,displaySize, writeOut, inputStream );
}
// file is now open and input scanner attached
if (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList<String> rowOne = new ArrayList<String>();
while (lineparse.hasNext()) {
String temp = lineparse.next();
String originaltemp = temp;
writeOut.add(temp);
temp = temp + "(" + (++numberOfColumns) + ")";
displaySize.add(temp.length());
// row.add(lineparse.next());
if (temp.trim().substring(0, 2).equalsIgnoreCase("S ")
|| temp.trim().substring(0, 2).equalsIgnoreCase("N ")) {
rowOne.add(originaltemp);
header.add(temp.substring(2));
sntypes.add(temp.toUpperCase().substring(0, 2).trim());
} else {
System.out.println("Invalid file please enter a new file: ");
//readinfile(table, numberOfColumns, header, original, sntypes,displaySize,writeOut,Name);
readinfile(table, numberOfColumns, header,
original, sntypes, displaySize, writeOut, inputStream);
}
}
// add table here it gives problem later on...
original.add(rowOne);
}
while (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList row = new ArrayList();
int j = 0;
while (lineparse.hasNextLine()) {
String temp = lineparse.next().trim();
int sizeOfrow = temp.trim().length();
if (sizeOfrow > displaySize.get(j)) {
displaySize.set(j, sizeOfrow);
}
if (j < numberOfColumns && sntypes.get(j).equalsIgnoreCase("N")) {
try {
if (temp.equalsIgnoreCase("")) {
row.add(new Double(0.0));
} else {
row.add(new Double(temp.trim()));
}
} catch (NumberFormatException E) {
System.out.println("Opps there is a mistake "
+ "I was expecting a number and I found: " + temp);
System.out.println("This row will be ignored");
// break;
}
} else {
if (temp.equalsIgnoreCase("")) {
row.add((" "));
} else {
row.add(temp);
}
}
j++;
}
if (row.size() == numberOfColumns) {
table.add(row);
}
}// close for while
inputStream.close();
}
homework?
Here's a clue on how to think about it:
main:
start loop
start
do stuff
set ok to end
catch exception
set not ok to end
loop if not ok to end
I'm not sure if you meant this, but the following code will run again and again until it succeeds (as in: doesn't throw an exception):
public static void main(String[] args){
while(true){
try{
// execute your code
break; // if successful, exit loop
}catch(SomeException e){
// handle exception
}catch(SomeOtherException e){
// handle exception
}finally{
// clean up, if necessary
}
}
}
Note: while(true) is an awful construct that I'm sure your teachers won't like. Perhaps you'll find a better way to rephrase that.
This is a bit of a hack but you could try calling the main method again, passing the arguments. As long as you didn't modify the string array of arguments, just call main(args); from a try/catch block in the main routine. Of course, if the exception keeps happening you'll loop infinitely and blow the stack:P

Categories