What the FXML equivalent for iterative rendering (v-for attribute) in below Vue-like markup?
<VBox>
<HBox v-for="task of tasks">
<Checkbox :checked="task.isComplete"></Checkbox>
<VBox>
<Label>{{ task.title }}</Label>
<Label>{{ task.description }}</Label>
</VBox>
</HBox>
</VBox>
The desired displaying:
I prepared the below ObservableList:
ObservableList<Task> tasks = FXCollections.observableArrayList();
tasks.add(new Task("Wake up", "... and fly."));
tasks.add(new Task("Wash face", "... with cold water."));
ObservableList will react to new additions, you just have to display it programmatically in some way, for example using a custom component with ListView:
package sample;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
static class Task{
String title, description;
boolean done;
Task(String title, String description){
this.title = title;
this.description = description;
}
}
ListView<Task> list = new ListView<>();
ObservableList<Task> data = FXCollections.observableArrayList(
new Task("Wake up", "... and fly."),
new Task("Wash face", "... with cold water.")
);
#Override
public void start(Stage stage) {
VBox box = new VBox();
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.setTitle("ListViewSample");
box.getChildren().addAll(list);
VBox.setVgrow(list, Priority.ALWAYS);
list.setItems(data);
list.setCellFactory(list -> new TaskCell());
stage.show();
}
static class TaskCell extends ListCell<Task> {
#Override
public void updateItem(Task task, boolean empty) {
super.updateItem(task, empty);
if (task != null) {
CheckBox done = new CheckBox();
done.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> { task.done = !task.done; });
done.setSelected(task.done);
HBox cell = new HBox(
done,
new VBox(new Label(task.title), new Text(task.description))
);
cell.setAlignment(Pos.CENTER_LEFT);
setGraphic(cell);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
See this article for more details.
Related
I'm currently trying to display the percentage of my Ev Via Android Auto. I can't manage to get CarInfo carInfo = getCarContext().getCarService(CarHardwareManager.class).getCarInfo(); to run. I used this in my automotive build.gradle useLibrary 'android.car' and tried importing many things but that didn't help obviously.
This is my first file:
package com.example.aatest4;
import android.car.Car;
import android.car.CarInfoManager;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.car.app.CarAppMetadataHolderService;
import androidx.car.app.CarAppService;
import androidx.car.app.CarContext;
import androidx.car.app.Screen;
import androidx.car.app.Session;
import androidx.car.app.hardware.CarHardwareManager;
import androidx.car.app.hardware.info.CarInfo;
import androidx.car.app.validation.HostValidator;
//import android.content.ServiceConnection;
public class HelloWorldService extends CarAppService {
#NonNull
#Override
public HostValidator createHostValidator() {
return HostValidator.ALLOW_ALL_HOSTS_VALIDATOR;
}
public Session onCreateSession() {
return new Session() {
#NonNull
#Override
public Screen onCreateScreen(#NonNull Intent intent) {
CarInfo carInfo = getCarContext().getCarService(CarHardwareManager.class).getCarInfo();
return new HelloWorldScreen(getCarContext());
}
};
}
}
and this my second:
package com.example.aatest4;
//import android.car.Car;
//import android.car.CarInfoManager;
import androidx.annotation.NonNull;
import androidx.car.app.CarContext;
import androidx.car.app.Screen;
import androidx.car.app.model.Pane;
import androidx.car.app.model.PaneTemplate;
import androidx.car.app.model.Row;
import androidx.car.app.model.Template;
public class HelloWorldScreen extends Screen {
//public HelloWorldScreen() {
public HelloWorldScreen(CarContext carContext) {
super(carContext);
}
#NonNull
#Override
public Template onGetTemplate() {
String akku = String.valueOf(50);
Row row = new Row.Builder().setTitle(akku + "% ").addText(akku + "%").build();
return new PaneTemplate.Builder(new Pane.Builder().addRow(row).build()) .setTitle("Akkuanzeige").build();
//Todo: Center?
}
}
Please forgive me if this has been asked but I have not found any matches yet.
I have some PDF files where images are duplicated on each page's resources but never used in its content stream. I think this is causing the PDFSplit command to create very bloated pages. Is there any utility code or examples to clean up unused resources like this? Maybe a starting point for me to get going?
I was able to clean up the resources for each page by gathering a list of the images used inside the page's content stream. With the list of images, I then check the resources for the page and remove any that weren't used. See the PageExtractor.stripUnusedImages below for implementation details.
The resource object was shared between pages so I also had to make sure each page had its own copy of the resource object before removing images. See PageExtractor.copyResources below for implementation details.
The page splitter:
package org.apache.pdfbox.examples;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PageExtractor {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public PDDocument extractPage(PDDocument source, Integer pageNumber) throws IOException {
PDDocument targetPdf = new PDDocument();
targetPdf.getDocument().setVersion(source.getVersion());
targetPdf.setDocumentInformation(source.getDocumentInformation());
targetPdf.getDocumentCatalog().setViewerPreferences(source.getDocumentCatalog().getViewerPreferences());
PDPage sourcePage = source.getPage(pageNumber);
PDPage targetPage = targetPdf.importPage(sourcePage);
targetPage.setResources(sourcePage.getResources());
stripUnusedImages(targetPage);
stripPageLinks(targetPage);
return targetPdf;
}
/**
* Collect the images used from a custom PDFStreamEngine (BI and DO operators)
* Create an empty COSDictionary
* Loop through the page's XObjects that are images and add them to the new COSDictionary if they were found in the PDFStreamEngine
* Assign the newly filled COSDictionary to the page's resource as COSName.XOBJECT
*/
protected void stripUnusedImages(PDPage page) throws IOException {
PDResources resources = copyResources(page);
COSDictionary pageObjects = (COSDictionary) resources.getCOSObject().getDictionaryObject(COSName.XOBJECT);
COSDictionary newObjects = new COSDictionary();
Set<String> imageNames = findImageNames(page);
Iterable<COSName> xObjectNames = resources.getXObjectNames();
for (COSName xObjectName : xObjectNames) {
if (resources.isImageXObject(xObjectName)) {
Boolean used = imageNames.contains(xObjectName.getName());
if (used) {
newObjects.setItem(xObjectName, pageObjects.getItem(xObjectName));
} else {
log.info("Found unused image: name={}", xObjectName.getName());
}
} else {
newObjects.setItem(xObjectName, pageObjects.getItem(xObjectName));
}
}
resources.getCOSObject().setItem(COSName.XOBJECT, newObjects);
page.setResources(resources);
}
/**
* It is necessary to copy the page's resources since it can be shared with other pages. We must ensure changes
* to the resources are scoped to the current page.
*/
protected PDResources copyResources(PDPage page) {
return new PDResources(new COSDictionary(page.getResources().getCOSObject()));
}
protected Set<String> findImageNames(PDPage page) throws IOException {
Set<String> imageNames = new HashSet<>();
PdfImageStreamEngine engine = new PdfImageStreamEngine() {
#Override
void handleImage(Operator operator, List<COSBase> operands) {
COSName name = (COSName) operands.get(0);
imageNames.add(name.getName());
}
};
engine.processPage(page);
return imageNames;
}
/**
* Borrowed from PDFBox page splitter
*
* #see org.apache.pdfbox.multipdf.Splitter#processAnnotations(org.apache.pdfbox.pdmodel.PDPage)
*/
protected void stripPageLinks(PDPage imported) throws IOException {
List<PDAnnotation> annotations = imported.getAnnotations();
for (PDAnnotation annotation : annotations) {
if (annotation instanceof PDAnnotationLink) {
PDAnnotationLink link = (PDAnnotationLink) annotation;
PDDestination destination = link.getDestination();
if (destination == null && link.getAction() != null) {
PDAction action = link.getAction();
if (action instanceof PDActionGoTo) {
destination = ((PDActionGoTo) action).getDestination();
}
}
if (destination instanceof PDPageDestination) {
// TODO preserve links to pages within the splitted result
((PDPageDestination) destination).setPage(null);
}
}
// TODO preserve links to pages within the splitted result
annotation.setPage(null);
}
}
}
The stream reader used to analyze the page's images:
package org.apache.pdfbox.examples;
import org.apache.pdfbox.contentstream.PDFStreamEngine;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.contentstream.operator.OperatorProcessor;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup;
import java.io.IOException;
import java.util.List;
abstract public class PdfImageStreamEngine extends PDFStreamEngine {
PdfImageStreamEngine() {
addOperator(new DrawObjectCounter());
}
abstract void handleImage(Operator operator, List<COSBase> operands);
protected class DrawObjectCounter extends OperatorProcessor {
#Override
public void process(Operator operator, List<COSBase> operands) throws IOException {
if (operands != null && isImage(operands.get(0))) {
handleImage(operator, operands);
}
}
protected Boolean isImage(COSBase base) throws IOException {
if (!(base instanceof COSName)) {
return false;
}
COSName name = (COSName)base;
if (context.getResources().isImageXObject(name)) {
return true;
}
PDXObject xObject = context.getResources().getXObject(name);
if (xObject instanceof PDTransparencyGroup) {
context.showTransparencyGroup((PDTransparencyGroup)xObject);
} else if (xObject instanceof PDFormXObject) {
context.showForm((PDFormXObject)xObject);
}
return false;
}
#Override
public String getName() {
return "Do";
}
}
}
I would like the player to pickup the Custom Arrow not an normal arrow.
I think its something to do with an ItemStack is this possible to do in Minecraft 1.12.2?
My arrow class called CustomArrow:
package domain.items.objects;
import domain.entity.ECustomArrow;
import domain.register.RegisterItems;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemArrow;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
public class LevitationArrow extends ItemArrow {
public LevitationArrow(String Name) {
this.setCreativeTab(CreativeTabs.COMBAT);
this.setRegistryName(Name);
this.setUnlocalizedName(Name);
RegisterItems.ITEMS.add(this);
}
public ECustomArrow makeTippedArrow(World world, ItemStack itemstack, EntityLivingBase shooter) {
return new ECustomArrow(world, shooter);
}
}
Arrow entity called ECustomArrow
package domain.entity;
import domain.Utils;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraft.init.MobEffects;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
public abstract class ECustomArrow extends EntityArrow {
public ECustomArrow(World worldIn, EntityLivingBase shooter) {
super(worldIn);
}
#Override
public void arrowHit(EntityLivingBase living) {
super.arrowHit(living);
if (living != shootingEntity) {
living.addPotionEffect(new PotionEffect(MobEffects.***EFFECT NAME***, Utils.SECS2TICKS(10), 1));
}
}
}
In my main items class i got
...
public static ItemArrow customarrow;
...
customarrow = new CustomArrow("customarrow");
...
I would like to ask about library APACHE POI. I have a .pptx file and with the example which I found on internet I split each slide into separate images. This works great when slide containts .png, .jpeg images but as soon as I have .emf files in slide this image disappear. So I want to have the same copy of slide but with .emf file as well. Is this possible?
version: Apache POI 3.12
Thanks a lot
As mentioned in the comments, EMF is not supported out of the box ... and as FreeHep decided to have a LGPL license it's unlikely that we will include in our release.
In POI you basically have two options to provide a custom image renderer:
implement and register your ImageRenderer implementation in the Graphics2D context via setRenderingHint(Drawable.IMAGE_RENDERER, new MyImageRendener()). The drawback is, that it will be called for any images and you loose the default handling for bitmap/wmf images
or provide a custom DrawFactory which serves your own DrawPictureShape implementation - as in the example below - which only diverts to the EMF renderer when necessary
(looking at this example, the current POI ImageRenderer handling doesn't look flexible and instead of having a global handler, it might be better to register a handler per content-type ...)
Apart of the usual POI component I've included freehep-graphics2d, freehep-graphicsbase, freehep-graphicsio, freehep-graphicsio-emf and freehep-io.
The example is far from being finished, but I guess you get at least a kick-start:
package org.apache.poi.xslf;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.poi.sl.draw.DrawFactory;
import org.apache.poi.sl.draw.DrawPictureShape;
import org.apache.poi.sl.draw.Drawable;
import org.apache.poi.sl.draw.ImageRenderer;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.sl.usermodel.PictureShape;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.freehep.graphicsio.emf.EMFInputStream;
import org.freehep.graphicsio.emf.EMFRenderer;
import org.junit.Test;
public class TestEMFRender {
private final static POILogger LOG = POILogFactory.getLogger(TestEMFRender.class);
#Test
public void render() throws Exception {
XMLSlideShow ppt = getDummy();
Dimension pgsize = ppt.getPageSize();
BufferedImage img = new BufferedImage((int)pgsize.getWidth(), (int)pgsize.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = initGraphicsCtx(img);
// draw stuff
ppt.getSlides().get(0).draw(graphics);
// save the result
File outfile = new File("bla.png");
ImageIO.write(img, "PNG", outfile);
// cleanup
graphics.dispose();
img.flush();
ppt.close();
}
static XMLSlideShow getDummy() throws IOException {
XMLSlideShow ppt = new XMLSlideShow();
FileInputStream fis = new FileInputStream("kiwilogo.emf");
PictureData pd = ppt.addPicture(fis, PictureType.EMF);
fis.close();
XSLFSlide sl = ppt.createSlide();
XSLFPictureShape ps = sl.createPicture(pd);
ps.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
return ppt;
}
static Graphics2D initGraphicsCtx(BufferedImage img) {
Graphics2D graphics = img.createGraphics();
// default rendering options
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
// custom draw factory
DrawFactory df = new DrawFactory(){
public DrawPictureShape getDrawable(PictureShape<?,?> shape) {
return new DrawPictureShapeEmf(shape);
}
};
graphics.setRenderingHint(Drawable.DRAW_FACTORY, df);
df.fixFonts(graphics);
return graphics;
}
static class DrawPictureShapeEmf extends DrawPictureShape {
public DrawPictureShapeEmf(PictureShape<?,?> shape) {
super(shape);
}
#Override
public void drawContent(Graphics2D graphics) {
PictureData data = getShape().getPictureData();
if(data == null) return;
Rectangle2D anchor = getAnchor(graphics, getShape());
Insets insets = getShape().getClipping();
try {
String contentType = data.getContentType();
ImageRenderer renderer =
PictureType.EMF.contentType.equals(contentType)
? new ImgRenderer()
: super.getImageRenderer(graphics, contentType);
renderer.loadImage(data.getData(), data.getContentType());
renderer.drawImage(graphics, anchor, insets);
} catch (IOException e) {
LOG.log(POILogger.ERROR, "image can't be loaded/rendered.", e);
}
}
}
static class ImgRenderer implements ImageRenderer {
EMFRenderer emfRenderer;
public void loadImage(InputStream data, String contentType) throws IOException {
emfRenderer = new EMFRenderer(new EMFInputStream(data));
}
public void loadImage(byte[] data, String contentType) throws IOException {
loadImage(new ByteArrayInputStream(data), contentType);
}
public Dimension getDimension() {
return emfRenderer.getSize();
}
public void setAlpha(double alpha) {
}
public BufferedImage getImage() {
return null;
}
public BufferedImage getImage(Dimension dim) {
return null;
}
public boolean drawImage(Graphics2D ctx, Rectangle2D graphicsBounds) {
return drawImage(ctx, graphicsBounds, null);
}
public boolean drawImage(Graphics2D ctx, Rectangle2D graphicsBounds, Insets clip) {
AffineTransform at = ctx.getTransform();
try {
Dimension emfDim = emfRenderer.getSize();
// scale output bounds to image bounds
ctx.translate(graphicsBounds.getX(), graphicsBounds.getY());
ctx.scale(graphicsBounds.getWidth()/emfDim.getWidth(), graphicsBounds.getHeight()/emfDim.getHeight());
// TODO: handle clipping
emfRenderer.paint(ctx);
return true;
} catch (RuntimeException e) {
// TODO: logging
return false;
} finally {
ctx.setTransform(at);
}
}
}
}
I would like to ask how is it possible to make a notification icon over an existing Node !
Here is a link I'm using as inspiration !
http://www.red-team-design.com/notification-bubble-css3-keyframe-animation
It would really save me if anyone could give me a help ^^
You can find an example here:
https://www.billmann.de/post/2012/08/05/javafx-miniiconanimationbutton/
I just solved The problem.
I've used the animation created by billman but not extending the StackPane this time, but by extending the Button Node, and I've set the Notification icon to be extending from the StackPane and it worked out perfectly !!
Here the way to do so:
AnimatedButton.java
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.scene.Node;
import javafx.scene.control.MenuItem;
import javafx.util.Duration;
public class Icons extends MenuItem {
private final Node icon;
private AnimationType type;
public Icons(String text, Node icon, AnimationType type) {
setText(text);
setGraphic(icon);
this.icon = icon;
this.type = type;
addAnimation();
}
private void addBlinkAnimation() {
final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
final KeyValue kv = new KeyValue(icon.opacityProperty(), 0.0);
final KeyFrame kf = new KeyFrame(Duration.millis(700), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
}
private void addJumpAnimation() {
final TranslateTransition translateTransition = new TranslateTransition(Duration.millis(200), icon);
final double start = 0.0;
final double end = start - 4.0;
translateTransition.setFromY(start);
translateTransition.setToY(end);
translateTransition.setCycleCount(-1);
translateTransition.setAutoReverse(true);
translateTransition.setInterpolator(Interpolator.EASE_BOTH);
translateTransition.play();
}
public enum AnimationType {
BLINK, JUMP, NONE;
};
private void addAnimation() {
switch (type) {
case BLINK:
addBlinkAnimation();
break;
case JUMP:
addJumpAnimation();
break;
case NONE:
break;
default:
break;
}
}
}
here's the main.java
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.MenuButton;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
MenuButton menu = new MenuButton("Bienvenue, Yassine", new ImageView(new Image("http://cdn1.iconfinder.com/data/icons/fs-icons-ubuntu-by-franksouza-/32/google-chrome.png", 20, 20, true, true)));
menu.setCenterShape(true);
Icons btn = new Icons("Notification", createNotification("5"), Icons.AnimationType.JUMP);
Icons btn2 = new Icons("Mails", createNotification("4"), Icons.AnimationType.JUMP);
Icons btn3 = new Icons("Private Messages", createNotification("10"), Icons.AnimationType.JUMP);
menu.getItems().addAll(btn, btn2, btn3);
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
scene.getStylesheets().add(getClass().getResource("notification_icon.css").toExternalForm());
root.getChildren().add(menu);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
private Node createNotification(String number) {
StackPane p = new StackPane();
Label lab = new Label(number);
lab.setStyle("-fx-text-fill:white");
Circle cercle = new Circle(10, Color.rgb(200, 0, 0, .9));
cercle.setStrokeWidth(2.0);
cercle.setStyle("-fx-background-insets: 0 0 -1 0, 0, 1, 2;");
cercle.setSmooth(true);
p.getChildren().addAll(cercle, lab);
return p;
}
}
and the css
.label{
-fx-font-size: 12;
-fx-font-weight: bold;
-fx-text-fill: black;
-fx-padding:5;
}