Appending text on a character interval - java

I am trying to write a program where the participant communicates with the program (I/O) via a console. Trick is, the console is part of a GUI, because I need the program to run off of a executable jar file. I append text with a scrollable text field, like so
textArea.append(printChar);
I give the method a String to work with, and it uses a nested for loop to take it, char by char, and append each Char (using string.substring()).
My problem is that it freezes up the entire time its supposed to be printing, then just displays it all. I don't know why, because I tested it using System.out.print, and it worked exactly as I wanted. So something is different about appending and printing. Any ideas?
Also, I am using Thread.Sleep(100) for my wait time.
public void actionPerformed(ActionEvent evt) {
if (!preforming){
preforming = true;
String input = textField.getText(); //Text from Input
textArea.append(dungeon.name + ": " + input + newline); //Add "text" to bottom of console
String[] output = dungeon.action(input);
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(5);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}

I've edited my answer as you are showing more of your codes. Since, there is an outer loop in your code, I just included it inside the run method of timer in this new edit. And also I don't have the code for the dungeon so I just temporarily replace it with constant values so the program can run in my test.
public void actionPerformed(ActionEvent evt) {
java.util.Timer timer = new java.util.Timer();
timer.schedule(new java.util.TimerTask() {
public void run() {
if (!preforming){
preforming = true;
String newline = "\n";
String dungeonName = "Star Light";
String input = textField.getText(); //Text from Input
textArea.append(dungeonName + ": " + input + newline); //Add "text" to bottom of console
String[] output = {
"Twinkle twinkle little star.",
"How I wonder what you are.",
"Up above the world so high."
};
//print everything in array output, char by char, with 2-3 seconds after each
for (int i = 0; i < output.length; i++){
String printThis = output[i];
if (printThis.length() > 0){
for (int j = 0; j < printThis.length(); j++){
String printChar = printThis.substring(j, j+1);
textArea.append(printChar);
//System.out.print(printChar);
try{
Thread.sleep(25);
} catch (InterruptedException e) {
System.out.print("Error ");
}
/*try { //useless
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
textArea.append("" + newline);
}
//cleaning up input bar
textField.setText("");
textField.selectAll();
//Make sure the new text is visible, even if there
//was a selection in the text area.
textArea.setCaretPosition(textArea.getDocument().getLength());
preforming = false;
}
}
}, 1);
}

Related

compare lines in JTextArea

Im working on a project where I create an online-shop-like application. Have everything working apart from last thing, which is reading the whole basket(items added to basket)
I have a button that adds item to the order(they are displayed in jtextarea).
I have another button that finishes shopping and is supposed to print your items which were added to jtextarea. Unfortunately I was only able to figure out how to read the last line in jtextarea. so basically what happens :
customer orders x, amount 1
customer orders y, amount 3
customer orders z, amount 7
It will only print the last line. any suggestion?
Here is the code
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int end = textArea.getDocument().getLength();
int start = 0;
try {
start = Utilities.getRowStart(textArea, end);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
while (start == end)
{
end--;
try {
start = Utilities.getRowStart(textArea, end);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
String text = null;
try {
text = textArea.getText(start, end - start);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
System.out.println("(" + text + ")"); ```

Why turns the string to empty?

If I run this code the first 28 lines of the append.txt are full of numbers but then it is empty, why? It should also contains some numbers!!
Is the String get too big?
try {
OutputStream os = new FileOutputStream(new File("append.txt"), true);
String seq = "11", output = "";
int u = 1;
while(u<=37)
{
String temp = "";
int iter = 1;
for(int i=0; i<seq.length()-1; i++) {
if(seq.charAt(i)==seq.charAt(i+1)) {
iter++;
if(i==seq.length()-2) {
temp += iter + "" + seq.charAt(i);
iter=1;
}
}else {
temp += iter + "" + seq.charAt(i);
if(i==seq.length()-2) {
temp += "1" + seq.charAt(i+1);
}
iter=1;
}
}
seq=temp;
output += seq + "\n";
System.out.println(u + ": " + seq.length());
u++;
}
os.write(output.getBytes(), 0, output.length());
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Ok, I have the solution:
I use Eclipse to show the text file but it magically do not show the rest of the file. If I use any other text editor it will show the rest. Maybe the eclipse txt editor can only show a limited amount of text...
If the String would be too big to create you would get an OutOfMemoryException. This is not the case, your program works and prints 37 lines of numbers with last line being 48410 characters long.
Most likely the editor you are using to view the output fails to render these very long lines. It works in IntelliJ IDEA for me.

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);
}

Why can my program not find a file after saving it

I am working on an inventory program and keep running into an issue. I have some text files that are named using a combination of numbers. I call them shelves. I open them up and edit them to store items in them. I am having a problem after I remove some objects from one of these.
How that process goes is I will open the file. Load it into a JTable. Select the item and amount I wish to remove. Then re save the file. That all works great until I go to open another shelf. Any other shelf I try to open after that process tells me that the shelf does not exist even if it the same one I just used. I can still go through the path on my computer and find it just fine and I can close the program and reopen it and it works just fine again until I remove and item from the shelf. I will post any relevant code below. Thanks for the help guys.
String[] binCombos = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
JComboBox<String> aisle, column, row;
JButton open = new JButton("Open Shelf");
tableHolder = new JScrollPane(shelfsContents);
aisle = new JComboBox<String>(binCombos);
column = new JComboBox<String>(binCombos);
row = new JComboBox<String>(binCombos);
open.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
shelfCombo = aisle.getSelectedItem().toString() + column.getSelectedItem().toString() + row.getSelectedItem().toString() + ".txt";
File shelfName = new File(sPath + "\\" + shelfCombo);
if(shelfName.exists() == true && Console.console.IsPulling() == false)
{
OpenShelf(shelfName);
}
else
{
System.out.println(shelfName + " does not exist");
}
}
});
private void SaveShelf()
{
try
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
bfw.write(tableModel.getValueAt(i, j).toString());
bfw.write(" : ");
}
}
}
bfw.newLine();
}
bfw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try this code
private void SaveShelf(){
PrintWriter pw ;
try
{
pw = new PrintWriter(new File("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
pw.print(tableModel.getValueAt(i, j).toString());
pw.print(" : ");
}
}
}
pw.println();
pw.flush();
}
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
pw.close();
}
}

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