How do I format text within a JList? - java

I have items in a JList that I can't get to format correctly.
I've created this method in order to do so:
private String formatString(String string){
string = string.trim();
int SEPERATOR = 20 - string.length();
for(int i = 0; i<SEPERATOR; i++){
string = string + " ";
}
return string;
}
When I output the items in my JList into the output window using a system out print it formats fine, but in my GUI it does not:
I'm not sure if this will help you help me better but here is how I am loading my data into the list:
DefaultListModel m = new DefaultListModel();
while (rs.next()){
String Expense = rs.getString("Expense");
String Cost = "£"+rs.getString("Cost");
String PurchaseDate = rs.getString("Purchase_Date");
String Description = rs.getString("Description");
Expense = formatString(Expense);
Cost = formatString(Cost);
PurchaseDate = formatString(PurchaseDate);
Description = formatString(Description);
String Row = Expense+Cost+PurchaseDate+Description;
m.addElement(Row);
System.out.println(Row);
}

The best solution, as has already been suggested, is to use a JTable. Read the section from the Swing tutorial on How to Use Tables for more information and working examples.
When i output the items in my jlist into the output window using a system out print it formats fine, but in my GUI it does not:
To answer your question you need to use a monospaced font.
list.setFont( new Font("monospaced", Font.PLAIN, 10) );
Also, use standard Java variable names. Variable name (Expense, Cost...) should NOT start with an upper case character.

You can use \t (you might have to use /t/t if the the text of a field is too long) instead of using spaces OR use a JTable

Related

Dealing with long Strings & TextView behavior

