Large label as a heading in Vaadin 8 web app - css

I need a larger piece of text to use as a heading to label sections of a form in a Vaadin 8 app using the Valo theme.
In previous versions of Vaadin, I recall doing this with a Label that I had somehow assigned a predefined style of "H1" (as in HTML "h1" tag) where that style was part of the Reindeer theme.
I tried and failed to do this in Vaadin 8 by calling Label::addStyleName and passing the constant ValoTheme.LABEL_H1.

Yes, indeed, calling addStyleName on the Label and passing the constant ValoTheme.LABEL_H1 does work, as per the comment by Morfic.
final Label labelPlain = new Label ( "This is a plain Label in Vaadin 8.1.0 Alpha 6." );
final Label labelH1 = new Label ( "This is a 'h1' Label in Vaadin 8.1.0 Alpha 6." );
labelH1.addStyleName ( ValoTheme.LABEL_H1 );
Here is a complete example app, modified from the usual Vaadin archetype vaadin-archetype-application in Vaadin 8.1.0 Alpha 6.
package com.example.try_h1;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of a html page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {#link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
#Theme ( "mytheme" )
public class MyUI extends UI {
#Override
protected void init ( VaadinRequest vaadinRequest ) {
final VerticalLayout layout = new VerticalLayout ( );
final Label labelPlain = new Label ( "This is a plain Label in Vaadin 8.1.0 Alpha 6." );
final Label labelH1 = new Label ( "This is a 'h1' Label in Vaadin 8.1.0 Alpha 6." );
labelH1.addStyleName ( ValoTheme.LABEL_H1 );
layout.addComponents ( labelPlain, labelH1 );
setContent ( layout );
}
#WebServlet ( urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true )
#VaadinServletConfiguration ( ui = MyUI.class, productionMode = false )
public static class MyUIServlet extends VaadinServlet {
}
}
Screenshot of running that example app.
addStyleName versus setStyleName
Be careful to call addStyleName rather than setStyleName. That second one clears all existing styles, replacing with your one style argument. This is not what you want, as you’ll lose all the existing styles assigned by the Vaadin framework.

Related

Specify a background image via CSS in Vaadin 14 programmatically with Java

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.

JavaFX - How to set Custom font to javaFX controls? [duplicate]

Firstly, I am quite a new guy in coding. I need to embed a font in my java FXML-based app and don't know how to do it. I have pasted the font, fontName.ttf in a "resources" folder in the root of the sources of my project, ie App/src/app/resources. I have set the CSS for the component (text) as
#text {
-fx-font-family: url(resources/fontName.ttf);
}
I have also tried adding inverted commas in the url, ie url("resources/fontName.ttf");, but it doesn't work. I have also set the CSS id for the component, so that can't be the problem. Is there any other working way to do so? I have seen http://fxexperience.com/2010/05/how-to-embed-fonts/, but it doesn't work since I have JDK 1.7 u21. Any ideas for a correct way to embed fonts?
Solution Approach
I updated the sample from Javafx How to display custom font in webview? to demonstrate using a custom true-type font in JavaFX controls styled using CSS.
Key points are:
Place the font in the same location as your application class and ensure your build system places it in your binary build package (e.g. application jar file).
Load the code font in your JavaFX code before you apply a style which uses it.
Font.loadFont(CustomFontApp.class.getResource("TRON.TTF").toExternalForm(), 10);
To use the custom font in a style class use the -fx-font-family css attribute and just reference the name of the font (e.g. in this case "TRON").
Create and load a stylesheet which defines the style classes.
Apply style classes to your controls.
Additional Information
If you are using Java 8, you may be interested in Use web(Google) fonts in JavaFX.
Font Collections
If your font file is in .ttc format, containing multiple fonts in a single file, then use the Font.loadFonts API (instead of Font.loadFont). Note that Font.loadFonts is only available since JDK 9 and is not available in earlier releases.
Sample Output Using a Custom Font
Sample Code
The example relies on a TRON.TTF font which you can download from dafont.
CustomFontApp.java
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.*;
import javafx.stage.Stage;
// demonstrates the use of a custom font.
public class CustomFontApp extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
stage.setTitle("TRON Synopsis");
// load the tron font.
Font.loadFont(
CustomFontApp.class.getResource("TRON.TTF").toExternalForm(),
10
);
Label title = new Label("TRON");
title.getStyleClass().add("title");
Label caption = new Label("A sci-fi flick set in an alternate reality.");
caption.getStyleClass().add("caption");
caption.setMaxWidth(220);
caption.setWrapText(true);
caption.setTextAlignment(TextAlignment.CENTER);
VBox layout = new VBox(10);
layout.setStyle("-fx-padding: 20px; -fx-background-color: silver");
layout.setAlignment(Pos.CENTER);
layout.getChildren().setAll(
title,
new ImageView(
new Image(
"http://ia.media-imdb.com/images/M/MV5BMTY5NjM2MjAwOV5BMl5BanBnXkFtZTYwMTgyMzA5.V1.SY317.jpg"
)
),
caption
);
// layout the scene.
final Scene scene = new Scene(layout);
scene.getStylesheets().add(getClass().getResource("custom-font-styles.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
}
custom-font-styles.css
/** file: custom-font-styles.css
* Place in same directory as CustomFontApp.java
*/
.title {
-fx-font-family: "TRON";
-fx-font-size: 20;
}
.caption {
-fx-font-family: "TRON";
-fx-font-size: 10;
}
On FXML Usage
Font.loadFont(url, size) is a static method taking two parameters. I don't think you can invoke font.loadFont from FXML and wouldn't advise it if you could. Instead, load the font in Java code (as I have done in my answer) before you load your FXML or style sheet which requires the font.
I know you didn't ask for a pure programmatic way to use a custom TTF font in a java fx application but i thought maybe it helps someone to see a programmatic version:
public class Test2 extends Application {
public static void main(String[] args) {
launch(args);
}
public void start(final Stage primaryStage) {
Group rootGroup = new Group();
// create a label to show some text
Label label = new Label("Demo Text");
try {
// load a custom font from a specific location (change path!)
// 12 is the size to use
final Font f = Font.loadFont(new FileInputStream(new File("./myFonts/TRON.TTF")), 12);
label.setFont(f); // use this font with our label
} catch (FileNotFoundException e) {
e.printStackTrace();
}
rootGroup.getChildren().add(label);
// create scene, add root group and show stage
Scene scene = new Scene(rootGroup, 640, 480, Color.WHITE);
primaryStage.setScene(scene);
primaryStage.show();
}
}
That did the job for me. You can place the font wherever you want just make sure you adapt the path.
You can find a lot more about using fonts inside java fx apps here.
HTH

Plone portlet using plone.namedfield.field.NamedImage

I'm running Plone 4.3 and have been trying to create a custom portlet. The portlet is simple and should allow the user to upload an image and provide some descriptive text which can be displayed beneath the image.
Here's the code I have so far:
from zope.interface import implements
from zope.formlib import form
from zope import schema
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.namedfile.field import NamedImage
from plone.directives import form
from z3c.form import field
from plone.app.portlets.browser import z3cformhelper
class IMyImagePortlet(form.Schema):
myimagetitle = schema.TextLine(
title=u"Image title",
description=u"Enter the image title",
default=u"",
required=True)
myimagedescription = schema.TextLine(
title=u"Image text",
description=u"Enter the text which appears below the image",
default=u"",
required=True)
myimage = NamedImage(
title=u"My image",
description=u"Upload an image",
required=True)
class Assignment(base.Assignment):
implements(IMyImagePortlet)
header = u"My Image"
myimagetitle = u""
myimagedescription = u""
myimage = u""
def __init__(self, myimagetitle=None, myimagedescription=None, myimage=None):
self.myimagetitle = myimagetitle
self.myimagedescription = myimagedescription
self.myimage = myimage
#property
def title(self):
"""This property is used to give the title of the portlet in the
"manage portlets" screen.
"""
return u"My image"
class Renderer(base.Renderer):
_template = ViewPageTemplateFile('templates/myimage_portlet.pt')
def __init__(self, *args):
base.Renderer.__init__(self, *args)
#memoize
def myimagetitle(self):
return self.data.myimgaetitle
#memoize
def myimagedescription(self):
return self.data.myimagedescription
#memoize
def myimage(self):
return self.data.myimage
def render(self):
return self._template()
class AddForm(z3cformhelper.AddForm):
fields = field.Fields(IMyImagePortlet)
label = u"Edit image"
description = u"A portlet which can display image with text"
def create(self, data):
return Assignment(**data)
class EditForm(z3cformhelper.EditForm):
fields = field.Fields(IMyImagePortlet)
label = u"Edit image"
description = u"A portlet which can display image with text"
This seems to work as expected and allows me to add a new portlet with a title, image, and image description. However, I've been reading the docs and I couldn't find many examples of creating a portlet with an image upload field, so there may be a better way of doing this.
My issue is that I can't seem to render the image in the template. I've been referring to the docs at https://developer.plone.org/reference_manuals/external/plone.app.dexterity/advanced/files-and-images.html and have the following in my template, but the image is not being displayed:
<div tal:define="picture nocall:context/myimage"
tal:condition="nocall:picture">
<img tal:attributes="src string:${context/absolute_url}/##download/myimage/${picture/filename};
height picture/_height | nothing;
width picture/_width | nothing;"
/>
</div>
We did exactly what you want.
https://github.com/4teamwork/ftw.subsite/tree/master/ftw/subsite/portlets
It's a teaser portlet, unfortunately not in a single package. but you can adapt the code to your needs.
We defined a browser view in image.py:
from Acquisition import aq_inner
from zope.publisher.browser import BrowserView
class ImageView(BrowserView):
"""View the image field of the image portlet. We steal header details
from zope.app.file.browser.file and adapt it to use the dublin
core implementation that the Image object here has."""
def __call__(self):
context = aq_inner(self.context)
image = context.image
self.request.response.setHeader('Content-Type', image.contentType)
self.request.response.write(image.data)
Register with zcml (Important the image view is for your portlet Assignment):
<browser:page
for=".yourportlet.Assignment"
name="image"
class=".image.ImageView"
permission="zope.Public"
/>
In your portlet Renderer you have to define a method, which gets the image (traverse).
from plone.app.portlets.portlets import base
class MyPortletRenderer(base.Renderer)
def image_tag(self):
state = getMultiAdapter((self.context, self.request),
name="plone_portal_state")
portal = state.portal()
assignment_url = \
portal.unrestrictedTraverse(
self.data.assignment_context_path).absolute_url()
return "<img src='%s/%s/##image' alt=''/>" % (
assignment_url,
self.data.__name__)
Now you are able to use the image in your portlet:
<tal:image content="structure view/image_tag />
I don't know if there is a simpler solution.
Naming could be better :-)
But it works and it's tested https://github.com/4teamwork/ftw.subsite/blob/master/ftw/subsite/tests/test_subsiteportlet.py

