Java JTextArea multiline help - java

one problem I'm having is i have 2 JTextAreas and i need to add a list of items to them.
The problem I'm running into is the string doesn't automatically move to the next line when it reaches the end of the JTextArea. So to solve this problem I tried this: (sorry if my code is kinda sloppy.)
public void setIncludeAndExclude(ArrayList<JComboBox> boxes){
String in = "",ex = "";
String[] inSplit, exSplit;
boolean[] include = new boolean[boxes.get(0).getModel().getSize()-1];
for(int i = 0; i < boxes.size(); i ++){
if(boxes.get(i).getSelectedIndex() != 0){
include[boxes.get(i).getSelectedIndex() -1] = true;
}
}
for(int i = 0; i < include.length; i ++){
if(include[i]){
//numToItem is a method that turns an int into a string e.g. 1 = "Acesss Doors"
in += (numToItem(i+1)+ ", ");
}else{
ex += (numToItem(i+1)+ ", ");
}
}
//take off the last comma
in = in.substring(0,in.lastIndexOf(","));
ex = ex.substring(0,ex.lastIndexOf(","));
//get how many lines there should be
inSplit = new String[(in.length()/100) +1];
exSplit = new String[(ex.length()/100) +1];
String temp;
int istart = 0, iend = Math.min(100, in.length()), estart = 0, eend = Math.min(100, ex.length());
for(int i = 0; i < inSplit.length; i ++){
try{
temp = in.substring(istart, iend);
int Iindex = temp.lastIndexOf(",");
temp = ex.substring(estart, eend);
int Eindex = temp.lastIndexOf(",");
inSplit[i] = in.substring(istart, Iindex);
exSplit[i] = ex.substring(estart, Eindex);
istart = Iindex; iend = Math.min(iend + 100, in.length());
estart = Eindex; eend = Math.min(eend + 100, ex.length());
}catch(Exception e){
e.printStackTrace();
}
}
//reset in and ex to ""
in = ""; ex = "";
//set in and ex to the new string with newline characters
for(int i = 0; i < inSplit.length; i ++){
in += inSplit[i] + "\n";
ex += exSplit[i] + "\n";
}
//set the text of the JTextAreas
Include.setText(in);
Exclude.setText(ex);
}
any help on what i could do different or change would be much appreciated

JTextArea has setLineWrap(...) and the setWrapStyleWord(...) methods. Perhaps all you need to do is call these on your JTextArea's setting both to true.
One bit of criticism: your code is very hard to interpret as you give no indication which variables are JTextAreas (which I'm guessing are "Include" and "Exclude"), and no comments as to what is doing what. Please write your questions here with the idea that we know nothing about your code and can't read minds. The clearer your question, usually the easier it is to answer. Thanks.

Maybe a better solution is to use JList. See How to Use Lists.
The code you posted is not complete. If you still want to use a text area solution then post your SSCCE that demonstrates the problem.

Related

How to check if a string is contained in another substring using "indexOf" and "for" iterator in Java Language?

I'm new to programming in Java so I'd like some help on this matter, thank you very much for your time :)
I want to check if "CheckAutonomy" is contained in a substring using indexOf and a for iterator to iterate trough my objects,(ambient contains 4 objects everytime, this is the "wouldbe" code :
ReEdit: I added more details, i hope this will be enough , i really don't know how to grasp it :|
public static void scrivi(JSONArray jsa, String nome, String versione ) throws IOException{
for(int j = 0; j < jsa.length(); j++){
JSONArray endpoint = jsa.getJSONArray(j);
bsrURI = getObjectValueFromJSONArrayEndpointData(endpoint, "bsrURI");
String query = normalizeQuery(QUERY_GET_BSRURI, null, null, null, bsrURI);
JSONArray jsaUriBSR = queryExecutor(query);
/*???
for(i = o; i < 3; i++){
if (ambient.contains("CheckAutonomy")){
}
}
???*/
String ambient = jsaUriBSR.get(0).toString()
.substring( jsaUriBSR.get(0).toString().indexOf('#') + 1, jsaUriBSR.get(0).toString().length() - 2 );
System.out.println(ambient);
}*/
String line = ambient + ";\n";
bw.write(line);
}
}
Solved it with something like this:
for(int i = 0; i < result.length(); i++){
if (risultato.get(i).toString().contains("CheckAutonomy"))
ambient = result.get(i).toString()
.substring( result.get(i).toString().indexOf('#') + 1,
result.get(i).toString().length() - 2 );
}
Nevertheless, thank you for your time ! :P