I’m developing an android app that gets objects from a server and shows them in a simple list.
I’m trying to figure out how to deal with long object’s titles :
Every title populates a designated multi-line TextView.
If a title is longer than 16 characters, it messes with my desired UI.
There are two scenarios I need to solve -
1). If the title is longer than 16 characters & contains more than one word, I need to split the words into different lines (I tried to .split("") and .trim(), but I don’t want to use another view, just break a line in the same one, and the use in ("") seems unreliable to me).
2). If the title is longer than 16 characters and contains only one long word, I only need to change font size specifically.
Any ideas for a good and reliable solution?
Thanks a lot in advance.
use SpannableString for a single view
For title:
SpannableString titleSpan = new SpannableString("title String");
titleSpan.setSpan(new RelativeSizeSpan(1.3f), 0, titleSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
for Message
SpannableString messageSpan = new SpannableString("Message String");
messageSpan.setSpan(new RelativeSizeSpan(1.0f), 0, messageSpan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
set in TextView
tvTermsPolicyHeading.setText(TextUtils.concat(titleSpan, messageSpan));
Code like below it will work as you need
String title; //your title
//find length of your title
int length = title.length();
if (length>16){
string[] titles = myString.split("\\s+");
int size = titles.length;
if (size < 2){
yourTextview.setText(title);
// reduce the text size of your textview
}else {
String newTitle= "";
for (int i=0;i<titles.length;i++){
newTitle = titles[i]+"\n"
}
yourTextview.setText(newTitle);
}
}
You can split and then concatenate the words using "\n" if there are more than one words.
In case of long word
You can see this question here
Auto-fit TextView for Android
try this:
if(title.split(" ").size > 1){
String line1 = title.substring(0, 16);
int end = line1.lastIndexOf(" ");
titleTextView.setText(title.substring(0,end) + "\n" +
title.substring(end+1,title.size-1);
}else{
titleTextView.setText(title);
titleTextView.setTextSize(yourTextSize);
}
this code should work perfectly for your case.

Separate Multiple Integers from a String

I've got a question about making a save function.
I'm trying to have a string be saved as a single file to set specific settings on a game. So saveFile would read "002007...", having 002 be a player's location, then 007 a player's level, for example.
I understand how to compile the various variables into a single string, but how would I return it to individual variables?
You better go with SQLite or SharedPreferences if you really want to save settings for a game on Android.
On the other hand, if you have to stick with saving a String on a file, you might want to use a delimiter(ie \r\n or # or | would do it) between numbers. So while parsing back delimiters will help you a lot, but beware when things get complicated a single String won't do the thing nicely. Then you might want to use JSON (for simplicity I would prefer gson) to encode your settings into one String and vice verse.
You could use a delimiter between the values like this:
int location = 02;
int level = 3;
int powerUps = 46;
... and so on
String saveString = location + "#" + level + "#" + powerUps + "#" + ...
Then to load the String back into variables:
String[] values = saveString.split("#");
location = values[0];
level = values[1];
powerUps = values[2];
... and so on
My advice is to check out Shared Preferences and you can read Android's documentation on it here.
If you did want to use your single String, file method, I suggest using delimiters. That simply means to put commas, or other types of delimeters in between different integer values. Instead of "002007", save it as "002,007". Example:
String s = "002,007"
String[] values = s.split(","); // values[0] is "002" and values[1] is "007"
Using the .split(String) command will return a String array with each element in the array containing parts of the String that was split up by the parameter, in this case: ,
If you wanted to separate values per person, something like this could be done:
String s = "002,007;003,008";
String[] people = s.split(";"); // people[0] is "002,007", people[1] is "003,004"
String[][] person = new String[people.length][people[0].split(",").length];
for (int i = 0; i < people.length; i++)
{
person[i] = people[i].split(",");
}
Here is what the array would then contain:
person[0][0] is "002"person[0][1] is "007" person[1][0] is "003" person[1][1] is "008"
// print it for your own testing
for (String ppl[] : person)
{
for (String val : ppl)
{
System.out.print(val + " ");
}
System.out.println("");
}

String Array: Displaying Results

I was thinking that I could take in the user inputs which I get from the two AutoCompleteTextView and show it in as a result for which there is a TableLayout.
The two inputs that the AutoCompleteTextView takes is My Location and Destination from the users. The complexity comes from the type of input that the AutoCompleteTextView generates. The AutoCompleteTextView uses the PlacesAutoComplete from Google, therefore I am working with an inputs like Jamal, Kathmandu, Central Region, Nepal and maybe Kalanki, Kathmandu, Central Region, Nepal. What I would want the TableLayout to reflect is Results: From ... To ...
My question is how can I just take in the first part of the string in Jamal, Kathmandu, Central Region, Nepal which is just Jamal for the TableLayout to display a the results like Results: From Jamal to Kalanki. Being very new to android I sort of have a vague idea, the code that I tried looks like this.
String[] from;
String[] to;
//pulling the auto complete text view
from = location.getString().toText();
to = destination.getString().toText();
//referencing the text view inside the table layout
results.setText(new StringBuilder().append("Results from"+from[0]).append(" to"+to[0]));
This code obviously does not work as it prompts me to change from to a String. I really do not know what is going on. Please help ?
Do this:
String[] from = new String[]{location.getString().toText()};
String[] to = new String[]{destination.getString().toText()};
results.setText(new StringBuilder().append("Results from"+from[0]).append(" to"+to[0]));
Or
String from;
String to;
from = location.getString().toText();
to = destination.getString().toText();
results.setText(new StringBuilder().append("Results from"+from).append(" to"+to));
Hope its help.
You're assigning a String to a String[]. That will not work.
from = location.getString().toText();
Assign them to a String and execute this.
results.setText(new StringBuilder().append("Results from"+from).append(" to"+to));
You cannot assign String to String[] (String and String array are not the same!)
Use them as a String:
String from = location.getString().toText();
results.setText(new StringBuilder().append("Results from"+from).append(" to"+to));
String from_split = location.getText().toString();
String to_split = destination.getText().toString();
if(from_split.contains(","))
{
from = from_split.split(",");
}
else
{
from = from_split.split(" ");
}
if(to_split.contains(","))
{
to = to_split.split(",");
}
else
{
to = to_split.split(" ");
}
results.setText(new StringBuffer().append(from[0]).append(" to "+to[0]));
I guess I found the answer to displaying the result the way I wanted to.

Trying to update the content of a JLabel

I'm back again with a simpler question! I'd like the content of this JLabel (triedLettersLA) to update periodically throughout the application (I have that part handled).
But I'd like to ADD text to the label. NOT rewrite it entirely. For example.. If the text said "Letters Tried: ", I'd want to add "N", and "X", and then "H" on three separate occasions. So at the end, it'd look like this "Letters Tried: N X H". Here's what I have, and it's totally not working..
This is way up top,
JLabel triedLettersLA = new JLabel("Tried letters:");
public boolean used[] = new boolean[26];
And this is lower down in my code..
StringBuffer missedLetter = new StringBuffer();
for (int le = 0; le <= 25; le++) {
if (used[le]) missedLetter.append((char)(le + 'a'));
String triedLettersLA.getText(t);
triedLettersLA.setText(t + " " + missedLetter.toString());
}
The code you posted makes no sense (nor could it ever compile). Well, it would compile now, possibly.
That being said, a String in Java is immutable; you can't change it. To change the text of a JLabel you need to create a new String and call the JLabel's setText() method.
String old = triedLettersLA.getText();
String newString = old + " N"; // this creates a new String object
triedLettersLA.setText(newString);
Nonsence code:
String triedLettersLA.getText(t);
Change it to:
String t = triedLettersLA.getText();

Java Map Matching Key

i am facing a problem which is:
I have map containing string and string. When i print that map i can see that there is a key
"0-8166-3835-7". But when i am trying to get it, there is nothing to get returned, like no matching found...
My code:
//Open a stream to read from file with isbn's AND titles
Scanner IsbnTitle = new Scanner(new FileReader("C:/Users/Proskopos/Documents/NetBeansProjects/ReadUrl/IsbnTitle.txt"));
//Create a Map to save both ISBN's and Titles
Map <String,String> IsbnTitleMap = new HashMap();
while(IsbnTitle.hasNext()){
String recordIsbnTitle = IsbnTitle.nextLine();
UrlFunctions.AddToMap(Recognised , recordIsbnTitle, IsbnTitleMap);
}
.....
.....
Set IsbnSet = new HashSet();
while (IsbnFile.hasNextLine()) {
String isbn = IsbnFile.nextLine();
IsbnSet.add(isbn);
}
//Create an Iterator for IsbnSet
Iterator IsbnIt =IsbnSet.iterator();
String suffix = IsbnIt.next().toString();
String OPACIALtitle = UrlFunctions.GetOpacTitle(suffix, IsbnTitleMap);
The code above is the only part in main about MAP and below are the functions i call:
static String GetOpacTitle(String opIsbn, Map IsbnTitle) {
String OpacTitle = null;
String isbn = opIsbn;
Map isbnMap = IsbnTitle;
System.out.println(isbn);
if ( isbnMap.containsKey(isbn)){
System.out.println("AAAAAAAAAAAAAAAA");
}
//String tade = isbnMap.get(isbn).toString();
//System.out.println("*************" + tade);
return OpacTitle;
}
static void AddToMap(int Recognise, String recordIsbnfollowed, Map IsbnfollowedMap) {
Map isbnsth = IsbnfollowedMap;
String records = recordIsbnfollowed;
int recs= Recognise;
if (recs == 0 || recs == 3) {
String isbn = records.substring(0, 10);
String title = records.substring(10);
isbnsth.put(isbn, title);
// System.out.println(isbn);
}else if (recs == 1) {
String isbn = records.substring(0, 14);
String title = records.substring(14);
isbnsth.put(isbn, title);
// System.out.println(isbn);
}
}
I cant understand where the problem is.. Maybe it is something like encoding of the suffix cames from a set, and the key from a map? they are both string.. dont think so..!!!
So? Can you help?
EDIT: I am trully sorry if you find the code difficult to read :\ I will follow your advices!!
BUT in case that anyone else has the same problem the solution was what Brand said below.. (I re-post it)
You probably have some whitespace in the Strings that you are reading form the file and storing in the Map. If this is the case use String.trim() before storing the value in the Map, and also before querying for the same string. – Brad 3 hours ago
Thank you all
Just to add to my comment that identified the problem. When comparing Keys in a Map you must be very careful about white space and case sensitivity. These types of issues commonly occure when reading data from Files because it's not always obvious what characters are being read. Even looking in your debugger whitepsace cna be an issue.
Always try to "normalize" your data by trimming leading and trailing whitespace before storing it in a Map.

Categories