Remove series from vaadin chart 4.0.0 - vaadin8

I want to change number of ListSeries to draw chart on button click.
I am using Vaadin 8.0.1 with Vaadin chart 4.0.0 and Java 8.
Class contains implementation of chart.
package v8.v8;
import java.util.List;
import com.vaadin.addon.charts.Chart;
import com.vaadin.addon.charts.model.ChartType;
import com.vaadin.addon.charts.model.Configuration;
import com.vaadin.addon.charts.model.HorizontalAlign;
import com.vaadin.addon.charts.model.LayoutDirection;
import com.vaadin.addon.charts.model.Legend;
import com.vaadin.addon.charts.model.ListSeries;
import com.vaadin.addon.charts.model.PlotOptionsColumn;
import com.vaadin.addon.charts.model.Series;
import com.vaadin.addon.charts.model.Tooltip;
import com.vaadin.addon.charts.model.VerticalAlign;
import com.vaadin.addon.charts.model.XAxis;
import com.vaadin.addon.charts.model.YAxis;
import com.vaadin.addon.charts.model.style.SolidColor;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
public class GetChartUI {
protected Component getChart() {
VerticalLayout vLayout = new VerticalLayout();
Chart chart = new Chart(ChartType.COLUMN);
Configuration conf = chart.getConfiguration();
conf.setTitle("Total fruit consumption, grouped by gender");
conf.setSubTitle("Source: WorldClimate.com");
XAxis x = new XAxis();
x.setCategories("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
conf.addxAxis(x);
YAxis y = new YAxis();
y.setMin(0);
y.setTitle("Rainfall (mm)");
conf.addyAxis(y);
Legend legend = new Legend();
legend.setLayout(LayoutDirection.VERTICAL);
legend.setBackgroundColor(new SolidColor("#FFFFFF"));
legend.setAlign(HorizontalAlign.LEFT);
legend.setVerticalAlign(VerticalAlign.TOP);
legend.setX(100);
legend.setY(70);
legend.setFloating(true);
legend.setShadow(true);
conf.setLegend(legend);
Tooltip tooltip = new Tooltip();
tooltip.setFormatter("this.x +': '+ this.y +' mm'");
conf.setTooltip(tooltip);
PlotOptionsColumn plot = new PlotOptionsColumn();
plot.setPointPadding(0.2);
plot.setBorderWidth(0);
conf.addSeries(new ListSeries("Tokyo", 49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6,
54.4));
conf.addSeries(
new ListSeries("New York", 83.6, 78.8, 98.5, 93.4, 106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3));
conf.addSeries(
new ListSeries("London", 48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2));
conf.addSeries(
new ListSeries("Berlin", 42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1));
chart.drawChart(conf);
Button button = new Button("Remove series",new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// TODO Auto-generated method stub
Configuration configuration = chart.getConfiguration();
List<Series> sc = configuration.getSeries();
for(Series scq :sc){
//Here i want to remove ListSeries contain name called London
if (scq.getName().equals("London"))
configuration.getSeries().remove(scq);
}
chart.drawChart();
}
});
vLayout.addComponents(chart,button);
return vLayout;
}
}
Above code does not throwing compilation error as configuration.getSeries() return unmodifiable List. But it throwing exception while removing series from list(It is expected due to unmodifiable List).
Any help will be appreciate. I have google whole day but no luck.

However, it simple to remove series from chart. Just get existing series from chart configuration and identify which one you should have to remove. Get reaming on new list or array and set them back to chart configuration.
Button button = new Button("Remove series", new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
// TODO Auto-generated method stub
Configuration configuration = chart.getConfiguration();
List<Series> sc = configuration.getSeries();
Series[] aList = new Series[sc.size()];
int i = 0;
for (Series scq : sc) {
if (!scq.getName().equals("London"))
aList[i++] = scq;
}
chart.getConfiguration().setSeries(aList);
chart.drawChart();
}
});

Related

javafx button to read lines from txt to text fields