Copying numbers from an addition series into an array

I'm trying to copy only the numbers from an addition series say 45+45+45
The code works just fine until the moment it encounters the last 45 and all I get displayed are two 45's where I wanted all the three of them.I'd like suggestions for what I haven't done which would give me the exact output.Here's my code
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
String str = "", st;
System.out.println("Enter Number");
st = in.readLine();
int l = st.length();
int c = 0;
String arr[] = new String[20];
for(int i = 0; i < l; i++)
{
char chr = st.charAt(i);
if(chr == '+')
{
arr[c++] = str;
str = "";
}
else
{
str += chr;
}
}
for(int i = 0; i < c; i++)
{
System.out.println(arr[i]);
}
}
Take a look in your code. You are only adding the content into the array after you read an +. As the last '45' number has no remaining + left, it is not added into your array.
If this is not a homework, the best solutions is to use split() as suggested in the comments. In other case, I would recommend you to store the last content of the str when the loop is over. It contains the remaining characters left.
It is an easy code and I am sure that you can figure it out.

Program Overwriting Array with Null

For a project in school (intro to java), we have to make a program using arrays. I decided to make a login program that stores logins. It works perfectly, except when deleting items. This is my code
public void delete() throws FileNotFoundException{
int p;
c.clear();
c.print("Please enter a website to delete it's login info: ");
String delete_name = c.readLine();
Boolean found = false;
// Search for the search key, and display the matching elements
c.println("Searching for " + delete_name + "...");
for (int i = 0; i < pass.length; i++)
if (pass[i][0].equals(delete_name)) {
c.println("Deleting login for " + pass[i][0]);
String new_array[][] = new String[pass.length - 1][3];
//remove an element
for (int w = 0; i < new_array.length; i++)
for (int j = 0; j <= 2; j++) {
p = w;
if (i >= p) {
new_array[w][j] = pass[w + 1][j];
} else {
new_array[w][j] = pass[w][j];
}
}
found = true;
pass = new_array;
}
if (found == false) {
c.println("No luck! " + delete_name + " wasn't found, please try again.");
delete();
}
fileWriter();
}
When it writes to the file, anything after the part that should have been deleted gets changed to "null".
Sorry if the format is awful, I'm just starting with java :) Any help is greatly appreciated, thanks!
When deleting a row of a 2D array in Java, you can use this shortcut (no for-loops needed)
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
//Remove row at index of "delete_name":
for(int i = 0; i < pass.length; i++){
if(pass[i][0].equals(delete_name)){
tempArr.remove(i);
}
}
String[][] new_array = tempArr.toArray(new String[][]{});
However, this solution only works if you are only deleting one object in the List. I would suggest looking into "iterators" to make this solution better.
EDIT:
Here is an example with an iterator
String[][] pass = new String[][]{{"Name","data1","data2"}};
List<String[]> tempArr = new ArrayList<String[]>(Arrays.asList(pass));
for (Iterator<String[]> iterator = tempArr.iterator(); iterator.hasNext();) {
String id = iterator.next()[0];
if (id.equals(delete_name)){
iterator.remove();
}
}

How do I print a 2d array?

