Prompt Text With JTextPane - jtextfield

I am using JtextPane as a JTextField to make use of Html for styling..but I cant implement prompt text functionality..here is my code...
JTextPane txtNm = new JTextPane();
txtNm.setContentType("text/html");
txtNm.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
if(txtNm.getText().equals("<html><font face='Tw Cen MT' size='4' color='GRAY'> NAME</font><font color='red'> *</font></html>")){
txtNm.setText("");
//System.out.println("in txtnmfocus");
txtNm.setForeground(Color.decode("#003366"));
}
}
#Override
public void focusLost(FocusEvent e) {
if(txtNm.getText().isEmpty()){
txtNm.setText("<html><font face='Tw Cen MT' size='4' color='GRAY'> NAME</font><font color='red'> *</font></html>");
}
}
});

txtNm.getText().isEmpty()
Is never empty. For HTMLEditorKit it returns at least <html><body></body></html> so is never empty.
Check what is really returned in both cases. You can try to analyse txtNm.getDocument().getLength() checking whether it's empty or not

Text returned by getText() should be treated with an HTML parser like Jsoup. This is because...
"<html><body></body></html>"
...and...
"<html>
<body>
</body>
</html>"
...for instance, correspond both to what you would call an "empty string". Though, the string aren't equal to each-other.

Related

How do I print the content of a TextArea?

So currently I'm trying to make a print feature for my Notepad application. I already have a kind of working Print feature, but it prints the full TextArea not only the string that is written into it.
I already tried to make it just print a string, but the PrintJob is not able to handle it, because it needs the actual TextArea, where the Text is written into.
My current Print Stuff:
public void doPrint() {
String toPrint = writeArea.getText();
printSetup(writeArea, Main.primaryStage);
}
private final Label jobStatus = new Label();
private void printSetup(Node node, Stage owner)
{
// Create the PrinterJob
PrinterJob job = PrinterJob.createPrinterJob();
if (job == null)
{
return;
}
// Show the print setup dialog
boolean proceed = job.showPrintDialog(owner);
if (proceed)
{
print(job, node);
}
}
private void print(PrinterJob job, Node node)
{
// Set the Job Status Message
jobStatus.textProperty().bind(job.jobStatusProperty().asString());
// Print the node
boolean printed = job.printPage(node);
if (printed)
{
job.endJob();
}
}
What I want to have:
A print that only shows the String, just like any other notepad application does if you try to print something
What I currently get:
The full textarea with frame.
As I mentioned in the comment you can wrap it into a Text, but then the first line for some reason isn't displayed correctly.
The solution would be to use a Label instead like:
printSetup(new Label(toPrint), Main.primaryStage);

JavaFX KeyCode for percent (%)

