I'm looking for a solution to receive text input through LWJGL. I'm not referring to the kind of standard keyboard event input offered by LWJGL, I'm looking for the ability to receive actual lines of text input, much like the TextFields offered by AWT/Swing. I'm doing this mostly in the interest of learning, and as such, I have no interest in using a library outside of LWJGL (such as TWL).
Currently, I have something like this:
private boolean shift = false;
private void chatControls(float ticksPassed) {
while (Keyboard.next()) {
if (Keyboard.isKeyDown(Keyboard.KEY_RETURN)) {
this.ui.toggleChat();
} else if (Keyboard.isKeyDown(Keyboard.KEY_DELETE)) {
this.chatText = "";
} else if (Keyboard.isKeyDown(Keyboard.KEY_BACK) && Keyboard.getEventKeyState()) {
try {
this.chatText = this.chatText.substring(0, chatText.length() - 1);
} catch (StringIndexOutOfBoundsException e) {}
} else if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
shift = Keyboard.getEventKeyState();
} else if (Keyboard.getEventKeyState() && !jtLetter) {
if (shift) {
this.chatText += Character.toUpperCase(Keyboard.getEventCharacter());
} else {
this.chatText += String.valueOf(Keyboard.getEventCharacter());
jtLetter = true;
}
} else {
jtLetter = false;
}
this.ui.updateChat(chatText);
}
}
However, it does not manage to properly handle shift, nor any of the other special commands described above. So, what's the best thing to do?
Take a look at this file of the source code of NiftyGUI, which should contain this text handling code.
Just delete your shift handling line and add:
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) && !Keyboard.isKeyDown(Keyboard.KEY_RSHIFT))
shift=true;
before the beginning of the While loop.
Related
I have a login page and a sign up page in my program.
I want to run it only if the user says begin.
These pages are called in the main method of my class, and I have a speech recognizer class.
I want the program to continue only when String output.contains("begin") == true
I tried putting the Class.main(args) in my if(output.contains("begin") == true)) case, there was an unhandled exception, and when i surrounded that section with try and catch, it didn't work.
I was told that Inheriting and implementing the classes from my API will work, but I'm not quite sure how to do it.
final Microphone mic = new Microphone(FLACFileWriter.FLAC);
GSpeechDuplex duplex = new GSpeechDuplex("AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw");
duplex.setLanguage("en");
duplex.addResponseListener(new GSpeechResponseListener() {
String old_text = "";
public void onResponse(GoogleResponse gr) {
String output = gr.getResponse();
if (gr.getResponse() == null) {
this.old_text = response.getText();
if (this.old_text.contains("(")) {
this.old_text = this.old_text.substring(0,
this.old_text.indexOf('('));
}
System.out.println("Paragraph Line Added");
this.old_text = ( response.getText() + "\n" );
this.old_text = this.old_text.replace(")", "").replace("( ", "");
response.setText(this.old_text);
}
if (output.contains("(")) {
output = output.substring(0, output.indexOf('('));
}
if (!gr.getOtherPossibleResponses().isEmpty()) {
output = output + " (" + (String)
gr.getOtherPossibleResponses().get(0) + ")";
}
response.setText("");
response.append(this.old_text);
response.append(output);
System.out.println(output);
if(output.contains("begin") == true){
duplex.stopSpeechRecognition();
mic.close();
Trying_Different_Languages t = new Trying_Different_Languages();
frame.dispose();
}
}
});
Expect The program to begin when i say begin but
It it doesn't begin when I say begin.
The try and catch statements just help in error free compilation.
In a program there should exist only 1 public static void main(String[] args) method. That is the indicator which tells you there starts the program.
Instead of calling the main method you should add a different method which do the stuff you want at a specific point.
So in detail it can look like that:
public class SomeClass {
public static void someMethodName() {
//some stuff you want to execute
}
}
So and where you want to execute the code:
...
SomeClass.someMethodName(); //executes the stuff you want.
In this case it would work if you create different methods which do exactly that you need to do at a specific point.
On the pc in c# this is the webserver i have this part:
private void cases()
{
if (request.QueryString[0] == "uploadstatus")
{
switch (Youtube_Uploader.fileuploadstatus)
{
case "uploading file":
return "uploading";
case "file uploaded successfully":
Youtube_Uploader.fileuploadstatus = "";
return "upload completed";
default:
return "upload unknown state";
}
}
}
Then i have in the client side the java using android studio this code:
Runnable serverChecksRunnable = new Runnable()
{
#Override
public void run()
{
if (connectedSuccess == true)
{
checkServer = Get(iptouse + "uploadstatus");
}
Handler h=new Handler(Looper.getMainLooper());
h.post(new Runnable()
{
#Override
public void run()
{
if (connectedSuccess)
{
if (checkServer != null)
{
String a = null;
try
{
a = new String(checkServer, "UTF-8");
textforthespeacch = a;
if (textforthespeacch.equals("upload completed"))
MainActivity.this.initTTS();
if (textforthespeacch.equals("uploading"))
{
servercheckCounter += 1;
if (servercheckCounter == 1)
{
MainActivity.this.initTTS();
}
}
servercheckCounter = 0;
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
}
});
customHandler.postDelayed(serverChecksRunnable,1000);
}
};
This line send a command to the webserver every second:
checkServer = Get(iptouse + "uploadstatus");
Back to the pc this is the working part: The webserver when i the case is "file uploaded successfully" i then reset the variable Youtube_Uploader.fileuploadstatus = ""; to be empty string the result is that it will say return "upload completed"; only once.
The problem is while it's uploading.
When the case is: "uploading file" on the webserver it keep saying every second "uploading" but i want that it will say "uploading" also only once.
I tried to do also to reset the variable like this:
case "uploading file":
Youtube_Uploader.fileuploadstatus = "";
return "uploading";
But it keep saying "uploading" every second.
I tried in the java the client side code to make some checkings:
if (textforthespeacch.equals("upload completed"))
MainActivity.this.initTTS();
if (textforthespeacch.equals("uploading"))
{
servercheckCounter += 1;
//if (servercheckCounter == 10)
//{
if (servercheckCounter == 1)
{
MainActivity.this.initTTS();
}
// servercheckCounter = 0;
//}
}
So if the it's completed it's working fine saying only once.
But when it's uploading it's saying "uploading" every second.
Another problem might be is the first time i wanted it to say "uploading" every 10 seconds but the webserver might be uploading it before a 10 seconds passed.
So i can't find the right logic and also how to make it work.
I think i want to make it so it will say each status once:
"uploading"
"upload completed"
But i can't make it work saying each status case once only.
The easiest way to solve this is simply to keep a boolean status that tells whether the "uploading" has already been said. You make sure to reset that status to false when starting an upload, and then, whenever an "uploading" status arrives, you check the boolean. Something like this:
private Boolean uploadAnnounceDone = false;
private void checkUpload()
{
String status = cases();
if (status.Equals("uploading"))
{
if (!uploadAnnounceDone)
{
uploadAnnounceDone = true;
PlayVoice(status);
}
}
else
PlayVoice(status);
}
If you reuse this same setup for multiple uploads, make sure to reset the boolean back to False when starting another upload, though.
Note that currently, your code is invalid; the "cases()" function should return that string. You set its return type to void
for some reason, I can do just about any method for a string. This includes:
*Getting the length of the string
*Adding to the string
*Using substring
*And probably everythng else
Except, I cant get the value of the string except when using my drawString method to draw to the screen in lwjgl. Here is my code before i further explain the problem.
public static boolean chatOn = false;
public static String text = "";
public static float typetimer = 0;
public static int ctrltimer = 0;
public static boolean runcmd = false;
public static void chat() {
if (Keyboard.isKeyDown(Keyboard.KEY_TAB)) {
if (ctrltimer < 0) {
chatOn = !chatOn;
Keyboard.destroy();
try {Keyboard.create();} catch (LWJGLException e) {}
ctrltimer = 10;
}
}
ctrltimer -= Game.delta;
typetimer -= Game.delta;
if (chatOn) {
//try {text.replace(null, "happy");} catch(NullPointerException e) {}
System.out.println(text);//print to console, dosen't
Text.drawString(text, 0, 0);//write the text on the screen with my draw method, does work
System.out.println(text);//print to console, dosen't, yet the one drawstring worked
if (typetimer < 0) {
while (Keyboard.next()) {
try {
if (Keyboard.getEventKey() == Keyboard.KEY_BACK) {
text = text.substring(0, text.length()-1);
typetimer = 1;
System.out.println(text);//print to console, doesn't
}
else if (Keyboard.getEventKey() == Keyboard.KEY_RETURN) {
System.out.println(text);//print to console, doesn't
runCommand();
text = "";
chatOn = false;
}
else {
System.out.println(text);//print to console, doesn't
text = text + Keyboard.getEventCharacter();
}
typetimer = 10;
} catch(Exception e){
}
}
}
}
}
public static void runCommand() {
String command = text;
System.out.println(command);//print to console, doesnt
if (command.startsWith("time")) {
try {
String[] time = new String[1];
time = command.split(" ", 0);
Camera.nighttimeASecond = Integer.parseInt(time[0]);
} catch (Exception e){
System.out.println("could not set time");
}
}
}
If you read my notes inside the code you can see where I have put print methods and drawString method. The print methods print nothing and sometimes might print the first few words of the string, although the drawString method worked fine. Thanks - Tyler
If System.out.println(text); is empty before Text.drawString(text, 0, 0); is called, then text should be empty when Text.drawString() is called. You should follow mattias' suggested debugging guide and find out where your issue is occuring (or add some System.out.println()s following text through your code and tracing it if you're particularly lazy :p). Without having a look at your Text class, I'd be willing to bet that the string to be printed is never getting set, and Text is printing a static string, or that the string to be printed is getting changed by the Text class itself.
Judging by:
String command = text;
System.out.println(command);//print to console, doesnt
text is never getting set.
Im parsing HTML code from a site and I'm nearly done. I have the section of text i need from the site, but occasionally there are some links included in the HTMl that i wish to get rid of. I am thinking of using the fact that all of the elements I do not want start with '<' and of course and with '>'. Is there anyway to do this? This is what I have so far.
for(int i = 0; i<desc.length();i++)
{
if(desc.charAt(i)==('<')){
}
}
desc being the string i want to trim up.
It's generally considered a bad idea to parse markup languages like XML and HTML manually. However, if you are only trying to remove all the elements, I could see where a simple script may be useful.
Something I thought worth mentioning, is that if you remove all elements of the HTML, you may have several pieces of text jammed together. Check out this piece of code, see if it helps.
public class RemoveHtmlElements {
public static void main(String[] args) {
String html = "<!DOCTYPE html><html><body><h1>My First Heading</h1>"
+ "<p>My first paragraph.</p></body></html>";
boolean elementsExist = true;
while(elementsExist) {
if(html.contains("<")) {
int open = html.indexOf("<");
int closed = html.indexOf(">", open);
html = html.substring(0, open) + " " + html.substring(closed + 1);
} else {
elementsExist = false;
}
}
System.out.println(html);
}
}
This should clean HTML of any bracketed elements. It will input a space where it removes an element to keep text from being jammed together unexpectedly.
I would try something like this;
StringBuilder sb = new StringBuilder();
boolean open = false;
for (char c : desc.toCharArray()) { // iterate over the characters
if (c == '<') { // if we hit a less then store that the tag is open.
open = true;
} else if (open && c == '>') { // if the tag is open and the close symbol hits close.
open = false;
} else if (!open) { // if the tag isn't open
sb.append(c);
}
}
System.out.println(sb.toString()); // print the string.
I have a java program, that runs in the background and monitors the system clipboard for changes (i do this through polling, as it seems to be the only way besides the "ownership-variant", where i have to reset the content all the time to become the owner). If it discovers an input text in an specific format, it processes that text and overwrites the clipboard with the result (so i can copy the input and right after it paste the result while the program is running in background).
This worked fine so far on Windows, but when running the same program on Mac OS X, the behavior is a little bit strange. As long as i don't copy my results into the system clipboard, the polling mechanism itself works as expected. But at the moment i set the clipboard content out of the java program the first time, it recognizes future extern changes only while becoming active. So i can't just let it run in the background, but instead i have to "copy input -> switch to java-program -> switch back -> paste result" all the time.
As that is annoying and thats exactly the thing i wanted to avoid by this "clipboard monitoring -> result pasting"-method, i would be very happy for any ideas how to fix that issue.
Edit: some code-fragements
public void setClipboardText(String text) {
if (text == null) {
throw new NullPointerException();
}
synchronized (this.lastFoundTextLock) {
this.lastFoundText = text;
Toolkit.getDefaultToolkit().getSystemClipboard()
.setContents(new StringSelection(text), null);
}
}
public String getClipboardText() {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().
getContents(null);
try {
if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String text = (String) t.getTransferData(DataFlavor.stringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
public void run() {
while (true) {
String currentClipboardText = getClipboardText();
boolean isNew;
synchronized (this.lastFoundTextLock) {
isNew = ((this.lastFoundText != null) || (currentClipboardText != null))
&& ((currentClipboardText == null) || !currentClipboardText
.equals(this.lastFoundText));
if (isNew) {
this.lastFoundText = currentClipboardText;
}
}
if (isNew && currentClipboardText != null) {
//new text found
fireNewClipboardTextFound(currentClipboardText);
}
try {
Thread.sleep(this.automaticCheckInterval);
} catch (InterruptedException e) {
// ignore
}
synchronized (this.monitorRunningLock) {
if (!this.monitorRunning) {
break;
}
}
}
}
I see that several others have attempted what you're trying ( Can't copy to a clipboard from a background java application on MAC OSX ) and had marginal success ( Copying to Clipboard in Java ) and few good answers ( java/swing: clipboard paste ) but you might want to investigate further... Can anyone else comment on the changes in Java 6 wrt this issue?