Making buttons link - Adobe flex - Blackberry Playbook

Maybe a simple question but I'm having alot of trouble making a button change the view of a Flex blackberry playbook app. I am coding it entirely in actionscript, no MXML.
myButton.addEventListener(MouseEvent.CLICK, doSomethingOnClick);
private function doSomethingOnClick(e:MouseEvent):void {
navigator.pushView(view.Login, "testdata");
}
When I try this I get:
1120: Access of undefined property navigator.
Which is weird as it works in a MXML file. How do I change views in actionscript?
Thanks
Phil
EDIT:
Cheer J_A_X, but now i have:
navigator = new ViewNavigator();
navigator.pushView(net.airpoint.assessments.view.Login, " ");
TypeError: Error #1009: Cannot access a property or method of a null object reference.
Apologies, as I realise this is really simple stuff but it just isnt clicking!
Update 2
*Assessments.as*
package
{
import flash.display.Sprite;
import flash.events.Event;
import net.airpoint.assessments.view.*;
import qnx.ui.core.Container;
import qnx.ui.core.ContainerAlign;
import qnx.ui.core.ContainerFlow;
import qnx.ui.core.Containment;
import qnx.ui.text.Label;
import spark.components.ViewNavigator;
[SWF(height="600", width="1024", frameRate="30", backgroundColor="#FFFFFF")]
/* Main Layout */
public class Assessments extends Sprite
{
//containers
private var main:Container;
private var menu:Container
private var firstLabel:Label;
private var navigator:ViewNavigator;
public function Assessments()
{
initializeUI();
}
private function initializeUI():void
{
main = new Container();
main.padding = Vector.<Number>([20,20,20,20]);
main.flow = ContainerFlow.HORIZONTAL;
main.debugColor = 0xFFCC00;
firstLabel = new Label();
firstLabel.text = "First label";
firstLabel.size=35;
main.addChild(firstLabel);
addChild(main);
navigator = new ViewNavigator();
navigator.pushView(Login, " ");
}
}
}
Login.as
package net.airpoint.assessments.view
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import qnx.ui.buttons.Button;
import qnx.ui.core.Container;
import qnx.ui.text.Label;
import qnx.ui.text.TextInput;
import spark.components.View;
public class Login extends View
{
private var usernameLabel:Label;
public function Login()
{
initializeUI();
}
public function initializeUI():void
{
usernameLabel.text = "test";
this.addChild(usernameLabel);
}
}
}
Something isn't right. If it's a Flex Mobile Project, you need an Application at the top level (you know, like how Flash Builder created the project with an mxml file). Either you create an actionscript file that extends Application as mentioned here or you just use an mxml file for the root component.
However, your argument to 'not use mxml' is redundant if you're using Flex components. If you're using Flex components, you're using mxml no matter what, so there's no performance increase. If anything, RIM is recommending to use AS only because their SDK is AS only (which is idiotic anyways). You could always add their UI component through AS in mxml files.
So really, the point is moot and you should just use mxml anyways since it's better than straight AS for UI layout and skinning. Either that or go Pure AS with no Flex components.
I think using Sprite is ok in an ActionScript project.
But if you're using ActionScript instead of Flex just because of the QNX components, then you could switch your project to Flex and follow these instructions to use the QNX components there: Using qnx.ui.picker.Picker in mobile Flex Hero project for Blackberry Playbook