My array is:
String[][] name = new String[15][2];
int rowNumber = 0;
My add button is:
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
I do not know what to put in my list button (lists the first name and last name) into my TextArea called outPut.
The Whole Code:
`
public class StudentGradesView extends FrameView {
String[][] name = new String[15][2];
double[][] testMark = new double[15][4];
int rowNumber = 0;
private void btnAddMouseClicked(java.awt.event.MouseEvent evt) {
name[rowNumber][0] = firstName.getText();
name[rowNumber][1] = lastName.getText();
rowNumber ++;
}
private void btnListMouseClicked(java.awt.event.MouseEvent evt) {
String outputStr = "";
for(int i=0; i < rowNumber; i++) {
outputStr += name[rowNumber][0] + " " + name[rowNumber][1] + "\n";
}outPut.setText(outputStr);
}
}`
Okay, I think I get what you want now.
First we take the inputs...
name[numberOfInputs][0] = firstName.getText();
name[numberOfInputs][1] = lastName.getText();
numberOfInputs += 1;
Now you want to output this to a textarea...
String outputStr = "";
for(int i=0; i < numberOfInputs; i++) {
outputStr += name[i][0] + " " + name[i][1] + "\n";
}
Then set your output textarea
outPut.setText(outputStr);
You are getting nulls because you are specifying a static array size but you (probably) are not filling up the array with test cases up to that amount. So you are printing elements of the array that are simply not populated.
Edit: for comments.
String st = "";
for (int i = 0; i < 15; i++)
st += name[i][0] + " " + name[i][1] + "\n";
outPut.setText(value);
This loops over the array and creates a string containing all the full names, separated by a line break.
This then sets the text using outPut.setText(value);
for(String[] s1d : s2d)
for(String s : s1d)
System.out.println(s);
A simple way using for() construct
The easiest way to print any array to any depth is to use Arrays.deepToString():
System.out.println(Arrays.deepToString(array));
try this:
import java.util.Arrays;
.
.
.
String[][] a = { { "john" },
{ "jones" }
};
System.out.println(Arrays.deepToString(a)); //whole string array
System.out.println(Arrays.deepToString(a[0])); //john
System.out.println(Arrays.deepToString(a[1])); //jones

JAVA: Word game query

Hello my fellow programmers!
I have this code so far:
public class Levels {
int cLevel;
public void newGame() {
boolean newGame = true;
if (newGame) {
cLevel = 1;
List<String> list = new ArrayList<String>();
try {
BufferedReader bf = new BufferedReader(new FileReader(
"src/WordGuess/ReadFile/LevelFiles/Level_" + cLevel
+ ".txt"));
String cLine;
while ((cLine = bf.readLine()) != null) {
list.add(cLine);
}
String words[] = new String[list.size()];
words = list.toArray(words);
System.out
.println("These are your help letters so you can beat that level: "
+ words[0]);
for (int i = 1; i < words.length; i++) {
char[] replaceChar = words[i].toCharArray();
for (int x = 0; x < replaceChar.length; x++) {
replaceChar[x] = '*';
}
String replacement = new String(replaceChar);
System.out.println("\f" + replacement);
}
System.out.println("\t Score: " + Score(0) + ";\t Lives: "
+ Lives(5) + ";");
System.out.println("\n Enter Word:");
System.in.read();
} catch (Exception e) {
System.out
.println("Oh! Something went terribly wrong. A team of highly trained and koala-fied koalas have been dispatched to fix the problem. If you dont hear from them please restart this program.");
e.printStackTrace();
}
}
}
private int Lives(int lives) {
int wrongTries = 0;
boolean correctWord;
int counter = 0;
String livesForm[] = new String[lives];
// for (int i = 0; i == lives; i++) {
// livesForm[i] = "♥";
// }
return lives;
}
private int Score(int score) {
return score;
}}
So my query is as follows.
I want to show the lives as the heart symbol and still keep the integer value of it for functioning purposes. So as shown in my code example 5 lives to be represented by 5 hearts but still keep the int lives value of 5. As shown also in my example i also tried with an array of strings the size of the integer value 'lives' and to be replaced by hearts. As far as i ran the code no error was displayed whatsoever so i would assume that the array has been populated but i couldn't figure out how to display the array in the console as "Lives: ♥♥♥♥♥".
I have tried with the regular:
System.out.println(livesForm[i]);
But it did not display anything. I don't know if i have structured my question perfectly clear. I will be glad if any of you fellas can give me an advice or hint. Thank you for spending time on this question!
Why not:
public String getLivesAsString(int lives) {
StringBuilder sb = new StringBuilder(lives);
for(int i = 0; i < lives; i++) {
sb.append("♥");
}
return sb.toString();
}
?
Not sure why you need an array to display an amount of '♥'-symbols defined by an integer?

Categories