I have ArrayList where I put Author, Title and Value(integer). I want to put them in label and print in separate lines. But what I get is that text is printed in one line.
for (Book book : listofbooks) {
labelis.setText(labelis.getText() + "\nName: " + book.getName() + "Tile: " + book.getTitle() + "Number of books: " + book.getHowMany());
}
panel.add(labelis);
Why \n does not work?
EDIT: Solution:
for (Book book : listofbooks) {
label.setText( "<html> "
+ label.getText()
+ "<br>Name: " + book.getName()
+ "Tile: " + book.getTitle()
+ "Number of books: "
+ book.getHowMany()
);
}
label.setText(label.getText()+ "</html>");
You can use HTML tags in your JLabel. Try to seperate your Strings with that break tag: <br>
label.setText("<html> +"
+ label.getText()
+ "<br>Name: " + book.getName()
+ "Tile: " + book.getTitle()
+ "Number of books: "
+ book.getHowMany()
+ "</html>");
NOTE: Your JLabel text has to start with the opening <html> and end with the closing </html>.
Related
I want to get all the message data only. Such that it should look for message and all the data between curly braces of the parent message. With the below code, I am getting service details too along with message which I don't want. Any suggestion on this experts thanks in advance.
String data = "/**\r\n" +
" * file\r\n" +
" */\r\n" +
"syntax = \"proto3\";\r\n" +
"package demo;\r\n" +
"\r\n" +
"import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
"import \"google/api/annotations.proto\";\r\n" +
"import \"google/protobuf/wrappers.proto\";\r\n" +
"import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
"\r\n" +
"option go_package = \"bitbucket.com;\r\n" +
"option java_multiple_files = true;\r\n" +
"\r\n" +
"schemes: HTTPS;\r\n" +
"consumes: \"application/json\";\r\n" +
"produces: \"application/json\";\r\n" +
"responses: {\r\n" +
"key:\r\n" +
" \"404\";\r\n" +
"value: {\r\n" +
"description:\r\n" +
" \"not exist.\";\r\n" +
"schema: {\r\n" +
"json_schema: {\r\n" +
"type:\r\n" +
" STRING;\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"responses: {\r\n" +
"key:\r\n" +
" \"401\";\r\n" +
"value: {\r\n" +
"description:\r\n" +
" \"Wrong user.\";\r\n" +
"schema: {\r\n" +
"json_schema: {\r\n" +
"type:\r\n" +
" STRING;\r\n" +
"};\r\n" +
"example: {\r\n" +
"value:\r\n" +
" '{ \"message\": \"wrong user.\" }'\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"\r\n" +
"message message1 {\r\n" +
" message message2 {\r\n" +
" enum Enum {\r\n" +
" UNKNOWN = 0; \r\n" +
" }\r\n" +
" }\r\n" +
" string id = 1;\r\n" +
" string name = 3;\r\n" +
" string account = 4;\r\n" +
"}\r\n" +
"\r\n" +
"message User{\r\n" +
" string firstName = 1 ;\r\n" +
" string lastName = 2 ;\r\n" +
" string middleName = 3 [(validate.rules).repeated = { min_items: 0 }];\r\n" +
"}\r\n" +
"\r\n" +
"service Userlogin{\r\n" +
" rpc Login(User) returns (APIResponse);\r\n" +
"}";
List<String> allmsg = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));
I am expecting response like below in my array list of string with size 2.
allMsg.get(0) should be
message message1 {
message message2 {
enum Enum {
UNKNOWN = 0;
}
}
string id = 1;
string name = 3;
string account = 4;
}
allMsg.get(1) should be
message User{
string firstName = 1 ;
string lastName = 2 ;
string middleName = 3 [(validate.rules).repeated = { min_items: 0 }];
}
Use a Pattern that matches a "message" and stream the match results to a List:
List<String> allmsg = Pattern.compile("(?ms)^message.*?^}")
.matcher(data)
.results() // stream the MatchResults
.map(MatchResult::group) // get the entire match
.collect(toList()); // collect as a List
See live code demo.
Regex breakdown:
(?ms) turns on flags s, which makes dot also match newlines, and m, which makes ^ and $ match start and end of each line
^message matches start of a line (not start of input, thanks to the m flag) then "message"
.*? reluctantly (ie as little as possible) matches any characters (including newlines, thanks to the s flag). Adding the ? to make the quantifier reluctant stops the match from consuming multiple "messages".
^} matches start of a line (not start of input, thanks to the m flag) then "}"
See live regex demo.
This will work even if "messages" are not contiguous with each other, ie they may be interspersed with other constructs (your example doesn't have this situation, but the linked demos do).
You should see you other question.
Pattern.compile("(?s)^message(.(?!message|service))*");
If message can appear after message
"message message1 {\r\n" +
You must adapt the regex.
I was not sure how to formulate the title however I have the following problem. I'm making a program which reads out things out of a CSV file and types it out. In a file where there are no problem I get my results normally. When I run my other file which has errors thrown my program still prints out the things I have in catch but not in a order I want it to- I want to put all parts with errors throw on top and the ones which have no errors on the bottom of the print. How can i do that?
This is the code I currently have
String []arrayS = line.split(",");
if(arrayS.length==7){
String fName = "";
String lName = "";
//String
int bDay;
int bMonth;
int bYear;
int weight;
double height;
try{
//System.out.printf("%15s%15s%15s%15s \n", fnlName , birthDate, sWeight, sHeight);
fName = arrayS[0];//gets first line in csv- name
lName = arrayS[1];//gets second line in csv- last name
try{
bDay = Integer.parseInt(arrayS[2].trim());//gets third line in csv- birth day
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Birth day");
continue;
}try{
bMonth = Integer.parseInt(arrayS[3].trim());//gets four line in csv- birth month
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Birth month");
continue;
}try{
bYear = Integer.parseInt(arrayS[4].trim());//gets fifth line in csv- birth year
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Birth year");
continue;
}try{
weight = Integer.parseInt( arrayS[5].trim());//gets sixth line in csv- weight
}catch (NumberFormatException nfe){
System.err.println("Error found in" +arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Weight");
continue;
}try{
height = Double.parseDouble(arrayS[6].trim());//gets seventh line in csv- height
}catch (NumberFormatException nfe){
System.err.println("Error found in" + arrayS[0] + ", " + arrayS[1] + ", " + arrayS[2] + ", " + arrayS[3] + ", " + arrayS[4] + ", " + arrayS[5] + ", " + arrayS[6] +"\n Offending item is: Height");
continue;
}
System.out.printf("%15s%15s%02d/%02d/%4d %d %.1f\n" , fName , lName , bDay , bMonth , bYear , weight , height);
}catch(NumberFormatException nfe ){
System.out.println("Cannot read student:" + fName);
continue;
}}```
Do not write the output directly to System.out and System.err but instead collect them first. You can use different approaches like using a List<String> or use a StringBuilder. When you have read the CSV file completely you can finally output the result you have collected at the end, first the errors and then the error-free entries. The code can look like this:
List<String> errors = new ArrayList<String>();
List<String> output = new ArrayList<String>();
while (/*reading a line */) {
/* [...] */
try {
/* [...] */
output.add(String.format("...", a, b, c, d, ...);
} catch (...) {
errors.add(...);
}
}
// now show the result, but show the errors first
if (!errors.isEmpty()) {
System.err.println("There were errors:");
for (String str: errors) {
System.err.println(str);
}
}
System.out.println("Your result");
for (String str: output) {
System.out.println(str);
}
I am trying to drag & drop 2 elements into my workspace but they are dropped over each other, how can i specify the position of dropping the elements?
I am using dragAndDrop() function
Actions act=new Actions(driver);
act.dragAndDrop(From, To).build().perform();
enter image description here
Using dragAndDrop() method you can perform drag and drop operations on only one location at a time. it is usually used to perform operations on web element which is capable of dropping. please find the reference http://demoqa.com/droppable/ for various types of dropable elements.
To implement drag and drop operation -
Example:
WebElement From=driver.findElement(By.xpath( <<source xpath>> ));
WebElement To=driver.findElement(By.xpath( <<destination xpath>> ));
Actions actions=new Actions(driver);
actions.dragAndDrop(From, To).build().perform();
to drag and drop another element, you need to perform above all steps again.
Hope this helps :)
Try Using below code :
public static void dragAndDropViaJQueryHelper(WebDriver driver, String dragSourceJQuerySelector, String dropTargetJQuerySelector) {
String jqueryScript = "(function( jquery ) {\r\n" +
" jquery.fn.simulateDragDrop = function(options) {\r\n" +
" return this.each(function() {\r\n" +
" new jquery.simulateDragDrop(this, options);\r\n" +
" });\r\n" +
" };\r\n" +
" jquery.simulateDragDrop = function(elem, options) {\r\n" +
" this.options = options;\r\n" +
" this.simulateEvent(elem, options);\r\n" +
" };\r\n" +
" jquery.extend(jquery.simulateDragDrop.prototype, {\r\n" +
" simulateEvent: function(elem, options) {\r\n" +
" /*Simulating drag start*/\r\n" +
" var type = 'dragstart';\r\n" +
" var event = this.createEvent(type);\r\n" +
" this.dispatchEvent(elem, type, event);\r\n" +
"\r\n" +
" /*Simulating drop*/\r\n" +
" type = 'drop';\r\n" +
" var dropEvent = this.createEvent(type, {});\r\n" +
" dropEvent.dataTransfer = event.dataTransfer;\r\n" +
" this.dispatchEvent(jquery(options.dropTarget)[0], type, dropEvent);\r\n" +
"\r\n" +
" /*Simulating drag end*/\r\n" +
" type = 'dragend';\r\n" +
" var dragEndEvent = this.createEvent(type, {});\r\n" +
" dragEndEvent.dataTransfer = event.dataTransfer;\r\n" +
" this.dispatchEvent(elem, type, dragEndEvent);\r\n" +
" },\r\n" +
" createEvent: function(type) {\r\n" +
" var event = document.createEvent(\"CustomEvent\");\r\n" +
" event.initCustomEvent(type, true, true, null);\r\n" +
" event.dataTransfer = {\r\n" +
" data: {\r\n" +
" },\r\n" +
" setData: function(type, val){\r\n" +
" this.data[type] = val;\r\n" +
" },\r\n" +
" getData: function(type){\r\n" +
" return this.data[type];\r\n" +
" }\r\n" +
" };\r\n" +
" return event;\r\n" +
" },\r\n" +
" dispatchEvent: function(elem, type, event) {\r\n" +
" if(elem.dispatchEvent) {\r\n" +
" elem.dispatchEvent(event);\r\n" +
" }else if( elem.fireEvent ) {\r\n" +
" elem.fireEvent(\"on\"+type, event);\r\n" +
" }\r\n" +
" }\r\n" +
" });\r\n" +
"})(jQuery);";
((JavascriptExecutor) driver).executeScript(jqueryScript);
String dragAndDropScript = "jQuery('" + dragSourceJQuerySelector + "').simulateDragDrop({ dropTarget: '" + dropTargetJQuerySelector + "'});";
((JavascriptExecutor) driver).executeScript(dragAndDropScript);
}
Just pass css or xpath selectors in parameters.
Hope that helps you.
If that does not help you I can help you out with some other solutions also.
I want customize a string with results that will be written in a TextView but not works. I just want color some part of text using html tags but it's still all text with same color. This is what i wrote so far:
#Override
public String toString() {
return (Html.fromHtml("<font color=\"#e61624\">"+fromHour+"</font>")) + " " + from + " / " + toHour + " " + to;
}
Thanks
I wouldn't use Html.fromHtml inside the toString() method.
In toString(), simply return the corresponding text:
return "<font color=\"#e61624\">"+fromHour+"</font> " + from + " / " + toHour + " " + to;
Then call:
textView.setText(Html.fromHtml(yourObject.toString());
// Try this way,hope this will help you to solve your problem.
yourTextView.setText(Html.fromHtml("<font color=\"#e61624\">"+fromHour+"</font> " + from + " / " + toHour + " " + to));
String text = "<font color=\"#e61624\">"+"<small>" + "Hello"
+ "</small>"+"</font>";
Html.fromHtml(text);
My assignment calls for the line number to be display with the output. The professor suggested I do it with a counter and as seeing Java doesn't have an easy way to print out the current line number, I just created a counter as suggested. The below code is as follows:
//Count Increment
for (count = 1; count<= 5; count++)
{
}
//Display information
System.out.println(count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(count + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(count + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(count + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(count + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyvalue);
However, the output starts the line counter at six as demonstrated here:
6. Street: park avenue #44
6. Total Rooms: 5
6. Total Area: 2500.0 sq.ft
6. The price per Sq. Ft is $120.4
6. The estimated property value is $301000.0
Removing the brackets doesn't help either. How can I get the line count to correctly state 1,2,3,4,5?
Please ask for clarification if needed!! Thanks.
Your prints are outside of the for loop. Your for loop ends when the counter is "6" which is when it exits the for loop. This variable doesn't change so the current value is "6",that is why it always prints "6" below on your code. If you want to print the line number for each instruction you could do something like this:
count = 0;
System.out.println(++count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
"++count", you increment the variable the moment you write a line, in the first case it should print 1 then 2 etc. Hope this helped :)
The loop is not required cause you are only counting the lines one time each. If you put those lines in a loop that goes from 0 to 5 you will be counting each line 5 times. Since you only need to count each line ONE time you dont need the loop and just the simple increment I previously mentioned. Hope this clears out why the loop is not required
I assume that you have somewhere above this a line defining count:
int count;
So after the for loop, you've incremented count to 6 and then started printing with count left at the last incremented value from the for loop.
So, remove the for loop and just pre-increment the count variable for each line of ouput.
int count = 0;
//Display information
System.out.println( (++count) + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
...
class Print{
static int lineno = 0;
private int static getLineNo(){
lineno = lineno + 1;
return lineno;
}
}
//Display information
System.out.println(Print.getLineNo() + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(Print.getLineNo() + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(Print.getLineNo() + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(Print.getLineNo() + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(Print.getLineNo() + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyv