JAVA How to align text in JTextArea regardless of length of characters - java

Here is a picture of my JTextArea:
Here is my code:
String display = "";
display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);
What should I do so that the texts are aligned properly regardless of the length of characters of the words?
As much as possible I want to use JTextArea not JTable (since I'm not familiar with it yet)
Thank you in advanced!

Use a JTextPane instead of JTextArea, as that can do HTML. Then add an HTML <table>. Probably with some styles.
StringBuilder display = new StringBuilder("<html><table>");
display.append("<tr><td align='right'>").append(num)
.append("</td><td>").append(name)
.append("</td><td align='right'>").append(stocks)
.append("</td><td>").append(req)
.append("</td></tr>");
display.append("</table>");
txtPane.setText(display.toString());
This allows proportional fonts and styled text like bold, red, background colors.

As mentioned by #AndyTurner above your best approach is to rely on the String formatter to set the character width of each variable to print with also the ability to right or left justified. So in your case, as you left justified everything it could be something like that:
txtArea.setText(String.format("%-3s%-20s%-5s%-5s%n", num, name, stocks, req));
In this example I allocated 3 characters for num, 20 for name and 5 for stocks and req.
More details here

I want to use JTextArea not JTable (since I'm not familiar with it yet)
Well, now is the time to become familiar with a JTable. Use the proper component for the job, that is why multiple components exist. Don't try to fit a square peg in a round hole.
A JTextArea is not the appropriate component for that kind of formatting.
Instead you should be using a JTable. A JTable is designed to display data in a row/column format. Check out the section from the Swing tutorial on How to Use Tables for more information and working examples.
If you must use a text component then use a JTextPane. You can manually set the value of a tab so all the text is aligned. The problem with this approach is again you need to determine what the size of each tab should be. So this means either you make a random guess at the size of each column or you iterate through all the data to determine the size. Of course this complicates the code. See: Java Setting Indent Size on JTextPane for an example.
Again, the better solution is to learn to use Swing how it was designed to be used.

String display = "";
// just add values accordingly the best way to get the result you
// want is to mess around with formatting until you have the values
// where you want them in the textfield.
display = String.format("%20s %10s%n", value1, value2);
//display = display + num + "\t\t" + name + "\t\t\t\t\t\t\t\t" +
// stocks + "\t\t\t" + req +"\n";
txtArea.setText(display);

Related

java spacing when writing to a file

just a beginner in java doing a simple reading file processing some data and writing to a file, however whenever I print to a file I get this inconsistent spacing such as shown below. Especially the zeros are throwing me off. Right now I am padding the strings with empty spaces but I am sure there are better suggestions out there to have consistent spacing between strings in a file. Thanks for the help. I have attached a picture of the inconsistent printing, especially the zeros.
In Apache Commons StringUtils library there are convenient methods to set the proper pad - e.g. rightPad seems to be useful in your case - you could make something like
String row = StringUtils.rightPad(firstValue, lengthOfTheLongestValueInColumn1 + definedColumnMargin) + StringUtils.rightPad(secondValue, lengthOfTheLongestValueInColumn2 + definedColumnMargin) // + ... etc
If these lengthOfTheLongestValueInColumn variables would be calculated dynamically then it would work perfectly but you could also just hardcode some reasonable value (if you know that no value will be longer than, let say, 20 it could have value of 20)
I think best option will be to use String format
return String.format("%1$" + length + "s", inputString)
where length is max size of your digit
you can read more here

Can a JFormattedTextField be assigned a formatter which has placeholders

I've used the following line of code to only allow users to enter digits inside a JFormattedTextField which collects information on time
final JFormattedTextField periodTextField = new JFormattedTextField();
periodTextField.setFormatterFactory(new DefaultFormatterFactory(createFormatter("##:## - ##:##")));
When running my application the text field will appear as ": - :" by default, but I would like it to appear as "00:00 - 00:00" as default, and editing the text field will only change the values of the 0's nothing else. I've looked at this guide for help on using formatters in java, but it doesn't mention how you can set default values. Is there a simple way to achieve what I need.

Changing a String of Text and Numbers into Just Numbers

I'm currently using the OCR tools in Sikuli API to find a transaction ID from the following screen:
It finds the text and returns the following after a little bit of cleanup:
My question is...How would one best replace the letter characters generated from the OCR with proper Numbers? From what I can see, its fairly consistent with how it deciphers the letters. For example, a '0' usually ends up '1J', a '6' turns into a 'b', and a '7' turns into a 'T'.
For those that are interested, I'll post the code I used to get the OCR to work as most correspondences about this are more then 2 years old.
1) Import your Sikuli libraries into your java project
2) At the top of your class, set the settings to TRUE
3) Setup you image to anchor off of and do a variation of the following code.
Thanks in advance for any help!
I use the same solution as #zerotres proposed myself and meanwhile didn't find anything better. Just few more points to consider that might improve the detection quality:
Option 1:
Make sure that the region enclosing the text doesn't include any unrelated areas, for example the frame around the text (as it appears in the question), etc...
Sometimes it will help moving the region slightly around the area of interest.
In both cases using region.highlight(seconds) can be helpful to determine what exactly is being covered by the region.
Option 2:
Sometimes, the detected text is unsalvageable and character replacement won't work. In such cases, a different approach might be considered. If you have some static visual pattern near the region of interest, you can use it as a pivot to locate the area of the text. Then, if the text that you are trying to scrape is clickable, you can just select the text (with double click for example) and then read it form the clipboard. That will result in 100% correct outcome.
Figured out a solutions for this...
String transactionId = "1lJ1BT0357317IJ253 ";
System.out.println("Before Conversion: " + transactionId);
transactionId = transactionId.replace("lJ","0");
transactionId = transactionId.replace("IJ","0");
transactionId = transactionId.replace("B","8");
transactionId = transactionId.replace("T","7");
transactionId = transactionId.replace(" ","");
System.out.println("After Conversion: " + transactionId);
Seems to get the job done for me...Hope this helps others.

