Java - <identifier> expecter error - java

I was writing a java tool that toggles wether a game mod is active (specifically, the game is Dwarf Fortress, and the mod is DFHack) and the program is nearly done. However, I cant seem to get the variables right that tell the program how to check if the mod is active or not.
I got this status file containing a single character, being 1 for active and 0 for inactive.
This is the code (By the way, if it is needed: I checked the name of the file and it matches the class declaration).
package nl.dirkkok.dfhacktoggle;
/*
* DFHacktoggle
* 28-12-2013 # 2:02 PM
*
* This program will disable DFHack if it is enabled, and enable it if it is disabled.
*
* Using this tool is at your own risk. If you send me an email complaining about this program doing anything you dont want, then I will laugh at you, and tell you that you cant read. :)
*
* Created by Dirk Kok <d.kok.2000#gmail.com>. This tool is my property, but I do not claim rights of neither Dwarf Fortress nor DFHack.
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.IOException;
import java.nio.file.NoSuchFileException;
public class Dfhacktoggle {
private static Path statusfile = "dfhack-status";
private boolean dfhack = false;
private byte[] fileArray = new byte[1];
private byte[] active = new byte[1];
private byte[] inactive = new byte[1];
private file dfhacksdl = "SDLdfhack.dll";
private file vanillasdl = "SDLreal.dll";
private file sdl = "SDL.dll";
active[] <byte> = 1;
inactive[] <byte> = 0;
public static void main(String[] args) {
try {
fileArray = Files.readAllBytes(file);
if (fileArray[0] == 1) {
p("DFHack is active. Deactivating...");
try {
if (vanillasdl.exists()) throw new java.io.IOException("File exists");
sdl.renameTo(dfhacksdl);
vanillasdl.renameTo(sdl);
Files.write(statusfile, inactive, WRITE);
} catch (IOException x) {
errp("DFHack could not be deactivated. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("IOException: " + x);
} catch (NoSuchFileException x) {
errp("Status file could not be found. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("NoSuchFileException: " + x);
}
} else if (fileArray[0] == 0) {
p("DFHack is inactive. Activating...");
try {
if(vanillasdl.exists()) throw new java.io.IOException("File exists");
sdl.renameTo(vanillasdl);
dfhacksdl.renameTo(sdl);
Files.write(statusfile, active, WRITE);
} catch (IOException x) {
errp("Status could not be checked. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("IOException: " + x);
} catch (NoSuchFileException x) {
errp("Status file could not be found. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("NoSuchFileException: " + x);
}
} else {
errp("DFHack's status could not be checked. Reinstalling the program will solve this.");
}
} catch (IOException x) {
errp("Status could not be checked. Reinstalling the program will solve this.");
errp("Detailed info:");
errp(x);
}
}
public void p(String txt) {
System.out.println(txt);
}
public void errp(String txt) {
System.err.println(txt);
}
}
The compiler returns this:
F:\Dfhack-swap>javac Dfhacktoggle.java
Dfhacktoggle:29: error: <identifier> expected
active[] <byte> = 1;
^
Dfhacktoggle:30: error: <identifier> expected
inactive[] <byte> = 0;
^

Your syntax is wrong there's no active[] <byte> = 1; in Java
If you want to assign it a value You can do it in this way
active[0] = 1;
inactive[0] = 0;
But there's no need for array to use it as a boolean you can just define it as a byte
byte active= 1;
byte inactive= 0;

Related

Java try/catch error with parameter of class build

I am still pretty new to coding and am working on a project where the idea is to look over an excel spreadsheet and put then create a class that builds a statement for each row's information. I have the following code below.
public class Message {
// information from excel
String excelPath = "./data/RecruiterData.xlsx";
String sheetName = "Sheet1";
ExcelUtils excel = new ExcelUtils(excelPath, sheetName);
int excelRowCount = excel.getRowCount();
// build recruiter class
public static Recruiter[] buildRecruiter = {
try {
// this needs to be a for each cell filled in excel, create an instance of recruiter
for (int i = 0; i < excelRowCount; i++) {
new Recruiter(excel.getCellData(1, i), excel.getCellData(2, i), excel.getCellData(3, i), excel.getCellData(4, i));
}
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
But yet it is giving me a bunch of errors. The first error is in the public static Recruiter[] where right at the end of that line, it says ; expect } expected.
Next, there are errors with my try catch statement just saying unexpected token.
Finally, it is giving each parameter in the new Recruiter line an error saying unhandled exception: java.io.IOException. I was not sucessful trying to find help online so I thought I would ask about it. Thank you so much!
mmmm i think your error is in the method declaration
public class Message {
// information from excel
static String excelPath = "./data/RecruiterData.xlsx";
static String sheetName = "Sheet1";
static ExcelUtils excel = new ExcelUtils(excelPath, sheetName);
static int excelRowCount = excel.getRowCount();
// build recruiter class
public static Recruiter[] buildRecruiter () {
//in java methods are declarated for that way [scope] [instance] data_type name ([params]) { [body; return data_type]}
//next if you declare static your function all fields must be static too or change te method declaration to public or private
try {
// this needs to be a for each cell filled in excel, create an instance of recruiter
for (int i = 0; i < excelRowCount; i++) {
new Recruiter(excel.getCellData(1, i), excel.getCellData(2, i), excel.getCellData(3, i), excel.getCellData(4, i));
}
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}

Glpk java and .mod file

I've got a .mod file and I can run it in java(Using netbeans).
The file gets data from another file .dat, because the guy who was developing it used GUSEK. Now we need to implement it in java, but i dont know how to put data in the K constant in the .mod file.
Doesn't matter the way, can be through database querys or file reading.
I dont know anything about math programming, i just need to add values to the already made glpk function.
Here's the .mod function:
# OPRE
set K;
param mc {k in K};
param phi {k in K};
param cman {k in K};
param ni {k in K};
param cesp;
param mf;
var x {k in K} binary;
minimize custo: sum {k in K} (mc[k]*phi[k]*(1-x[k]) + cman[k]*phi[k]*x[k]);
s.t. recursos: sum {k in K} (cman[k]*phi[k]*x[k]) - cesp <= 0;
s.t. ocorrencias: sum {k in K} (ni[k] + (1-x[k])*phi[k]) - mf <= 0;
end;
And here's the java code:
package br.com.genera.service.otimi;
import org.gnu.glpk.*;
public class Gmpl implements GlpkCallbackListener, GlpkTerminalListener {
private boolean hookUsed = false;
public static void main(String[] arg) {
String[] nomeArquivo = new String[2];
nomeArquivo[0] = "C:\\PodaEquipamento.mod";
System.out.println(nomeArquivo[0]);
GLPK.glp_java_set_numeric_locale("C");
System.out.println(nomeArquivo[0]);
new Gmpl().solve(nomeArquivo);
}
public void solve(String[] arg) {
glp_prob lp = null;
glp_tran tran;
glp_iocp iocp;
String fname;
int skip = 0;
int ret;
// listen to callbacks
GlpkCallback.addListener(this);
// listen to terminal output
GlpkTerminal.addListener(this);
fname = arg[0];
lp = GLPK.glp_create_prob();
System.out.println("Problem created");
tran = GLPK.glp_mpl_alloc_wksp();
ret = GLPK.glp_mpl_read_model(tran, fname, skip);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
throw new RuntimeException("Model file not found: " + fname);
}
// generate model
GLPK.glp_mpl_generate(tran, null);
// build model
GLPK.glp_mpl_build_prob(tran, lp);
// set solver parameters
iocp = new glp_iocp();
GLPK.glp_init_iocp(iocp);
iocp.setPresolve(GLPKConstants.GLP_ON);
// do not listen to output anymore
GlpkTerminal.removeListener(this);
// solve model
ret = GLPK.glp_intopt(lp, iocp);
// postsolve model
if (ret == 0) {
GLPK.glp_mpl_postsolve(tran, lp, GLPKConstants.GLP_MIP);
}
// free memory
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
// do not listen for callbacks anymore
GlpkCallback.removeListener(this);
// check that the hook function has been used for terminal output.
if (!hookUsed) {
System.out.println("Error: The terminal output hook was not used.");
System.exit(1);
}
}
#Override
public boolean output(String str) {
hookUsed = true;
System.out.print(str);
return false;
}
#Override
public void callback(glp_tree tree) {
int reason = GLPK.glp_ios_reason(tree);
if (reason == GLPKConstants.GLP_IBINGO) {
System.out.println("Better solution found");
}
}
}
And i'm getting this in the console:
Reading model section from C:\PodaEquipamento.mod...
33 lines were read
Generating custo...
C:\PodaEquipamento.mod:24: no value for K
glp_mpl_build_prob: invalid call sequence
Hope someone can help, thanks.
The best way would be to read the data file the same way you read the modelfile.
ret = GLPK.glp_mpl_read_data(tran, fname_data, skip);
if (ret != 0) {
GLPK.glp_mpl_free_wksp(tran);
GLPK.glp_delete_prob(lp);
throw new RuntimeException("Data file not found: " + fname_data);
}
I resolved just copying the data block from the .data file into the .mod file.
Anyway,Thanks puhgee.

Java Applet using local scanner not working and no errors

I am a newbie in Java but I need to make a scanner (that has a built in ocr) output some content to a browser. I haven't gotten to the browser yet, but the code works when I run it as an application.
With the scanner, I received Java code that makes the scanner take a picture, then read from it and output it back to the console. I added a few lines to make it an applet:
import gx.*;
import pr.*;
import java.applet.*;
public class DocScan extends Applet
{
/**
*
*/
private static final long serialVersionUID = 1L;
static
{
try
{
System.loadLibrary("jgx");
System.loadLibrary("jpr");
}
catch (UnsatisfiedLinkError e)
{
System.err.println("Native code library failed to load." + e);
System.exit(1);
}
}
public static void main(String argv[])
{
Lib lib = new Lib();
String text;
String[] ec ={ "Ok", "Warning", "Error" };
try
{
/* Opening the PR system */
lib.FunctionStart("Opening system files");
PassportReader pr = new PassportReader(); /* Object for the PR system */
lib.FunctionEnd();
/* Validity check */
if (!pr.IsValid())
{
lib.Error("Failed to initialize!");
lib.PrintStat();
}
/* Connecting to the first device */
lib.FunctionStart("Connecting to the first device");
pr.UseDevice(0, jpr.PR_UMODE_FULL_CONTROL);
lib.FunctionEnd();
/* Using the device */
while (!lib.KbHit())
{
lib.ProcessStart("Processing document");
try
{
/* Capturing images */
lib.FunctionStart("Capturing images");
pr.Capture();
lib.FunctionEnd();
/* Getting document data */
lib.FunctionStart("Recognizing.");
prDoc doc = pr.Recognize(0);
lib.FunctionEnd();
if (!doc.IsValid()) lib.WriteLine("No data found.");
else
{
/* Displaying document type */
lib.WriteLine("Document type: " + doc.Code() + ", status: " + ec[doc.Status() / 100]);
/* Get some fixed fields and displaying them */
text = doc.Field(jpr.PR_DF_NAME);
if (!text.equals("")) lib.WriteLine("NAME \"" + text + "\" [" + ec[doc.FieldStatus(jpr.PR_DF_NAME) / 100] + "]");
text = doc.Field(jpr.PR_DF_DOCUMENT_NUMBER);
if (!text.equals("")) lib.WriteLine("DOCUMENT NUMBER \"" + text + "\" [" + ec[doc.FieldStatus(jpr.PR_DF_DOCUMENT_NUMBER) / 100] + "]");
text = doc.Field(jpr.PR_DF_EXPIRY_DATE);
if (!text.equals("")) lib.WriteLine("EXPIRY DATE \"" + text + "\" [" + ec[doc.FieldStatus(jpr.PR_DF_EXPIRY_DATE) / 100] + "]");
/* Searching for fields and displaying them */
gxVariant pdoc = doc.ToVariant();
gxVariant fieldlist = new gxVariant();
pdoc.GetChild(fieldlist, jgx.GX_VARIANT_BY_ID, jpr.PRV_FIELDLIST, 0);
int nitems = fieldlist.GetNItems();
for (int i = 0; i < nitems; i++)
{
gxVariant field = new gxVariant();
fieldlist.GetItem(field, jgx.GX_VARIANT_BY_INDEX, 0, i);
int field_code = field.GetInt();
text = doc.Field(field_code);
if (!text.equals("")) lib.WriteLine("[" + field_code + "] \"" + text + "\" [" + ec[doc.FieldStatus(field_code) / 100] + "]");
if (field_code >= jpr.PR_DF_FORMATTED) continue;
try
{
gxImage img = doc.FieldImage(field_code);
if (img.IsValid()) img.Save(field_code + ".jpg", jgx.GX_JPEG);
}
catch (RuntimeException e)
{
lib.DisplExcp(e);
}
}
}
}
catch (RuntimeException e)
{
lib.DisplExcp(e);
}
lib.ProcessEnd();
lib.WaitForSec(3);
}
/* Closing the device */
lib.FunctionStart("Closing the device");
pr.CloseDevice();
lib.FunctionEnd();
}
catch (RuntimeException e)
{
lib.DisplExcp(e);
}
lib.PrintStat();
}
}
I am using Eclipse as an IDE. Right now my goal is to simply make the scanner "flash". I know that the output is to the console and I will not see anything from it in an applet, but it should still flash.
When I run this code as an application, it works. The scanner takes a picture and then it outputs what it has read to the console.
When I run this code as an Applet, the applet starts and does nothing. It just stays there with no errors of any kind (at least that's what Eclipse is showing me).
I read that I should allow the applet accesss, so I edited:
c:\program files\java\jre8\lib\security\java.policy
and added this at the end:
grant {
permission java.security.AllPermission;
};
Which should allow applets full access. However, there is no change - the applet still launches and does nothing.
Can anyone point me in the right direction? Why is the code not working when I run it as an applet?

How to call a class that accepts command line arguments?

I am not a good programmer. In school, I learned MATLAB. So i have no idea what I am doing.
I am working with the ThingMagic M6 reader. They have their own API. I wanted to create my own application to read the program. I want to use a sample program that they have supplied (since my program doesn't seem to work). However, the supplied program only accepts command line arguments. How do i change it so I can pass arguments to it in my code.
This is the supplied code: (at the command line I input tmr://10.0.0.101)
/**
* Sample program that reads tags for a fixed period of time (500ms)
* and prints the tags found.
*/
// Import the API
package samples;
import com.thingmagic.*;
public class read
{
static void usage()
{
System.out.printf("Usage: demo reader-uri <command> [args]\n" +
" (URI: 'tmr:///COM1' or 'tmr://astra-2100d3/' " +
"or 'tmr:///dev/ttyS0')\n\n" +
"Available commands:\n");
System.exit(1);
}
public static void setTrace(Reader r, String args[])
{
if (args[0].toLowerCase().equals("on"))
{
r.addTransportListener(r.simpleTransportListener);
}
}
static class TagReadListener implements ReadListener
{
public void tagRead(Reader r, TagReadData t) {
System.out.println("Tag Read " + t);
}
}
public static void main(String argv[])
{
System.out.println(argv.getClass().toString());
// Program setup
TagFilter target;
Reader r;
int nextarg;
boolean trace;
r = null;
target = null;
trace = false;
nextarg = 0;
if (argv.length < 1)
usage();
if (argv[nextarg].equals("-v"))
{
trace = true;
nextarg++;
System.out.println("Trace");
}
// Create Reader object, connecting to physical device
try
{
TagReadData[] tagReads;
r = Reader.create(argv[nextarg]);
if (trace)
{
setTrace(r, new String[] {"on"});
}
r.connect();
if (Reader.Region.UNSPEC == (Reader.Region)r.paramGet("/reader/region/id"))
{
r.paramSet("/reader/region/id", Reader.Region.NA);
}
r.addReadListener(new TagReadListener() );
// Read tags
tagReads = r.read(500);
// Print tag reads
for (TagReadData tr : tagReads)
System.out.println(tr.toString());
// Shut down reader
r.destroy();
}
catch (ReaderException re)
{
System.out.println("Reader Exception : " + re.getMessage());
}
catch (Exception re)
{
System.out.println("Exception : " + re.getMessage());
}
}
}
This is me trying to use it: (arg comes from a JTextField)
String[] argv = new String[1];
argv[0] = arg;
readOnceApp(argv);
I have a feeling there is a really simple answer to this problem, I just can't figure it out. I searched the internet for a few days and read books, and still can't figure it out. Any help is appreciated. Thank You.
edit: readOnceApp is one method I wrote. It is basically just the main method of the supplied code. I can include it, if it will help. I just didn't want to post too much code.
If you want to call the "main" method of a class from another class, do it like this:
String [] args = new String [1];
args[0]= "some param";
readOnceApp.main(args);
This is making the assumption that "readOnceApp" is the name of your class. (BTW, you should follow the convention of using capitalized class names, e.g. ReadOnceApp).
Hope this helps.

How do I make my java application open a console/terminal window?

Is there any way I can make an executable .jar that will open up the command line when double clicked?
I'm making a text-based adventure game. As of right now it is just a maze with rooms. Eventually it is going to be much bigger and more in depth but for now I just want to get the basic structure down. Anyways, to make this work I've been getting output and input from the System.out.printf command and the java.util.Scanner. It's all working beautifully so far but I've realized I'm going to run into a problem when I try to send this to other people that don't know how or just don't want to run the program from the command line.
I found this while looking for an answer myself, I ended up writing this bit:
/**
* This opens a command line and runs some other class in the jar
* #author Brandon Barajas
*/
import java.io.*;
import java.awt.GraphicsEnvironment;
import java.net.URISyntaxException;
public class Main{
public static void main (String [] args) throws IOException, InterruptedException, URISyntaxException{
Console console = System.console();
if(console == null && !GraphicsEnvironment.isHeadless()){
String filename = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
Runtime.getRuntime().exec(new String[]{"cmd","/c","start","cmd","/k","java -jar \"" + filename + "\""});
}else{
THEMAINCLASSNAMEGOESHERE.main(new String[0]);
System.out.println("Program has ended, please type 'exit' to close the console");
}
}
}
not sure if my answer is still relevant, but feel free to use it with the comment kept in o/
Only flaw I can think of is that it leaves the cmd window open after the program completes.
Usage: place this class in the same package as your main class and set it as the main class, it will open a command prompt window if one is not open, or if one is open launch the main class. Name / location of jar file is automatic. Designed for windows, but if you want it for another system just message me and I'll fix it. (I could do OS detection but I'm lazy and just making this so I can turn in a double-click jar file to my professor who uses windows).
If you want full control, you can implement a Console window in Swing which does what you have now.
If you cannot open said window (if headless) or the user asks for it on the command line, then just default to your current behaviour.
Double-clicking a jar opens it with whatever application you've associated to it in your OS. By default, javaw[.exe] is normally associated to jar files. That's the binary that runs without a terminal window. To see a terminal on double-click, you'd need to associate the java[.exe] binary with jar files.
Or you can provide a .sh .bat that will open a terminal and call your java in it.
As long as the .jar is executed with java.exe, a commandline window will always show up. executing it with javaw.exe would prevent this.
for further reading:
http://download.oracle.com/javase/1.4.2/docs/tooldocs/windows/java.html
So this is my solution, I used the code from #Brandon Barajas and modified it. It creates a batchfile that starts the program by itself.
public static void main(String[] args){
Console console = System.console();
if(console == null && !GraphicsEnvironment.isHeadless()) {
String filename = YOURMAINCALSS.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6);
try {
File batch = new File("Launcher.bat");
if(!batch.exists()){
batch.createNewFile();
PrintWriter writer = new PrintWriter(batch);
writer.println("#echo off");
writer.println("java -jar "+filename);
writer.println("exit");
writer.flush();
}
Runtime.getRuntime().exec("cmd /c start \"\" "+batch.getPath());
} catch(IOException e) {
e.printStackTrace();
}
} else {
//your program code...
}
}
If you want you can add a writer.println("pause"); before the "exit" print, to keep the window open after the progam finishes. Then you need to hit ENTER to close the window.
You can use this program. This program creates a console for JAR programs (when JAR programs are run by double clicking on them).
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.border.*;
class InitComponents {
public static JFrame setupJFrameAndGet(String title, int width, int height) {
JFrame tmpJF = new JFrame(title);
tmpJF.setSize(width, height);
tmpJF.setLocationRelativeTo(null);
tmpJF.setLayout(null);
tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return tmpJF;
} // end of setupJFrameAndGet
public static JTextArea setupJTextAreaAndGet(String text, int rows, int columns, boolean setEditableFlag, boolean setLineWrapFlag, boolean setWrapStyleWordFlag, boolean setBoundsFlag, int xpos, int ypos, int width, int height) {
JTextArea tmpJTA = new JTextArea(text, rows, columns);
tmpJTA.setEditable(setEditableFlag);
tmpJTA.setLineWrap(setLineWrapFlag);
tmpJTA.setWrapStyleWord(setWrapStyleWordFlag);
if (setBoundsFlag == true) {
tmpJTA.setBounds(xpos, ypos, width, height);
}
return tmpJTA;
} // end of setupJTextAreaAndGet
public static JScrollPane setupScrollableJTextAreaAndGet(JTextArea jta, int xpos, int ypos, int width, int height) {
JScrollPane tmpJSP = new JScrollPane(jta);
tmpJSP.setBounds(xpos, ypos, width, height);
return tmpJSP;
} // end of setupScrollableJTextAreaAndGet
public static JMenuBar setupJMenuBarAndGet() {
JMenuBar tmpJMB = new JMenuBar();
return tmpJMB;
} // end of setupJMenuBarAndGet
public static JMenu setupJMenuAndGet(String text) {
JMenu tmpJM = new JMenu(text);
return tmpJM;
} // end of setupJMenuAndGet
public static JMenuItem setupJMenuItemAndGet(String text) {
JMenuItem tmpJMI = new JMenuItem(text);
return tmpJMI;
} // end of setupJMenuItemAndGet
}// end of InitComponents
public class ConsoleForJARPrograms implements KeyListener, ActionListener {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
String title = null;
String text = null;
JFrame jf = null;
JTextArea jta = null;
JScrollPane jsp = null;
JMenuBar jmb = null;
JMenu jm = null;
JMenuItem jmi = null;
int initialCaretPosition = 0;
int currentCaretPosition = 0;
boolean inputAvailable = false;
// key codes
int BACKSPACE = 8;
int ENTER = 10;
int PG_UP = 33; // do nothing for this key pressed
int PG_DN = 34; // do nothing for this key pressed
int END = 35;
int HOME = 36;
int LEFT_ARROW = 37;
int UP_ARROW = 38; // do nothing for this key pressed
//int RIGHT_ARROW = 39; // handled by JTextArea
int DOWN_ARROW = 40; // do nothing for this key pressed
int CTRL = 128;
int A = 65; // disable ctrl-a
int H = 72; // handle ctrl-h
//int DELETE = 127; // handled by JTextArea
public void actionPerformed(ActionEvent ae) {
int cCurrPos = jta.getCaretPosition();
jta.selectAll();
jta.copy();
jta.select(cCurrPos, cCurrPos);
} // end of actionPerformed
public void keyTyped(KeyEvent ke) {
} // end of keyTyped
public void keyReleased(KeyEvent ke) {
} // end of keyReleased
public void keyPressed(KeyEvent ke) {
int keyCode = ke.getKeyCode();
if ((keyCode == PG_UP) || (keyCode == PG_DN) || (keyCode == UP_ARROW) || (keyCode == DOWN_ARROW) || ((keyCode == A) && (ke.getModifiersEx() == CTRL))) {
ke.consume();
} else if ((keyCode == LEFT_ARROW) || (keyCode == BACKSPACE) || ((keyCode == H) && (ke.getModifiersEx() == CTRL))) {
synchronized(this) {
if (jta.getCaretPosition() <= initialCaretPosition) {
ke.consume();
}
} // end of synchronized block
} else if (keyCode == HOME) {
synchronized(this) {
jta.setCaretPosition(initialCaretPosition);
ke.consume();
} // end of synchronized block
} else if (keyCode == END) {
synchronized(this) {
jta.setCaretPosition(jta.getDocument().getLength());
ke.consume();
} // end of synchronized block
} else if (keyCode == ENTER) {
jta.setCaretPosition(jta.getDocument().getLength());
synchronized(this) {
currentCaretPosition = jta.getCaretPosition();
// If character at initial caret position is newline then it means that the user has
// pressed enter without enetring any other character. Also, the code gets called here
// as soon as enter is pressed which means that the caret position (jta.getCaretPosition())
// of the document will be incremented by 1 by the system after this code returns.
// This means that if at initial caret position, the character is newline, then we must ignore
// this enter and increment initial caret position by 1 and do not set inputAvailable to true.
try {
String charAtInitialCaretPosition = jta.getText(initialCaretPosition, 1);
if ((charAtInitialCaretPosition.equals("\n")) == true) {
initialCaretPosition++;
}
} catch (Exception e) {
}
/*
debug: start
try {
System.out.println("keyPressed (1): initial = " + initialCaretPosition + ", current = " + currentCaretPosition + ", System current = " + jta.getDocument().getLength());
String initialString = jta.getText(initialCaretPosition, 1);
String currentString = jta.getText(currentCaretPosition, 1);
System.out.println("char at initial = " + initialString + ", char at current = " + currentString);
if ((initialString.equals("\n")) == true) {
System.out.println("char at initial is newline");
}
if ((currentString.equals("\n")) == true) {
System.out.println("char at current is newline");
}
} catch (Exception e) {
}
debug:end
*/
if ((currentCaretPosition - initialCaretPosition) > 0) {
inputAvailable = true;
notifyAll();
}
} // end of synchronized block
} // end of if else if
} // end of keyPressed
String getInputFromJTextArea(JTextArea jta) {
int len = 0;
String inputFromUser = "";
while (true) {
synchronized(this) {
if (inputAvailable == true) {
len = currentCaretPosition - initialCaretPosition;
try {
inputFromUser = jta.getText(initialCaretPosition, len);
initialCaretPosition = currentCaretPosition;
} catch (Exception e) {
inputFromUser = "";
return inputFromUser;
} // end of outer try catch
/*
The following lines of code are not needed now.
if ((len == 1) && (inputFromUser.equals("\n")) == true) {
try {
wait();
continue;
} catch (Exception e) {
} // end of try catch
} else if (Character.compare(inputFromUser.charAt(0), '\n') == 0) { // matched
// remove first character from inputFromUser
inputFromUser = inputFromUser.substring(1);
}
*/
inputAvailable = false;
return inputFromUser;
} else {
try {
wait();
continue;
} catch (Exception e) {
} // end of try catch
} // end of if else inputAvailable
} // end of synchronized block
} // end of while true
} // end of getInoutFromJtextArea
void outputToJTextArea(JTextArea jta, String text) {
jta.append(text);
jta.setCaretPosition(jta.getDocument().getLength());
synchronized(this) {
initialCaretPosition = jta.getCaretPosition();
}
} // end of outputToJTextArea
void begin() {
while (true) {
outputToJTextArea(jta, "Enter some input (press enter after inputting): ");
String input = getInputFromJTextArea(jta);
outputToJTextArea(jta, "User input was: " + input + "\n\n");
}
} // end of begin
void configureJTextAreaForInputOutput(JTextArea jta) {
jta.addKeyListener(this);
// remove all mouse listeners
for (MouseListener listener : jta.getMouseListeners()) {
//outputToJTextArea(jta, "\nRemoving mouse listener\n");
jta.removeMouseListener(listener);
}
// remove all mouse motion listeners
for (MouseMotionListener listener : jta.getMouseMotionListeners()) {
//outputToJTextArea(jta, "\nRemoving mouse motion listener\n");
jta.removeMouseMotionListener(listener);
}
// remove all mouse wheel listeners
for (MouseWheelListener listener : jta.getMouseWheelListeners()) {
//outputToJTextArea(jta, "\nRemoving mouse wheel listener\n");
jta.removeMouseWheelListener(listener);
}
} // end of configureJTextAreaForInputOutput
void createAndShowGUI() {
title = "Console";
jf = InitComponents.setupJFrameAndGet(title, screenWidth - 150, screenHeight - 100);
jta = InitComponents.setupJTextAreaAndGet("", 1000, 100, true, true, true, false, 0, 0, 0, 0);
configureJTextAreaForInputOutput(jta);
jsp = InitComponents.setupScrollableJTextAreaAndGet(jta, 10, 10, screenWidth - 180, screenHeight - 180);
jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jf.add(jsp);
//jf.setLocation(screenWidth / 5, screenHeight / 6);
jmb = InitComponents.setupJMenuBarAndGet();
jm = InitComponents.setupJMenuAndGet("Copy All to Clipboard");
jm.setBorder(BorderFactory.createLineBorder(Color.green, 2));
jmi = InitComponents.setupJMenuItemAndGet("Copy All to Clipboard");
jm.add(jmi);
jmb.add(jm);
jmi.addActionListener(this);
jf.setJMenuBar(jmb);
jf.setVisible(true);
} // end of createAndShowGUI
public static void main(String[] args) {
ConsoleForJARPrograms cfjp = new ConsoleForJARPrograms();
cfjp.createAndShowGUI();
cfjp.begin();
} // end of main
} // end of ConsoleForJARPrograms
I guess the simplest way is to write a simple shortcut for your jar file. e.g. eclipse (like the most ide's) is able to export a jar file with all necessary libraries, etc. so you just need to set the shortcut command like "java -jar filePath/file.jar" (filePath: e.g. ./bin/file.jar)
One way to accomplish this is to create a .bat file with the command: "java -jar filePath/yourfile.jar" (without ""). Make sure to include the file path or else your file won't be found.
Though the question was answered already, this is a simple way to do it.
You could create your own window, using Swing or Awt, using a TextPane, the only problem... is how to input and use like the cmd should do. But you can always do this with alerts and all...
Other way, is running directly from a batch file, showing on the console.
You should consider too, make your game DIRECTLY on batch... is not a bad language to make and is present on every Windows Operating Systems.
(Hope was useful ('cause i'm new), and my english was not THAT BAD...)
Use Launch4j and in Basic Tab give your exe name in Output file and then load a jar file in Jar Tab.
Go to Header Tab and select Console.
Then go to JRE tab and give the JRE version e.g 1.8.0
Then click the build wrapper button (kind of setting icon)
It will ask you to save a xaml file just put some random name and click save.
Finally your .exe is created and you can run now.
I found another way ... for example for project myproject with a class foo in package bar :
java -cp myproject.jar; bar.foo
I wrote a little snippet which uses a similar approach to Brandon Barajas' solution.
It supports Mac (untested), Linux (tested with xfce) and Windows (cmd) in one go (although you might need to customize the linux terminal commands, since there are many different ones).
https://github.com/Lartsch/java-selfconsole/
Really helpful in the following case:
you don't want the jar to have to be directly executed in a console
you can't use any custom made console / can't use any GUI library
you don't want to ship bridge starting files like sh, bat, ...
you simply want the jar to open itself in a console on double-click

Categories

Resources