I am creating a file object that is used in the open and close functions.
For now I am pointing to a specific location and using a fixed name. The file is populated with lines of data.
The button is on the pane, I have a function to openContact which is supposed to read the text file line by line and send the result to the text field setText method, and this function is called when you click on the button.
There are no syntax errors in the editor, but the clicking the button is not populating the fields in the GUI.
Other than that I am not sure what question to ask or what to search for.
I am attaching my code as it is.
Any hints or guidance toward the appropriate questions to ask or thought process would be appreciated.
package programmingassignment1;
import java.awt.Image;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.*;
//import javafx.scene.layout.StackPane;
//import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.io.*; //input/output
import java.util.Scanner;
//import java.util.*; //scanner, user input
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
public class Address extends Application {
String contactFirst,
contactLast,
spouseFirst,
spouseLast,
street,
city,
state,
zip;
TextField tf_contactFirst = new TextField();
TextField tf_contactLast = new TextField();
TextField tf_spouseFirst = new TextField();
TextField tf_spouseLast = new TextField();
TextField tf_street = new TextField();
TextField tf_city = new TextField();
TextField tf_state = new TextField();
TextField tf_zip = new TextField();
TextArea ta_notes = new TextArea();
ExtensionFilter jpgExtension = new ExtensionFilter("JPG", "*.jpg");
ExtensionFilter pngExtension = new ExtensionFilter("PNG", "*.png");
ExtensionFilter allExtension = new ExtensionFilter("ALL", "*.*");
Rectangle imageBox = new Rectangle(10, 0, 10, 20);
FileChooser fc = new FileChooser();
#Override
public void start(Stage primaryStage){
//modify text area and register actions
ta_notes.setWrapText(true);
ta_notes.setEditable(true);
ta_notes.setPrefColumnCount(12);
ta_notes.setPrefRowCount(3);
//Setting an action for the Clear button
Button bt_cancel = new Button("Cancel");
bt_cancel.setOnAction(e -> {
tf_contactFirst.clear();
tf_contactLast.clear();
tf_spouseFirst.clear();
tf_spouseLast.clear();
tf_street.clear();
tf_city.clear();
tf_state.clear();
tf_zip.clear();
ta_notes.setText(null);
});
//Setting an action for the Open Contact button
Button bt_openContact = new Button("Open Contact");
File file = new File("AddressBook.txt");
bt_openContact.setOnAction(e -> {
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{openContact(file);}
catch(Exception f){f.getMessage();}
}
};
});
//Setting an action for the Save button
Button bt_save = new Button("Save");
bt_save.setOnAction(
new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent e){
try{saveContact(file);}
catch(Exception f){f.getMessage();}
}});
RadioButton rb_male = new RadioButton("Male");
RadioButton rb_female = new RadioButton("Female");
ToggleGroup tgrp = new ToggleGroup();
rb_male.setToggleGroup(tgrp);
rb_female.setToggleGroup(tgrp);
rb_male.setOnAction(e -> {
if(rb_male.isSelected()){int maleContact = 1;}
});
rb_female.setOnAction(e -> {
if(rb_female.isSelected()){int maleContact = 0;}
});
//create combo box and add items as an observable list
String[] x = {"Home Address", "Work Address"};
ComboBox cbo = new ComboBox(FXCollections.observableArrayList(x));
//cbo.setEditable(false);
cbo.setValue("Home Address");
// cbo.setOnAction(e -> {/**____________***/;});
//set imageBox rectangle action
//click in it, choose image, file, its displayed?
//fc is an import or not?
//setOnMouseClicked should work for any node or scene, why not this rect
/*imageBox.setOnMouseClicked((MouseEvent e) -> {
fc.setTitle("Open Image File");
fc.setInitialDirectory(new File("."));
fc.getExtensionFilters().addAll(jpgExtension, pngExtension, allExtension);
fc.setSelectedExtensionFilter(jpgExtension);
File picture = fc.showOpenDialog(primaryStage);
if (picture != null){
rootPane.getChildren().remove(imageBox);
contact.setImageFile(picture.getName());
Image userImage = new Image(picture.getName());
ImageView userView = new ImageView(userImage);
rootPane.getChildren().add(userView);
}
});*/
GridPane rootPane = new GridPane();
rootPane.add(new Label("First Name"), 1, 1);
rootPane.add(tf_contactFirst, 1, 2);
rootPane.add(new Label("Last Name"), 2, 1);
rootPane.add(tf_contactLast, 2, 2);
rootPane.add(new Label("Sex"), 3, 1);
rootPane.add(rb_female, 3, 2);
rootPane.add(rb_male, 3, 3);
rootPane.add(new Label("Spouse's First Name"), 1, 4);
rootPane.add(tf_spouseFirst, 1, 5);
rootPane.add(new Label("Spouse's Last Name"), 2, 4);
rootPane.add(tf_spouseLast, 2, 5);
rootPane.add(cbo, 1, 6);
rootPane.add(new Label("Address Street"), 1, 7);
rootPane.add(tf_street, 1, 8);
rootPane.add(new Label("City"), 1, 9);
rootPane.add(tf_city, 1, 10);
rootPane.add(new Label("State"), 2, 9);
rootPane.add(tf_state, 2, 10);
rootPane.add(new Label("Zip Code"), 3, 9);
rootPane.add(tf_zip, 3, 10);
rootPane.add(imageBox, 4, 1 );
//Label label = new Label();
rootPane.add(new Label("Notes"), 1, 11);
rootPane.add(ta_notes, 1, 12);
rootPane.add(bt_cancel, 2, 13);
rootPane.add(bt_save, 3, 13);
rootPane.add(bt_openContact, 1, 13);
//scene = window (isn't it just easier if someon mentions that?)
Scene scene = new Scene(rootPane, 1000, 500);
primaryStage.setTitle("Address Book");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public void saveContact(File file) throws FileNotFoundException, Exception{ //declaration
//this code might cause a FileNotFoundException
//if it does it creates an exception object of the above type
try{
//PrintWriter output = new PrintWriter (file);
PrintStream output = new PrintStream(file);
output.println(tf_contactFirst.getText());
output.println(tf_contactLast.getText());
output.println(tf_spouseFirst.getText());
output.println(tf_spouseLast.getText());
output.println(tf_street.getText());
output.println(tf_city.getText());
output.println(tf_state.getText());
output.println(tf_zip.getText());
output.close();
}
//what do do with exception
//here the catch clause with create another exception
//that is passed the result of the getMessage() method from the original exception
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
//read same text file you save too
public void openContact (File file) throws FileNotFoundException, Exception{
try{
Scanner read = new Scanner(file);
while(read.hasNextLine()){
//how is a blank field recognized, how are two or three
//consecutive tokens handled
//how do I save the imageFileName
tf_contactFirst.setText(read.nextLine());
tf_contactLast.setText(read.nextLine());
//tf_contactGender.setText(read.nextLine());
tf_spouseFirst.setText(read.nextLine());
tf_spouseLast.setText(read.nextLine());
//tf_spouse_gender.setText(read.nextLine());
tf_street.setText(read.nextLine());
tf_city.setText(read.nextLine());
tf_state.setText(read.nextLine());
tf_zip.setText(read.nextLine());
//ta_notes.setText(read.nextLine());
}
}
catch(FileNotFoundException e){
throw new Exception(e.getMessage());
}
}
}
There are several issues with your code that are causing an issue.
First of all, the lambda statement in your setOnAction() method for bt_openContact is incorrect. The openContact() method is never actually being called.
You can correct that with either passing a new EventHandler directly:
bt_openContact.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
}
});
Or using a properly-formatted lamda statement:
bt_openContact.setOnAction(event -> {
try {
openContact(file);
} catch (Exception e) {
e.printStackTrace();
}
});
It appears you were trying to do both. :)
Note also the catch block. Your code is simply calling f.getMessage(), which returns a String. But you don't actually do anything with that String so even if there are errors, you wouldn't see them.
Instead, you should call f.printStackTrace() to actually print any exceptions to the console.
Unrelated Note: Please look into the Java Naming Conventions and stick to them.
Zephir's answer is completely correct.
To answer your question as to hints and guidance:
always, if possible think " why is this here? is there a reason for it? do i need it? " - this will hopefully prevent dead code like : " catch(Exception f){f.getMessage();} "
learn how to use debugers.
It looks like you're trying to figure out how a programming language works, and you probably have some prior experience with other programming languages. Whenever you attempt this, it's a good idea to follow learning trails such as the ones available at https://docs.oracle.com/javase/tutorial/
This is especially important as the more experience in different programming languages you have, the more things start to look the same when in fact they're completely different. Spending 3 hours doing simple tutorials such as these will spare you days of frustration trying to figure out what the hell is going on.
For some reason this looks to me like someone trying to write code directly in notepad or some text editing software. Don't. Use an IDE (netbeans, eclipse, etc.). These come with formatting tools and debuggers which would allow you to find simple issues such as these in less time than it took me to write this answer.