JFrame Form add from JTextField to JList

I'm trying to make a contact field where you can type in a first name and a last name in two separate text fields and click the "Add" button I created to send it to the list, but I'm unsure of how to do this exactly, being new to jFrame. I was using something in a tutorial that was similar to this using floats (which is shown below), only because I wasn't sure how to use the "String" variation, however this only seems to work when the "setText" command is set on another text field and won't work on a jList.
float num1, num2, result;
num1 = Float.parseFloat(textFieldFirstName.getText());
num2 = Float.parseFloat(textFieldLastName.getText());
result = num1+num2;
listFieldContact.setText(String.valueOf(result));
Are there any ideas or even good resources out there for jFrame? I've looked in a lot of places but they never quite seem to have exactly the information I need.
this only seems to work when the "setText" command is set on another text field and won't work on a jList.
A JList doesn't have a setText(...) method. You need to update the ListModel.
Read the section from the Swing tutorial on How to Use Lists for a working example that does almost exactly what you want.
The example uses a single text field by you should easily be able to get it to work with two text fields.
Try:
String fname = textFieldFirstName.getText();
String lname = textFieldLastName.getText();
listFieldContact = fname + " " + lname;
You don't need float conversion, as MadProgrammer pointed out. You do need a space between first and last name. Maybe you want lname + ", " + fname in other circumstances.
I think to make the values available in the JList it is not necessary to use Float for string operation. We can do it like this :
Vector<String> nameVector = new Vector<>();
JList<String> nameList = new JList<>();
public void addText() {
nameVector.add(firstNameTF.getText()+lastNameTF.getText());
nameList.setListData(nameVector);
}
I think this piece of code will help you to solve your query.

cleanly lining up output

I have a text file that contains data that was saved using the cvs encryption and I want to open it in java and display it lined up perfectly. I have come to the point of reading it from the text file but now I want it to be split at the commas and now I want to display it all perfectly aligned.
Last, First, car year, car model
barry, john, 1956, chevy impala
and I want it to display like this:
last First car year car model
barry john 1956 chevy impala
and I am just using the scanner class to get the data from the text file.
Determine the max lengths of the column values (including column headers), then create a format String and use that format string to build the aligned rows:
// some easy magic first
String[][] values = getCsvValues(file);
int[] maxLengths = determineMaxLengths(values);
// create formatstring, something like "%10s %5s %10s %n"
StringBuilder formatBuilder = new StringBuilder();
for (int maxLength:maxLengths)
formatBuilder.append("%").append(maxLength).append("s ");
formatBuilder.append("%n"); // newline
// output
for (String[] row:values)
System.out.printf(formatBuilder.toString, row);
depending on how certain you need to be that it all lines up, you might have to go through and find the longest string for each column, but I would use tabs: "\t". Two or three between columns usually works for me, for simple debugging that's what I use.
If you're really serious about it being right all the way down, try looking at Formatters and printf.

Categories

Resources