Adobe Air application and {StageScaleMode.SHOW_ALL StageDisplayState.FULL_SCREEN}

I have problem with using next two properties together in one Air application, I need some functionality for show my application in full screen and scale for different displays. I mean , if user has 17" and other has 24" display my app should save proportionals. So, I've start to use these two properties StageScaleMode.SHOW_ALL StageDisplayState.FULL_SCREEN and see that internal canvas (buffer) is bigger than external, please see on the pictures the firs just StageDisplayState.FULL_SCREEN and the second StageDisplayState.FULL_SCREEN and StageScaleMode.SHOW_ALL.
Could you help me and say How to fix this problem?
Thanks.
StageScaleMode.SHOW_ALL ensures the entire content of your Flash Movie is always displayed. Depending on how large your content is, and where you place your images, this might well exceed the actual display width of your screen.
If you want your movie to always center on screen, but not scale its content, do it like this (fullscreen on click):
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
public class Test extends MovieClip
{
private var content : Sprite;
public function Test ()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
content = new Sprite( );
content.graphics.beginFill( 0, 1 );
content.graphics.drawRect( 0, 0, 200, 100 );
content.graphics.endFill( );
addChild( content );
stage.addEventListener( Event.RESIZE, onResize );
content.addEventListener( MouseEvent.CLICK, onMouseClick );
}
public function onMouseClick (ev : Event) : void
{
stage.displayState = StageDisplayState.FULL_SCREEN;
}
public function onResize ( ev : Event ) : void
{
content.x = (stage.stageWidth - content.width) * .5;
content.y = (stage.stageHeight - content.height) * .5;
}
}
}
Then attach all your elements to the content Sprite instead of the stage.
I have developed my own approach for re-sizing without using SHOW_ALL property, but currently it correctly works only on the Windows systems.
The real issue here is that anything except stage.scaleMode = StageScaleMode.NO_SCALE; will not report the actual stage.stageWidth and stage.stageHeight, but will instead return the width and height of the authored dimensions.

Resources