In Vaadin 14, we can set some CSS values programmatically in our Java code.
We can call getElement, then getStyle, and set the name of the CSS property along with a value.
For example, here we set the background color to green.
public class MainView extends VerticalLayout
{
public MainView ( )
{
this.getElement().getStyle().set( "background-color" , "Green" );
How do we do this for a CSS property like background-image that takes an argument of the CSS function named url?
Hard-coding the CSS path does not work.
public class MainView extends VerticalLayout
{
public MainView ( )
{
this.getElement().getStyle().set( "background-image" , "cat.jpg" );
➥ In Vaadin Flow, how to do we use Java to get CSS to find an image such as "cat.jpg"?
Furthermore, what should be the relative or absolute path to that image file be? I understand that the usual place for static images in Vaadin web app is in the src/main/resources folder.
In case of a "Plain Java Servlet" (non-Spring, non-CDI) Vaadin project, the file should go under /src/main/webapp
In case of Spring: /src/main/resources/META-INF/resources/img
Taken from official docs here: Resource Cheat Sheet
And, as #symlink has noticed in the comments, you should use a url('filename') syntax to reference an image in css : CSS background-image Property
For example, if I have a file named cat.jpg inside a /src/main/webapp/images, then this sets it getElement().getStyle().set("background-image","url('images/cat.jpg')");
Here is another example, with the picture file cat.jpg in src/main/webapp without nesting in an images folder. This is a Vaadin 14.0.10 web app, using the Plain Java Servlet technology stack option on the Start a new project with Vaadin page.
Below is the source code for an entire view using this image as a background.
Notice the first line of the constructor, where we pass "url('cat.jpg')" as an argument. See how we used single-quote marks around the file name to embed in a Java string without escaping. Fortunately the CSS specification allows for either single quotes (') or double quotes (") — quite convenient for Vaadin programmers embedding CSS within Java code.
package work.basil.example;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.PWA;
/**
* The main view contains a button and a click listener.
*/
#Route ( "" )
#PWA ( name = "Project Base for Vaadin", shortName = "Project Base" )
public class MainView extends VerticalLayout
{
public MainView ( )
{
this.getElement().getStyle().set( "background-image" , "url('cat.jpg')" );
Button button = new Button( "Click me" , event -> Notification.show( "Clicked!" ) );
add( button );
}
}
And a screenshot of this web app in action. The image is cropped because of the short height of the VerticalLayout. The layout is short because it contains only a button, whose label Click me can be seen faintly in blue text on the left edge. The cropped cat’s face is repeated across the page as is the default with CSS.
Related
I want to use SVG images as icons on a TabbedPage in Xamarin.Forms for iOS.
The documentation for the TabbedPage class provides the following tip:
The TabbedRenderer for iOS has an overridable GetIcon method that can be used to load tab icons from a specified source. This override makes it possible to use SVG images as icons on a TabbedPage. In addition, selected and unselected versions of an icon can be provided.
I created the following class to perform the override:
[assembly: ExportRenderer(typeof(TabsRoot), typeof(TabbedPageCustomRenderer))]
namespace MyProject.iOS.Renderers
{
public class TabbedPageCustomRenderer : TabbedRenderer
{
protected override Task<Tuple<UIImage, UIImage>> GetIcon(Page page)
{
var image = UIImage.FromFile(#"home-black-18dp.svg");
return Task.FromResult(new Tuple<UIImage, UIImage>(image, image));
}
}
}
The accepted answer in this thread recommends creating a UIImage from an SVG file by doing something like this: var myImage = UIImage.FromFile(<<file name>>) where <<filename>> is an SVG. This other thread contradicts the previous thread, saying that UIImages cannot be made from SVG files. Sure enough, when I provide an SVG file, UIImage.FromFile() returns null and no icon is shown at all, just as the latter thread predicted. When I provide a PNG file, the override works as expected.
Another way I've tried to square this circle is to use the SvgCachedImage provided by FFImageLoading.Svg.Forms, but I haven't figured out how to 'wrap' a UIImage around an SvgCachedImage or whether that is even appropriate in this case.
Thank you for your help!
Add Xamarin.FFImageLoading.Svg nuget package to your ios project.
then create the UImage in your GetIcon method like below :
UIImage img = await ImageService.Instance
.LoadFile("timer.svg")
.WithCustomDataResolver(new SvgDataResolver((int)(TabBar?.Bounds.Height / 2 ?? 30), (int)(TabBar?.Bounds.Height / 2 ?? 30), false))
.AsUIImageAsync();
UIImage newImg = img.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
I would like to set the caret color for all JavaFX text inputs (e.g. TextField, TextArea, the ones in ComboBox:editable, DatePicker, etc...)
I found this Stackoverflow answer: How to change the caret color in JavaFX 2.0?
... and an example on GitHub.
The first one does change the text and the caret color which is not good. The second one extends the TextFieldSkin class, which is already better, but how can I use it in CSS?
Any help is appreciated.
UPDATE 1:
I found the following CSS style property for JavaFX controls: -fx-skin.
This would theoretically allow me to set a custom skin class (-fx-skin: "package.MySkin";), however, the skin class just isn't used!
The class looks like the following:
package gui;
…
public class MyTextFieldSkin extends TextFieldSkin
{
public MyTextFieldSkin(TextField tf) {
super(tf);
System.out.println("MyTextFieldSkin constructor called!");
ReadOnlyObjectWrapper<Color> farbe = new ReadOnlyObjectWrapper<>(Color.green);
caretPath.strokeProperty().bind(farbe);
caretPath.setStrokeWidth(1.5);
}
}
… and is set in CSS like that:
.text-field {
-fx-skin: "gui.MyTextFieldSkin";
}
What am I doing wrong? I looked at the source code of AquaFX, and they are doing it the same way as me!
After a bit of try & error, I solved the problem in the following way:
I gathered all TextFields and controls that have TextFields in them (like ComboBox, DatePicker and so on) inside a container recursively (in deference of TitledPane, ScrollPane, SplitPane and TabPane, because they don't publish their children in getChildren(), so one has to call the getContent() method of the individual classes and scan through it).
After I had all the TextField controls, I looped over them and changed their Skin with the following code:
public class MyTextFieldSkin extends TextFieldSkin {
public MyTextFieldSkin(TextField tf)
{
super(tf);
ReadOnlyObjectWrapper<Color> color = new ReadOnlyObjectWrapper<>(Color.RED);
caretPath.strokeProperty().bind(color);
}
}
Then I just had to call
textfield.setSkin(new MyTextFieldSkin(textfield));
and that was about it.
Cheers
I've managed to style my QLineEdit to something like this:
alt text http://www.kimag.es/share/54278758.png
void Utilities::setFormErrorStyle(QLineEdit *lineEdit)
{
lineEdit->setStyleSheet(
"background-color: #FF8A8A;"
"background-image: url(:/resources/warning.png);"
"background-position: right center;"
"background-repeat: no-repeat;"
"");
}
I called the function using
Utilities *util = new Utilities;
util->setFormErrorStyle(lineNoStaf);
The flow should be something like this:
User open form
User fill data
User submit data
Got error
Use setFormErrorStyle()
User edit the text in the QLineEdit and the style disappear
This function should be reusable over and over again, but how can I connect QLineEdit signal such as textChanged() to a function in other class that will reset the Style Sheet and then disconnect the signal so that it won't be running continuously every time the text changed ?
Qt also allows dynamic properties in its stylesheet, that means you don't need to code your own class for every widget type in your form.
From http://qt-project.org/doc/qt-4.8/stylesheet-examples.html
Customizing Using Dynamic Properties
There are many situations where we need to present a form that has mandatory fields. To indicate to the user that the field is mandatory, one effective (albeit esthetically dubious) solution is to use yellow as the background color for those fields. It turns out this is very easy to implement using Qt Style Sheets. First, we would use the following application-wide style sheet:
*[mandatoryField="true"] { background-color: yellow }
This means that every widget whose mandatoryField Qt property is set to true would have a yellow background.
Then, for each mandatory field widget, we would simply create a mandatoryField property on the fly and set it to true. For example:
QLineEdit *nameEdit = new QLineEdit(this);
nameEdit->setProperty("mandatoryField", true);
QLineEdit *emailEdit = new QLineEdit(this);
emailEdit->setProperty("mandatoryField", true);
QSpinBox *ageSpinBox = new QSpinBox(this);
ageSpinBox->setProperty("mandatoryField", true);
Works also in Qt 4.3!
Allright, this is not compile but should work in principle, you should be able to change the look by calling editWidget->setProperty('isError',true) or editWidget->setError(false)
class ErrorTextEdit : QLineEdit
{
Q_OBJECT
QPROPERTY(bool isError, READ isError, WRITE setError);
public:
ErrorTextEdit(QWidget* parent) : QLineEdit(parent), m_isError(false)
{
m_styleSheet = "" // see below
setStyleSheet(m_styleSheet);
}
void setError(bool val)
{
if (val != m_isError)
{
m_isError = val;
setStyleSheet(m_styleSheet);
}
}
bool isError() {return m_isError;}
private:
QString m_styleSheet;
bool m_isError;
}
for the stylesheet
ErrorTextEdit[isError="false"]
{
optional ...
Style for textedit that is NOT an error
}
ErrorTextEdit[isError="true"]
{
background-color: #FF8A8A;
background-image: url(:/resources/warning.png);
background-position: right center;
background-repeat: no-repeat;
}
the term
[<property>="<value>"]
restricts the application of the stylesheet to instances of the class whose <property> has the appropriate <value> the only caveat is that the style is not changed when the property changes its' value, so the stylesheet has to be reapplied for the look of the widget to actually change, see Stylesheet Documentation -> Property Selector
This construction moves the stylesheet into the widget that uses it and makes switch internal to the widget, the widget changes in accordance to its state.
In general you have a couple of ways to handle invalid inputs in your form
a) observe every change and update the style appropriately, you should be able to use QValidator for that too, but that is a separate topic, using QValidator you will probably be able to completely internalize the state of a single QTextEdit and not have to deal with its validity from the outside
b) Do it in the submit loop that you have described above, whenever the user clicks on submit change the state of the correct and incorrect fields
it all depends the structure of your app and the view
See, the other idea is you need to override the paint evet of line edit and then set the background image and color.
here the implimentation is presetn here button, follow up the same to your line edit
in MXML, there is a Button class which you can instantiate like so:
<mx:Button id="something />
but what if you wanted to dynamically build this in AS3 and add it to the Flex app dynamically, without the use of components (just AS3) and then modify Flex's styles, for example, here you access the Button's properties and set them:
var btn:Button = new Button();
btn.height = 50;
btn.width = 75;
btn.x = 100;
btn.y = 40;
but how would you go about changing the Style, for example:
btn.downSkin = "something";
btn.color = "0xfffff";
I'm sort of starting to lean towards making a flex component in MXMLand than just making it visible true/false, but i like the fact that i create an object in AS3 and then destroy it when I don't need it anymore, than create it again once needed.
This page has a solution to the problem:
Setting and getting Style attributes in ActionScript:
// setting a components styleName to reference a CSS class
component.styleName = "highlight";
// set a Button's background color and font size
submitButton.setStyle( "backgroundColor", 0x000000 );
submitButton.setStyle( "fontSize", 14 );
// get a TextArea's font family and color
textArea.getStyle( "fontFamily" );
textArea.getStyle( "color" );
You could use CSS, either inline or as an external CSS file. That way you don't have to set the properties manually every time you create a button.
/* CSS file */
Button {
borderColor: red;
}
Check out Styling Button control, by Peter deHaan (also read the comments in that post).
I embed SVG graphics in my Flex application using
package MyUI
{
public class Assets
{
[Embed(source="/assets/pic.svg"]
[Bindable]
public static var svgPic:Class;
}
}
and then extending the Tree class with some of my own code, setting the icon upon adding a node to the data provider:
public class MyTree extends Tree
{
public function MyTree()
{
// ...
this.iconField = "svgIcon";
// ...
this.dataProvider = new ArrayCollection;
this.dataProvider.addItem({ /* ... */ svgIcon: MyUI.Assets.svgPic /* ... */ });
// ...
}
}
Now I have two things I want to do:
use the SVG graphics in multiple places in the app, scaling them to the appropriate size for each appearance, i. e. scale them to a proper icon size when using them in the tree
change the size of the icon at runtime, e. g. display a slightly larger icon for selected items or let an icon "pulse" as a response to some event
I read the Flex documentation on the 9-slice scaling properties in the Embed tag, but I think that's not what I want.
Edit:
I unsuccessfully checked the "similar questions" suggested by SO, among others this one:
Flex: Modify an embedded icon and use it in a button?
Subclass mx.controls.treeClasses.TreeItemRenderer and make it resize the icon to your desired dimensions, or create your own item renderer implementation by using the same interfaces as TreeItemRenderer. Set a custom item renderer with the itemRenderer property:
exampleTree.itemRenderer = new ClassFactory( ExampleCustomItemRendererClass );
The answer to this question might point you in the right direction, without knowing more about the trouble you're having:
Flex: Modify an embedded icon and use it in a button?
Hope it helps!