error in projecting a shapefile from epsg:4326 to epsg:32056

I have been trying to change the projection of Shapefile from one coordinate reference system to other. The shapefile I have used has EPSG:4326 as its reference system and I need to change it to EPSG:32056.
I am using Geotools API-20.0 for the same.
I have already tried various methods available in the geotools like using ReprojectingFeatureCollection, use of JTS, use of Query API to convert the shapefile directly to the other coordinate reference system
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.SwingWorker;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFactorySpi;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Query;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.referencing.CRS;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.referencing.factory.gridshift.GridShiftLocator;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.JProgressWindow;
import org.geotools.swing.action.SafeAction;
import org.geotools.swing.data.JFileDataStoreChooser;
import org.locationtech.jts.geom.Envelope;
import org.opengis.feature.Feature;
import org.opengis.feature.FeatureVisitor;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.FeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.util.ProgressListener;
import com.vividsolutions.jts.geom.Geometry;
public class CRSLab {
private File sourceFile;
private SimpleFeatureSource featureSource;
private MapContent map;
public static void main(String[] args) throws Exception {
CRSLab lab = new CRSLab();
lab.displayShapefile();
}
// docs end main
/**
* This method:
* <ol type="1">
* <li>Prompts the user for a shapefile to display
* <li>Creates a JMapFrame with custom toolbar buttons
* <li>Displays the shapefile
* </ol>
*/
// docs start display
private void displayShapefile() throws Exception {
sourceFile = JFileDataStoreChooser.showOpenFile("shp", null);
if (sourceFile == null) {
return;
}
FileDataStore store = FileDataStoreFinder.getDataStore(sourceFile);
featureSource = store.getFeatureSource();
// Create a map context and add our shapefile to it
map = new MapContent();
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
map.layers().add(layer);
// Create a JMapFrame with custom toolbar buttons
JMapFrame mapFrame = new JMapFrame(map);
mapFrame.enableToolBar(true);
mapFrame.enableStatusBar(true);
JToolBar toolbar = mapFrame.getToolBar();
toolbar.addSeparator();
toolbar.add(new JButton(new ValidateGeometryAction()));
toolbar.add(new JButton(new ExportShapefileAction()));
// Display the map frame. When it is closed the application will exit
mapFrame.setSize(800, 600);
mapFrame.setVisible(true);
}
// docs end display
// docs start export
private void exportToShapefile() throws Exception {
SimpleFeatureType schema = featureSource.getSchema();
JFileDataStoreChooser chooser = new JFileDataStoreChooser("shp");
chooser.setDialogTitle("Save reprojected shapefile");
chooser.setSaveFile(sourceFile);
int returnVal = chooser.showSaveDialog(null);
if (returnVal != JFileDataStoreChooser.APPROVE_OPTION) {
return;
}
File file = chooser.getSelectedFile();
if (file.equals(sourceFile)) {
JOptionPane.showMessageDialog(null, "Cannot replace " + file);
return;
}
// set up the math transform used to process the data
CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
CoordinateReferenceSystem worldCRS = CRS.decode("EPSG:32056", true);// map.getCoordinateReferenceSystem();
boolean lenient = true; // allow for some error due to different datums
MathTransform transform = CRS.findMathTransform(dataCRS, worldCRS, lenient);
// grab all features
SimpleFeatureCollection featureCollection = featureSource.getFeatures();
// And create a new Shapefile with a slight modified schema
DataStoreFactorySpi factory = new ShapefileDataStoreFactory();
Map<String, Serializable> create = new HashMap<String, Serializable>();
create.put("url", file.toURI().toURL());
create.put("create spatial index", Boolean.TRUE);
DataStore dataStore = factory.createNewDataStore(create);
SimpleFeatureType featureType = SimpleFeatureTypeBuilder.retype(schema, worldCRS);
dataStore.createSchema(featureType);
String createdName = dataStore.getTypeNames()[0];
// carefully open an iterator and writer to process the results
Transaction transaction = new DefaultTransaction("Reproject");
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(createdName,
transaction);
SimpleFeatureIterator iterator = featureCollection.features();
try {
int counter = 0;
while (iterator.hasNext()) {
// copy the contents of each feature and transform the geometry
SimpleFeature feature = iterator.next();
SimpleFeature copy = writer.next();
org.locationtech.jts.geom.Geometry geometry = (org.locationtech.jts.geom.Geometry) feature
.getDefaultGeometry();
org.locationtech.jts.geom.Geometry geometry2 = JTS.transform(geometry, transform);
System.out.println(geometry.isSimple() && geometry2.isSimple());
// if (geometry2.isValid()) {
copy.setAttributes(feature.getAttributes());
counter++;
copy.setDefaultGeometry(geometry2);
writer.write();
// }
}
transaction.commit();
System.out.println("valid geometries : " + counter);
JOptionPane.showMessageDialog(null, "Export to shapefile complete");
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
JOptionPane.showMessageDialog(null, "Export to shapefile failed");
} finally {
writer.close();
iterator.close();
transaction.close();
}
}
// docs end export
// docs start validate
private int validateFeatureGeometry(ProgressListener progress) throws Exception {
final SimpleFeatureCollection featureCollection = featureSource.getFeatures();
// Rather than use an iterator, create a FeatureVisitor to check each
// fature
class ValidationVisitor implements FeatureVisitor {
public int numInvalidGeometries = 0;
public void visit(Feature f) {
SimpleFeature feature = (SimpleFeature) f;
Geometry geom = (Geometry) feature.getDefaultGeometry();
if (geom != null && !geom.isValid()) {
numInvalidGeometries++;
System.out.println("Invalid Geoemtry: " + feature.getID());
}
}
}
ValidationVisitor visitor = new ValidationVisitor();
// Pass visitor and the progress bar to feature collection
featureCollection.accepts(visitor, progress);
return visitor.numInvalidGeometries;
}
// docs end validate
// docs start export action
class ExportShapefileAction extends SafeAction {
ExportShapefileAction() {
super("Export...");
putValue(Action.SHORT_DESCRIPTION, "Export using current crs");
}
public void action(ActionEvent e) throws Throwable {
exportToShapefile();
}
}
// docs end export action
/**
* This class performs the task of checking that the Geometry of each
* feature is topologically valid and reports on the results. It also
* supplies the name and tool tip.
*/
// docs start validate action
class ValidateGeometryAction extends SafeAction {
ValidateGeometryAction() {
super("Validate geometry");
putValue(Action.SHORT_DESCRIPTION, "Check each geometry");
}
public void action(ActionEvent e) throws Throwable {
int numInvalid = validateFeatureGeometry(null);
String msg;
if (numInvalid == 0) {
msg = "All feature geometries are valid";
} else {
msg = "Invalid geometries: " + numInvalid;
}
JOptionPane.showMessageDialog(null, msg, "Geometry results", JOptionPane.INFORMATION_MESSAGE);
}
}
// docs end validate action
}
The output obtained after doing projection using Geotools are a lot different than what I used to get from ArcMap of esri. Is there any other transformation that I should perform.
When I try this (with v22.x) all I get is an error as too many points are outside the valid projection error. This is because you are taking a map of the world and reprojecting it to a CRS designed for Wyoming.
It seems that ESRI are being "helpful" and clipping your output to the area of validity (assuming you meant something other than EPSG:32056). GeoTools assumes that you know what you are doing and doesn't do that, which is why you have all the countries of the world shown in that map.
Here is the output for just the USA, which suggests that the ESRI image you show is a different projection again (look at the 49th parallel).

