How spring data elasticsearch use offset and limit to query - spring-data-elasticsearch

How spring data elastisearch use offset and limit to query. I want to use offset and limit param to query page.But I can not find methods support. For Example:
queryBuild.withPageable(PageRequest.of(pageIndex, pageSize));
Page<Content> content = elasticsearchOperations.queryForPage(queryBuild.build(),Content.class);
it could be ok
But I can not found method with offset and limit
queryBuild.withPageable(PageRequest.of(offset, limit));

I have the same problem, so I implemented the following class
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
public class OffsetLimitPageable implements Pageable {
private int offset;
private int page;
private int size;
private Sort sort = Sort.unsorted();
protected OffsetLimitPageable(int offset, int page, int size) {
if (offset < 0) {
throw new IllegalArgumentException("Offset must not be less than zero!");
}
if (page < 0) {
throw new IllegalArgumentException("Page index must not be less than zero!");
}
if (size < 1) {
throw new IllegalArgumentException("Page size must not be less than one!");
}
this.offset = offset;
this.page = page;
this.size = size;
}
public static OffsetLimitPageable of(int offset, int page, int size) {
return new OffsetLimitPageable(offset, page, size);
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#getPageNumber()
*/
#Override
public int getPageNumber() {
return page;
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#getPageSize()
*/
#Override
public int getPageSize() {
return size;
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#getOffset()
*/
#Override
public long getOffset() {
return offset + page * size;
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#getSort()
*/
#Override
public Sort getSort() {
return sort;
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#next()
*/
public Pageable next() {
return of(offset, page + 1, size);
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#previousOrFirst()
*/
public Pageable previousOrFirst() {
return hasPrevious() ? of(offset, page - 1, size) : first();
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#first()
*/
public Pageable first() {
return of(offset, 0, size);
}
/*
* (non-Javadoc)
* #see org.springframework.data.domain.Pageable#hasPrevious()
*/
public boolean hasPrevious() {
return page > 0;
}
}
And, use like this
queryBuild.withPageable(OffsetLimitPageable.of(offset, page, limit));

This is not supported in spring-data-es (or in ANY spring-data project), so you'll have to provide your own custom implementation for the Pageable interface
Take a look here or here and here if you attempt to use the repository variant (extending ElasticsearchRepository<...,...>) and implement your own.
Then perform the query just as you noted, with
PageRequest p = new MyOwnPageRequest(offset, limit);
SearchQuery sq = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withPageable(p)
.build();
Page<SampleEntity> result = elasticsearchTemplate.queryForPage(sq, SampleEntity.class);

Related

Java - Writing method for public int indexOf(T element) in a double linked list

Below I have the int indexOf(T element) method for a double linked list. I need help with the code to make sure it functions properly. The method should return the first occurence of the element in the list or -1 if element is not in the list. Below is the node class it uses. The IUDoubleLinkedList.java class implements IndexedUnsortedList.java which is where the indexOf method comes from. I tried using my indexOf method from my single linked list class but it's not the same so I hope to understand why it would be different and what code is used that is different between the the single and double linked list.
public class IUDoubleLinkedList<T> implements IndexedUnsortedList<T> {
private Node<T> head, tail;
private int size;
private int modCount;
public IUDoubleLinkedList() {
head = tail = null;
size = 0;
modCount = 0;
This is the indexOf(T element) method
#Override
public int indexOf(T element) {
// TODO Auto-generated method stub
return 0;
}
Below is the Node.java class it uses
public class Node<T> {
private Node<T> nextNode;
private T element;
private Node<T> prevNode;
/**
* Creates an empty node.
*/
public Node() {
nextNode = null;
element = null;
}
/**
* Creates a node storing the specified element.
*
* #param elem
* the element to be stored within the new node
*/
public Node(T element) {
nextNode = null;
this.element = element;
setPrevNode(null);
}
/**
* Returns the node that follows this one.
*
* #return the node that follows the current one
*/
public Node<T> getNextNode() {
return nextNode;
}
/**
* Sets the node that follows this one.
*
* #param node
* the node to be set to follow the current one
*/
public void setNextNode(Node<T> nextNode) {
this.nextNode = nextNode;
}
/**
* Returns the element stored in this node.
*
* #return the element stored in this node
*/
public T getElement() {
return element;
}
/**
* Sets the element stored in this node.
*
* #param elem
* the element to be stored in this node
*/
public void setElement(T element) {
this.element = element;
}
#Override
public String toString() {
return "Element: " + element.toString() + " Has next: " + (nextNode != null);
}
public Node<T> getPrevNode() {
return prevNode;
}
public void setPrevNode(Node<T> prevNode) {
this.prevNode = prevNode;
}
}
Check the following code, hope I helped you!
Insert item at head as well as tail end
public void insertItem(T elem) {
/* if head and tail both are null*/
if(head == null || tail == null) {
head = new Node<T>(elem);
tail = new Node<T>(elem);
}else {
Node<T> tempItem = new Node<T>();
tempItem.setElement(elem);
/* insert at head end /*
tempItem.setNextNode(head);
head.setPrevNode(tempItem);
head = tempItem;
Node<T> tempItem1 = new Node<T>();
tempItem1.setElement(elem);
/* append at tail end */
tail.setNextNode(tempItem1);
tempItem1.setPrevNode(tail);
tail = tempItem1;
}
size += 1;
}
Print item from head end
public void printItemsFromHead() {
while(head != null) {
System.out.print(head.getElement()+" --> ");
head = head.getNextNode();
}
}
Print item from tail end
public void printItemsFromTail() {
Node<T> temp = null;
while(tail != null) {
temp = tail;
System.out.print(tail.getElement()+" --> ");
tail = tail.getPrevNode();
}
/*System.out.println();
while(temp != null) {
System.out.print(temp.getElement()+" --> ");
temp = temp.getNextNode();
}*/
}
Implemention of indexOf function
#Override
public int indexOf(T element) {
int result = -1;
int headIndex = 0;
int tailIndex = size;
while(head != null && tail != null) {
if(head.getElement().equals(element)) {
result = headIndex;
break;
}
/*
if(tail.getElement().equals(element)) {
result = tailIndex;
break;
} */
head = head.getNextNode();
tail = tail.getPrevNode();
headIndex += 1;
tailIndex -= 1;
}
return result;
}
Driver class
public class Driver {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> void main(String[] args) {
UDoubleLinkedList uDoubleLinkedList = new UDoubleLinkedList();
uDoubleLinkedList.insertItem(1);
uDoubleLinkedList.insertItem(2);
uDoubleLinkedList.insertItem(3);
uDoubleLinkedList.insertItem(4);
uDoubleLinkedList.insertItem(5);
System.out.println(uDoubleLinkedList.indexOf(1));
}
}

proper video streaming with rxjava

To handle a video stream from a webcam (delivered by opencv) i am considering to use RxJava.
I am hoping to achieve the following:
being able to control the frames per second to be delivered
to be able to handle different inputs - e.g. a life webcam, a video or even a still picture
being able to switch to a picture-by-picture handling under the control of a gui
I have been experimenting a bit with RxJava but i am confused about the debounce, throttleFirst and async operators
Examples like https://stackoverflow.com/a/48723331/1497139 show some code but I am missing more detailed explanation.
Where could I find a decent example for video processing or something similar along the needs mentioned above?
The code below does some non async logic at this time - please let me know if i could build on it:
ImageFetcher
import org.opencv.core.Mat;
import org.opencv.videoio.VideoCapture;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
/**
* fetcher for Images
*
*/
public class ImageFetcher {
// OpenCV video capture
private VideoCapture capture = new VideoCapture();
private String source;
protected int frameIndex;
public int getFrameIndex() {
return frameIndex;
}
/**
* fetch from the given source
*
* #param source
* - the source to fetch from
*/
public ImageFetcher(String source) {
this.source = source;
}
/**
* try opening my source
*
* #return true if successful
*/
public boolean open() {
boolean ret = this.capture.open(source);
frameIndex=0;
return ret;
}
/**
* fetch an image Matrix
*
* #return - the image fetched
*/
public Mat fetch() {
if (!this.capture.isOpened()) {
boolean ret = this.open();
if (!ret) {
String msg = String.format(
"Trying to fetch image from unopened VideoCapture and open %s failed",
source);
throw new IllegalStateException(msg);
}
}
final Mat frame = new Mat();
this.capture.read(frame);
frameIndex++;
return !frame.empty() ? frame : null;
}
#Override
protected void finalize() throws Throwable {
super.finalize();
}
/**
* convert me to an observable
* #return a Mat emitting Observable
*/
public Observable<Mat> toObservable() {
// Resource creation.
Func0<VideoCapture> resourceFactory = () -> {
VideoCapture capture = new VideoCapture();
capture.open(source);
return capture;
};
// Convert to observable.
Func1<VideoCapture, Observable<Mat>> observableFactory = capture -> Observable
.<Mat> create(subscriber -> {
boolean hasNext = true;
while (hasNext) {
final Mat frame = this.fetch();
hasNext = frame!=null && frame.rows()>0 && frame.cols()>0;
if (hasNext) {
String msg = String.format("->%6d:%4dx%d", frameIndex, frame.cols(), frame.rows());
System.out.println(msg);
subscriber.onNext(frame);
}
}
subscriber.onCompleted();
});
// Disposal function.
Action1<VideoCapture> dispose = VideoCapture::release;
return Observable.using(resourceFactory, observableFactory, dispose);
}
}
ImageSubscriber
import org.opencv.core.Mat;
import rx.Subscriber;
public class ImageSubscriber extends Subscriber<Mat> {
public Throwable error;
public int cols = 0;
public int rows=0;
public int frameIndex=0;
public boolean completed = false;
public boolean debug = false;
#Override
public void onCompleted() {
completed = true;
}
#Override
public void onError(Throwable e) {
error = e;
}
#Override
public void onNext(Mat mat) {
cols = mat.cols();
rows = mat.rows();
frameIndex++;
if (cols==0 || rows==0)
System.err.println("invalid frame "+frameIndex);
if (debug) {
String msg = String.format("%6d:%4dx%d", frameIndex, cols, rows);
System.out.println(msg);
}
}
};

How to access properties of node over 2 relations with NEO4J-PHP-OGM

I cant get my head around how to access properties over 2 relationships with the neo4j-php-ogm library.
Say for example I have a "user" node, which connects to MANY "resource" nodes, which in return are each connected to a fixed number of predefined "MetaResource" node. The "resource" nodes have properties and the "MetaResource" nodes have the Meta-Properties of each resource type. How can I know access the properties of the "MetaResource" nodes starting from a "user" node? In Neo4j one such route looks like this:
(user)-[r:HAS_RESOURCE]->(resource)-[m:METARESOURCE]->(metaResource)
My example user entity:
/**
* #OGM\Node(label="User")
*/
class User
{
/**
* #OGM\GraphId()
* #var int
*/
private $id;
/**
* #OGM\Relationship(type="HAS_RESOURCE", direction="OUTGOING", targetEntity="\AppBundle\Entity\Resources", collection=true)
* #var ArrayCollection|\AppBundle\Entity\Resources[]
*/
protected $resources;
/**
* #return \Doctrine\Common\Collections\ArrayCollection|\AppBundle\Entity\Resources[]
*/
public function getResources()
{
return $this->resources;
}
/**
* #return \Doctrine\Common\Collections\ArrayCollection|\AppBundle\Entity\Resources[]
*/
public function getResource($name)
{
foreach($this->resources as $resource){
if($resource->getResourceType() == $name){
return $resource;
break;
}
}
}
/**
* #param AppBundle\Entity\Resources $resources
*/
public function addResource(Resources $resources)
{
if (!$this->resources->contains($resources)) {
$this->resources->add($resources);
}
}
}
My Example Resource Entity:
/**
* #OGM\Node(label="Resources")
*/
class Resources
{
/**
* #OGM\GraphId()
* #var int
*/
protected $id;
/**
* #OGM\Property(type="int")
* #var int
*/
protected $resourcecount;
/**
* #OGM\Relationship(type="METARESOURCE", direction="OUTGOING", targetEntity="\AppBundle\Entity\MetaResource", collection=false)
* #var MetaResource
*/
protected $metaResource;
/**
* #param \AppBundle\Entity\MetaResource $metaResource
*/
public function __construct(MetaResource $metaResource)
{
$this->metaResource = $metaResource;
}
public function getId()
{
return $this->id;
}
public function getResourceCount()
{
return $this->resourcecount;
}
public function setResourceCount($resourcecount)
{
$this->resourcecount = $resourcecount;
}
/**
* #return \AppBundle\Entity\MetaResource
*/
public function getMetaResource()
{
return $this->metaResource;
}
}
And my Example MetaResource Entity:
/**
* #OGM\Node(label="MetaResource")
*/
class MetaResource
{
/**
* #OGM\GraphId()
* #var int
*/
protected $id;
/**
* #OGM\Property(type="string")
* #var string
*/
protected $resourceType;
/**
* #OGM\Property(type="string")
* #var string
*/
protected $name_DE;
/**
* #OGM\Property(type="string")
* #var string
*/
protected $icon;
/**
* #OGM\Property(type="string")
* #var string
*/
protected $iconColour;
/**
* #OGM\Property(type="string")
* #var string
*/
protected $colour;
public function getResourceType()
{
return $this->resourceType;
}
public function getName_DE()
{
return $this->name_DE;
}
public function getIcon()
{
return $this->icon;
}
public function getIconColour()
{
return $this->iconColour;
}
public function getColour()
{
return $this->colour;
}
}
And finally the code from my controller, which sets up the relations:
$metaResource=$em->getRepository(MetaResource::class)->findOneBy('resourceType', 'wood');
$rWood = new Resources($metaResource);
$rWood->setResourceCount(20);
$em->persist($rWood);
$em->flush();
$user->addResource($rWood);
If I now have a look at the Neo4j webconsole, all relationships and nodes are correctly inserted.
Now, if I get the resources of a user with $user->getResources() I successfully get all the resource objects, but the "$metaResource" property is always NULL instead of the anticipated Object of my MetaResource entity. For example if I do:
foreach($user->getResources() as $resource){
var_dump($resource->getMetaResource());
}
Then it outputs only NULLs.
On the other hand, if I directly get a resource object (for example with $resource = $em->getRepository(Resources::class)->findOneById(123) ) and then try to get the connected MetaResource with $resource->getMetaResource() it works. What am I missing?
Cheers
I have made some progress regarding this use case. I'm using now a proxy generator that can handle this use case (this was a big missing part into the lib actually but takes time to implement).
So please test with the latest release 1.0.0-beta7.

Why the bind of the width of TableColumn is not working?

I would like to bind the width of the second column of my TableView with the width of my TableView.
My custom TableView :
public class CustomTableView<T> extends
TableView<ObservableList<Pair<String, Object>>> implements Cloneable {
private static Logger logger = Logger.getLogger(CustomTableView.class);
private double prefWidth; // optionnel
private double minWidth; // optionnel
private double maxWidth; // optionnel
private double height; // optionnel
private List<InfoColumnBean> cols; // optionnel
private ObservableList<ObservableList<Pair<String, Object>>> data; // optionnel
private boolean withContextMenu; // optionnel
private ContextMenu menu; // optionnel
private String title; // obligatoire
private int titleWidth; // optionnel
private Label placeHolder; // optionnel
#SuppressWarnings("unchecked")
public CustomTableView(CustomTableViewBuilder<T> builder) {
super();
// apparence tableau
this.prefWidth = builder.prefWidth;
this.minWidth = builder.minWidth;
this.maxWidth = builder.maxWidth;
this.height = builder.height;
this.title = builder.title;
this.titleWidth = builder.titleWidth;
this.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
this.getStyleClass().add("tableView");
this.setPrefWidth(prefWidth);
this.setMinWidth(minWidth);
this.setMaxWidth(maxWidth);
this.setPrefHeight(height);
this.setEditable(false);
DropShadow ds = new DropShadow();
ds.setOffsetY(3.0);
ds.setOffsetX(3.0);
ds.setColor(Color.DARKGRAY);
this.setEffect(ds);
this.withContextMenu = builder.withContextMenu;
this.menu = builder.menu;
this.placeHolder = builder.placeHolder;
if (placeHolder != null)
this.setPlaceholder(placeHolder);
// colonnes du tableau
this.cols = builder.cols;
if (cols != null) {
for (final InfoColumnBean col : cols) {
#SuppressWarnings("rawtypes")
TableColumn ws_col = null;
if (col.isColumnWithImage()) {
ws_col = new TableColumn<ObservableList<Pair<String, Object>>, Object>(
col.getName());
ws_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<Pair<String, Object>>, Object>, ObservableValue<Object>>() {
#SuppressWarnings("rawtypes")
public ObservableValue<Object> call(
TableColumn.CellDataFeatures<ObservableList<Pair<String, Object>>, Object> data) {
Object value = data.getValue().get(col.getIndex())
.getValue();
return (value instanceof ObservableValue) ? (ObservableValue) value
: new ReadOnlyObjectWrapper<>(value);
}
});
}
if (!col.isColumnWithImage()) {
ws_col = new TableColumn<ObservableList<Pair<String, Object>>, String>(
col.getName());
if (!col.isColumnWithDecimalsManagement())
ws_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<Pair<String, Object>>, String>, ObservableValue<String>>() {
public ObservableValue<String> call(
TableColumn.CellDataFeatures<ObservableList<Pair<String, Object>>, String> data) {
return new ReadOnlyObjectWrapper<>(data
.getValue().get(col.getIndex())
.getKey());
}
});
else {
ws_col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList<Pair<String, Object>>, String>, ObservableValue<String>>() {
public ObservableValue<String> call(
TableColumn.CellDataFeatures<ObservableList<Pair<String, Object>>, String> data) {
// gestion des décimales
NumberFormat df = DecimalFormat.getInstance();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
df.setRoundingMode(RoundingMode.HALF_UP);
String ret = df.format(
Double.parseDouble(data.getValue()
.get(col.getIndex()).getKey()))
.replace(",", ".");
return new ReadOnlyObjectWrapper<>(ret);
}
});
}
}
if (col.getId() != null && !col.getId().equals("")) {
logger.debug("col_name, id = " + col.getName() + " "
+ col.getId());
ws_col.setId(col.getId());
}
ws_col.setPrefWidth(col.getPrefWidth());
ws_col.setMinWidth(col.getMinWidth());
ws_col.setMaxWidth(col.getMaxWidth());
ws_col.getStyleClass().add(col.getStyle());
ws_col.setResizable(col.isResizable());
ws_col.setSortable(col.isSortable());
if (col.getBindPrefWidthWithTable() > 0)
ws_col.prefWidthProperty().bind(
this.widthProperty().subtract(
col.getBindPrefWidthWithTable()));
this.getColumns().add(ws_col);
}
logger.debug("cols size = " + this.getColumns().size());
// données
this.data = builder.data;
if (data != null) {
// style lignes
refresh();
this.setItems(data);
logger.debug("data.size = " + data.size());
} else {
ObservableList<ObservableList<Pair<String, Object>>> items = FXCollections
.observableArrayList();
this.setItems(items);
}
// menu contextuel ?
final CustomTableView<T> current = this;
if (withContextMenu) {
this.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton().equals(
MouseButton.SECONDARY)
&& current.getItems().size() > 0) {
menu.show(current, event.getScreenX(),
event.getScreenY());
}
}
});
}
}
}
/**
* #return titre du contrôle
*
* #since 0.0.8
*/
public String getTitle() {
return title;
}
/**
* #return longueur titre label
*
* #since 0.0.8
*/
public int getTitleWidth() {
return titleWidth;
}
/**
* refresh tableView
*
* #since 0.0.8
*/
public void refresh() {
this.setRowFactory(new Callback<TableView<ObservableList<Pair<String, Object>>>, TableRow<ObservableList<Pair<String, Object>>>>() {
#Override
public TableRow<ObservableList<Pair<String, Object>>> call(
TableView<ObservableList<Pair<String, Object>>> tableView) {
final TableRow<ObservableList<Pair<String, Object>>> row = new TableRow<ObservableList<Pair<String, Object>>>() {
protected void updateItem(
ObservableList<Pair<String, Object>> pair,
boolean empty) {
super.updateItem(pair, empty);
int idx = getIndex();
if (idx >= 0) {
if ((idx % 2) == 0)
getStyleClass().add("ligne1");
else
getStyleClass().add("ligne2");
}
}
};
return row;
}
});
}
#Override
public CustomTableView<T> clone() throws CloneNotSupportedException {
CustomTableView<T> cloneObject = new CustomTableView<T>();
cloneObject.setItems(super.getItems());
return cloneObject;
}
/**
* useful for cloning
*
* #since 0.0.8
*/
public CustomTableView() {
super();
}
/**
*
* Classe : CustomTableViewBuilder
*
* paramètres contrôle
*
* #author fmaupin
*
* #since 0.0.8
*
*/
public static class CustomTableViewBuilder<T> {
private double prefWidth = 200; // optionnel
private double minWidth = 200; // optionnel
private double maxWidth = 200; // optionnel
private double height = 200; // optionnel
private List<InfoColumnBean> cols = null; // optionnel
private ObservableList<ObservableList<Pair<String, Object>>> data = null; // optionnel
private boolean withContextMenu = false; // optionnel
private ContextMenu menu = null; // optionnel
private String title = ""; // obligatoire
private int titleWidth = 0; // optionnel
private Label placeHolder = null; // optionnel
/**
* #param title
* : titre label contrôle
*
* #since 0.0.8
*/
public CustomTableViewBuilder(String title) {
this.title = title;
}
/**
*
* longueur titre contrôle
*
* #param width
* : longueur titre
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> titleWidth(int width) {
this.titleWidth = width;
return this;
}
/**
*
* placeholder
*
* #param value
* : message pour placeholder
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> setPlaceHolder(String value) {
this.placeHolder = new Label(value);
return this;
}
/**
*
* largeurs tableau
*
* #param width
* : toutes largeurs tableau
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> with(double width) {
this.prefWidth = width;
this.minWidth = width;
this.maxWidth = width;
return this;
}
/**
*
* largeur tableau
*
* #param width
* : largeur tableau
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> prefWith(double width) {
this.prefWidth = width;
return this;
}
/**
*
* largeur minimale tableau
*
* #param width
* : largeur tableau
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> minWith(double width) {
this.minWidth = width;
return this;
}
/**
*
* largeur maximale tableau
*
* #param width
* : largeur tableau
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> maxWith(double width) {
this.maxWidth = width;
return this;
}
/**
*
* hauteur tableau
*
* #param height
* : hauteur tableau
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> height(double height) {
this.height = height;
return this;
}
/**
*
* ajouter colonne(s) dans tableau
*
* #param infoColumns
* : informations sur colonnes (nom, index, largeur, largeur
* minimum, largeur maximum, style)
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> addColumns(
List<InfoColumnBean> infoColumns) {
this.cols = infoColumns;
return this;
}
/**
*
* ajouter données dans tableau
*
* #param data
* : données à ajouter
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> addDATA(
ObservableList<ObservableList<Pair<String, Object>>> data) {
this.data = data;
return this;
}
/**
*
* avec menu contextuel ?
*
* #param menu
* : descriptif menu contextuel
*
* #since 0.0.8
*/
public CustomTableViewBuilder<T> withContextMenu(ContextMenu menu) {
this.withContextMenu = true;
this.menu = menu;
return this;
}
/**
* construire contrôle
*
* #since 0.0.8
*/
public CustomTableView<T> build() {
return new CustomTableView<T>(this);
}
}
}
The initialisation of my custom TableView (InfoColumns contains description of columns):
mytable = new CustomTableView.CustomTableViewBuilder<ObservableList<Pair<String, Object>>>(
"")
.setPlaceHolder(
"my message !")
.addColumns(infoColumns).prefWith(width * 0.4f)
.minWith(TABLEVIEW_WIDTH).maxWith(width).height(height * 0.75)
.build();
And my Binding :
mytable.getColumns().get(1).prefWidthProperty().bind(mytable.widthProperty().subtract(385));
Unfortunately it does not work !
If you have a idea ...
Thanks you in advance
Fabrice
Well it does work, follow the example below :
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableViewColumnBind extends Application {
#Override
public void start(Stage stage) throws Exception {
BorderPane borderPane = new BorderPane();
Scene scene = new Scene(borderPane, 500, 500);
String cssFile = getClass().getResource("tableviewgridline.css").toExternalForm();
scene.getStylesheets().add(cssFile);
stage.setScene(scene);
TableView<Integer> table = new TableView<>();
ObservableList<Integer> data = FXCollections.observableArrayList();
for (int i = 0; i < 20; i++) {
data.add(i);
}
table.setItems(data);
for (int i = 0; i < 10; i++) {
TableColumn<Integer,String> column = new TableColumn<>(Integer.toString(i));
column.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().toString()));
table.getColumns().add(column);
}
table.getColumns().get(1).prefWidthProperty().bind(table.widthProperty().subtract(400));
borderPane.setCenter(table);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}

How can i create one play/pause button like youtube in black berry java?

i want to create a play/pause button like youtube in blackberry java,how can we handle two actions with single button i.e when the button is clicked for first time it should paly the audio,and again,if the same button is clicked again the audio should be stopped,how can we handle two actions with single button and how can we change the images like play/ pause?
import java.util.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.Bitmap;
public class CustomImageButtonApp extends UiApplication
{
static Bitmap image;
public static void main(String[] args)
{
CustomImageButtonApp app = new CustomImageButtonApp ();
app.enterEventDispatcher();
}
public CustomImageButtonApp ()
{
final imagebutton img_btn = new imagebutton("",Field.FOCUSABLE, "play.png",
"pause.png", 0x9cbe95);
MainScreen screen=new MainScreen();
pushScreen(screen);
screen.setTitle("title");
screen.add(img_btn);
}
public class CustomImageButton extends Field {
private String _label;
private int _labelHeight;
private int _labelWidth;
private Font _font;
private Bitmap _currentPicture;
private Bitmap _playPicture;
private Bitmap _pausePicture;
int color;
public CustomImageButton (String text, long style ,String playimg, String pauseimg, int color){
super(style);
_playPicture= Bitmap.getBitmapResource( playimg );
_pausePicture=Bitmap.getBitmapResource( pauseimg );
_font = getFont();
_label = text;
_labelHeight = _playPicture.getHeight();
_labelWidth = _pausePicture.getWidth();
this.color = color;
_currentPicture = _playPicture;
}
/**
* #return The text on the button
*/
String getText(){
return _label;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredHeight()
*/
public int getPreferredHeight(){
return _labelHeight;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#getPreferredWidth()
*/
public int getPreferredWidth(){
return _labelWidth;
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#drawFocus(Graphics, boolean)
*/
protected void drawFocus(Graphics graphics, boolean on) {
// Do nothing
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#layout(int, int)
*/
protected void layout(int width, int height) {
setExtent(Math.min( width, getPreferredWidth()),
Math.min( height, getPreferredHeight()));
}
/**
* Field implementation.
* #see net.rim.device.api.ui.Field#paint(Graphics)
*/
protected void paint(Graphics graphics){
// First draw the background colour and picture
graphics.setColor(this.color);
graphics.fillRect(0, 0, getWidth(), getHeight());
graphics.drawBitmap(0, 0, getWidth(), getHeight(), _currentPicture, 0, 0);
// Then draw the text
graphics.setColor(Color.BLACK);
graphics.setFont(_font);
graphics.drawText(_label, 4, 2,
(int)( getStyle() & DrawStyle.ELLIPSIS | DrawStyle.HALIGN_MASK ),
getWidth() - 6 );
}
/**
* Overridden so that the Event Dispatch thread can catch this event
* instead of having it be caught here..
* #see net.rim.device.api.ui.Field#navigationClick(int, int)
*/
protected boolean navigationClick(int status, int time){
if (_currentPicture == _playPicture) {
_currentPicture = _pausePicture;
// invalidate();
} else {
_currentPicture = _playPicture;
//invalidate();
}
//fieldChangeNotify(1);
return true;
}
}
}

Resources