I want to detect when certain keys are pressed. I can't seem to find a KeyCode for the percent (%) sign. I have scoured the JavaFX 8 JavaDoc, and there is no Enum constant for PERCENTlike I would expect. Google was not helpful either. Is there something special about % that I don't know about?
#FXML
private void keyPressed(KeyEvent evt) {
if (evt.getCode().isDigitKey() && !evt.isShiftDown()) {
String number = evt.getText();
numberAction(number);
}
if (evt.getCode().equals(KeyCode.DECIMAL)) {
decimalAction();
}
if (evt.getCode().equals(KeyCode.PERCENT)) {
percentAction();
}
}
The Enum KeyCode.PERCENT does not exist.
Rather than using the keyPressed event, use the keyTyped event and use KeyEvent.getCharacter to get the result independent from keyboard layout:
#FXML
private void keyTyped(KeyEvent evt) {
...
if ("%".equals(evt.getCharacter())) {
percentAction();
}
}
(You need to modify your fxml file of course.)
Did u try this?
YOUR_CONTROLLER.setOnKeyPressed(event ->{
if((event.getCode() == KeyCode.DIGIT5) && event.isShiftDown())
System.out.println("It's work");
});
And yes, u can't find KeyCode for this symbol because to write it you should to press more then 1 key (:
UPDATE:
You also can try this:
YOUR_CONTROLLER.setOnKeyPressed(event ->{
if((event.getText().equals("%"))
System.out.println("It's work");
});

how to get text from textview using espresso

I want get text string shown in a textview in LinearLayout. can espresso do that? If not, is there other way to do that or can I use android api in espresso test case? I am using API 17 18 or newer, espresso 1.1(It should be the latest one.). I have no clue about this. Thanks.
The basic idea is to use a method with an internal ViewAction that retrieves the text in its perform method. Anonymous classes can only access final fields, so we cannot just let it set a local variable of getText(), but instead an array of String is used to get the string out of the ViewAction.
String getText(final Matcher<View> matcher) {
final String[] stringHolder = { null };
onView(matcher).perform(new ViewAction() {
#Override
public Matcher<View> getConstraints() {
return isAssignableFrom(TextView.class);
}
#Override
public String getDescription() {
return "getting text from a TextView";
}
#Override
public void perform(UiController uiController, View view) {
TextView tv = (TextView)view; //Save, because of check in getConstraints()
stringHolder[0] = tv.getText().toString();
}
});
return stringHolder[0];
}
Note: This kind of view data retrievers should be used with care. If you are constantly finding yourself writing this kind of methods, there is a good chance, you're doing something wrong from the get go. Also don't ever access the View outside of a ViewAssertion or ViewAction, because only there it is made sure, that interaction is safe, as it is run from UI thread, and before execution it is checked, that no other interactions meddle.
If you want to check text value with another text, you can create Matcher. You can see my code to create your own method:
public static Matcher<View> checkConversion(final float value){
return new TypeSafeMatcher<View>() {
#Override
protected boolean matchesSafely(View item) {
if(!(item instanceof TextView)) return false;
float convertedValue = Float.valueOf(((TextView) item).getText().toString());
float delta = Math.abs(convertedValue - value);
return delta < 0.005f;
}
#Override
public void describeTo(Description description) {
description.appendText("Value expected is wrong");
}
};
}

HtmlGenericControl("br") rendering twice

I'm adding some content to a given web page from code behind. When I want to add a break after some text, I try to do that this way:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(New HtmlGenericControl("br"))
,where pDoc is the Panel in which I'm adding the content. But it adds two br tags into the final HTML.
I've avoid this behaviour this way:
pDoc.Controls.Add(New Label With {.Text = "whatever" & "<br />"})
Anyway, I'm so curious and I want to know why
pDoc.Controls.Add(New HtmlGenericControl("br"))
is acting that way. I also think my approach is not too fancy.
Regards,
Actually you can use;
pDoc.Controls.Add(new LiteralControl("<br/>"));
Whereas new HtmlGenericControl("br") adds two <br>, this will only add <br/> tag to your HTML so that you just have 1 space line.
In this picture I added those breaks with that code block.
Also similar question here: Server control behaving oddly
After some testing it looks like the reason is that HtmlGenericControl doesn't support self closing. On server side the HtmlGenericControl("br") is treated as:
<br runat="server"></br>
There is no </br> tag in HTML, so the browser shows it as there are two <br /> tags. Nice way out of this is to create HtmlGenericSelfCloseControl like this (sorry for C# code but you should have no issue with rewritting this in VB.NET):
public class HtmlGenericSelfCloseControl : HtmlGenericControl
{
public HtmlGenericSelfCloseControl()
: base()
{
}
public HtmlGenericSelfCloseControl(string tag)
: base(tag)
{
}
protected override void Render(HtmlTextWriter writer)
{
writer.Write(HtmlTextWriter.TagLeftChar + this.TagName);
Attributes.Render(writer);
writer.Write(HtmlTextWriter.SelfClosingTagEnd);
}
public override ControlCollection Controls
{
get { throw new Exception("Self closing tag can't have child controls"); }
}
public override string InnerHtml
{
get { return String.Empty; }
set { throw new Exception("Self closing tag can't have inner content"); }
}
public override string InnerText
{
get { return String.Empty; }
set { throw new Exception("Self closing tag can't have inner text"); }
}
}
And use it instead:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(New HtmlGenericSelfCloseControl("br"))
As a simpler alternative (if you have reference to the Page) you can try using Page.ParseControl:
pDoc.Controls.Add(New Label With {.Text = "whatever"})
pDoc.Controls.Add(Page.ParseControl("br"))

Razor Helpers sharing html problem with code blocks

I guess what I want to do is "chain" my data down so that it ends up looking the same.
All my html must be wrapped in some form of
<fieldset class="" data-role="">
So what I have is a helper that prints the various forms. One would be a label:
<fieldset data-role="#role">
<label>#Html.Raw(label)</label>
</fieldset>
Now when I have multiple types of labels, and one includes being a code block. When it is a
simple piece of text, like "First Name" I do:
#FieldSet.Label("First Name")
But when I have a code block such as:
<b>some text</b>
<p>some other text (some time frame - some time frame)
It becomes complicated to use this:
#FieldSet.Label("<b>" + Model.Text1 + "</b><p>" + Model.Text2 +
" (" + Model.Time1 + " - " + Model.Time2 +")</p>")
What I want it a solution that looks something like this:
#FieldSet.Label(#<text>
<b>#Model1.Text1</b>
<p>#Model.Text2 (#Model.Time1 - #Model.Time2)</p>
</text>)
I read somewhere this was possible, but I cannot find the article. I could be completely misled, but I really don't want to have a single piece of HTML in the code behind and I want to utilize the razor syntax, not string concatenation.
Check this articles from Phil Haack
http://haacked.com/archive/2011/02/27/templated-razor-delegates.aspx
http://haacked.com/archive/2011/04/14/a-better-razor-foreach-loop.aspx
You could:
Write as an extension method to a strongly-typed HtmlHelper:
public static class RazorExtensions
{
public static HelperResult Label<T>(this HtmlHelper<T> helper, Func<T, HelperResult> template) {
return new HelperResult(writer => {
writer.Write("<label>");
template(helper.ViewData.Model).WriteTo(writer);
writer.Write("</label>");
});
}
}
So you could write
#Html.Label(#<text><span>#Model.Item1<span><strong>#Model.Item2</strong></text>)
Pass Model as a parameter to your helper method
public static class FieldSet
{
public static HelperResult Label<T>(this T model, Func<T, HelperResult> template) {
return new HelperResult(writer => {
writer.Write("<label>");
template(model).WriteTo(writer);
writer.Write("</label>");
});
}
}
Usage:
#FieldSet.Label(Model, #<div><span>#Model.UserName</span><strong>#Model.FullName</strong><p>#Model.Description</p></div>)
You could look at how the #Html.BeginForm is implemented.
Create a class that implements IDisposable, and that writes to the Response stream directly:
Your code could look like this (entered by head, not tested):
class FieldSet : IDisposable {
public FieldSet(string label) {
// TODO: Encode label on line below
HttpContext.Current.Response.Write(string.Format("<fieldset><label =\"{0}\"", label));
}
public void Dispose() {
HttpContext.Current.Response.Write("</fieldset>");
}
}
static class FieldSetExtionsions {
public static FieldSet FieldSet(this HtmlHelper html, string label) {
return new FieldSet(label);
}
}
The usage will be:
#using (Html.FieldSet("your label")) {
<div>
Your razor code goes here
</div>
}

Resources