Javafx Collision Detection inTimeLine

I am using timeline for animating lines but I can't detect collisions.
Here is a short example of what I am trying to do basically.
Line line = new Line(100, 200, 200, 200);
Line line1= new Line(350,50,350,300);
Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(1.5), new KeyValue(line.endXProperty(), 400))
);
animation.setCycleCount(1);
animation.play();
if(line.getBoundsInParent().intersects(line1.getBoundsInParent())){
System.out.println("Collision!");
}
Pane root = new Pane(line);
root.getChildren().add(line1);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
I used some other codes,method,ideas that I found in stackoverflow. Like following one:
Bounds bounds = line.getLayoutBounds();
Shape intersect = Shape.intersect(line, line1);
boolean intersects = intersect.getBoundsInLocal().getWidth() != -1;
System.out.println("Intersects: " + intersects);
if(intersect.getBoundsInLocal().getWidth() != -1)
{
System.out.println("This object can overlap other the other object!");
System.out.print("Collision detected!");
}
else
{
intersect.getBoundsInLocal().getWidth();
System.out.print("Collision not detected!");
}
And some variaions of this code.
Any idea would help
In this case, the "collision" (first time the lines intersect) is when line.endX reaches 350.
So you can simply do:
BooleanBinding intersecting = line.endXProperty().greaterThanOrEqualTo(350);
intersecting.addListener((obs, wasIntersecting, isNowIntersecting) -> {
System.out.println("Collision!");
});
i.e.:
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.binding.BooleanBinding;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;
public class AnimatedLine extends Application {
#Override
public void start(Stage primaryStage) {
Line line = new Line(100, 200, 200, 200);
Line line1= new Line(350,50,350,300);
BooleanBinding intersecting = line.endXProperty().greaterThanOrEqualTo(350);
intersecting.addListener((obs, wasIntersecting, isNowIntersecting) -> {
System.out.println("Collision!");
});
Timeline animation = new Timeline(
new KeyFrame(Duration.seconds(1.5), new KeyValue(line.endXProperty(), 400))
);
animation.setCycleCount(1);
animation.play();
Pane root = new Pane(line);
root.getChildren().add(line1);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
In general, detecting whether or not two line segments intersect might be a little harder than the case where one is horizontal and one vertical, but you can always solve the equations pretty easily and do something similar to this.

PdfTextFormField - 2 synchron Fields - How to fill in an initial value? - iText 7.1.0 for Java

At the moment I'm writing a couple of evaluatuation programs with iText.
I have an issue with 2 fields which should always have the same value (2 represantations of 1 field).
In the final version these fields are on different pages at an arbitrary
position.
Setting the value with field.SetValue gives an error. Setting the value with
widget1.setContents does nothing.
Has someone an idea how to solve this problem?
Thanks, Dirk
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.forms.fields.PdfTextFormField;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.annot.PdfWidgetAnnotation;
public class problem2 {
public static void main(String[] args) throws IOException {
String fnPdf = "results/problem2.pdf";
PdfWriter writer = new PdfWriter(fnPdf);
PdfDocument pdf = new PdfDocument(writer);
PdfPage page = pdf.addNewPage();
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
PdfTextFormField field = PdfFormField.createText(pdf);
field.setFieldName("fName");
// field.setValue("test"); // produces an error
Rectangle rect1 = new Rectangle(40, 200, 150, 20);
PdfWidgetAnnotation widget1 = new PdfWidgetAnnotation(rect1);
widget1.setContents("test"); // no error but does'nt work
page.addAnnotation(widget1);
Rectangle rect2 = new Rectangle(240, 200, 150, 20);
PdfWidgetAnnotation widget2 = new PdfWidgetAnnotation(rect2);
widget2.setContents("test"); // no error but does'nt work
page.addAnnotation(widget2);
form.addField(field, page);
field.addKid(widget1);
field.addKid(widget2);
pdf.close();
Desktop.getDesktop().open(new File(fnPdf));
}
}
You need to change the order of the operations you perform a little bit. #mkl is correct in that you first have to set up the structure and then change the value of a field.
If you do this you don't need to use setContents and calling setValue is enough.
Also, make sure that the widgets are indirect objects: widget.makeIndirect(pdf);
The full code snippet that produces the desired field with two widgets that share field's value:
PdfWriter writer = new PdfWriter(fnPdf);
PdfDocument pdf = new PdfDocument(writer);
PdfPage page = pdf.addNewPage();
PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
PdfTextFormField field = PdfFormField.createText(pdf);
field.setFieldName("fName");
Rectangle rect1 = new Rectangle(40, 200, 150, 20);
PdfWidgetAnnotation widget1 = new PdfWidgetAnnotation(rect1);
widget1.makeIndirect(pdf);
page.addAnnotation(widget1);
field.addKid(widget1);
Rectangle rect2 = new Rectangle(240, 200, 150, 20);
PdfWidgetAnnotation widget2 = new PdfWidgetAnnotation(rect2);
widget2.makeIndirect(pdf);
page.addAnnotation(widget2);
field.addKid(widget2);
field.setValue("test");
form.addField(field, page);
pdf.close();

JavaFX "quickfixes" with tooltips and hyperlinks

does JavaFX provide something like Eclipse Quickfixes? Meaning that you hover over a thing that is broken and got some solutions for it that you can apply immediately.
I know that there are tooltips but they can only contain text, I would need something clickable. Another solution would be something like Dialogs, but I don't want to open another window. I want it to appear on the current stage.
Any suggestions?
Edit: to make it clear, I want to adopt the concept of eclipse quickfixes onto a JavaFX based application, maybe showing a "quickfix" when hovering over a circle instance. I don't want to check any (java/javafx) source code.
Edit2: I've got a hyperlink on a tooltip now:
HBox box = new HBox();
Tooltip tooltip = new Tooltip();
tooltip.setText("Select an option:");
tooltip.setGraphic(new Hyperlink("Option 1"));
Tooltip.install(box, tooltip);
I've got three new problems now:
How to make the tooltip not disappear when leaving the HBox and staying there when entering the mouse into the tooltip?
How to add mulitple graphics / hyperlinks? Is it even possible?
How to first show the text and then, in a new line, display the graphics?
Thanks in advance!
You can add any node to a tooltip using the setGraphic() method. Here is a simple example demonstrating using a tooltip for "quick fix" functionality:
import java.util.Random;
import javafx.application.Application;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TooltipWithQuickfix extends Application {
#Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
textField.pseudoClassStateChanged(PseudoClass.getPseudoClass("invalid"), true);
textField.setTextFormatter(new TextFormatter<Integer>(c -> {
if (c.getText().matches("\\d*")) {
return c ;
}
return null ;
}));
textField.textProperty().isEmpty().addListener((obs, wasEmpty, isNowEmpty) ->
textField.pseudoClassStateChanged(PseudoClass.getPseudoClass("invalid"), isNowEmpty));
Tooltip quickFix = new Tooltip();
Hyperlink setToDefault = new Hyperlink("Set to default");
Hyperlink setToRandom = new Hyperlink("Set to random");
setToDefault.setOnAction(e -> {
textField.setText("42");
quickFix.hide();
});
Random rng = new Random();
setToRandom.setOnAction(e -> {
textField.setText(Integer.toString(rng.nextInt(100)));
quickFix.hide();
});
VBox quickFixContent = new VBox(new Label("Field cannot be empty"), setToDefault, setToRandom);
quickFixContent.setOnMouseExited(e -> quickFix.hide());
quickFix.setGraphic(quickFixContent);
textField.setOnMouseEntered(e -> {
if (textField.getText().isEmpty()) {
quickFix.show(textField, e.getScreenX(), e.getScreenY());
}
});
VBox root = new VBox(textField);
root.getStylesheets().add("style.css");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
with the stylesheet (style.css):
.root {
-fx-alignment: center ;
-fx-padding: 24 10 ;
}
.text-field:invalid {
-fx-control-inner-background: #ff7979 ;
-fx-focus-color: red ;
}

Resources