Can't paint an image after choosing it from JFileChooser - image

Good evening. I have read a lot of topics here on stackoverflow or even internet but I can't find the solution to my problem.
I have an interface like this:
When I click on "Load Image A", I can choose the image that I want. Next I want to paint this image under the JLabel "Image A". But it doesn't want to show up.
Here is the code I wrote:
package projet;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class MonPanelImage extends JPanel{
private static final long serialVersionUID = -8267224342030244581L;
private BufferedImage image;
public MonPanelImage(File adresse)
{
try{
image = ImageIO.read(adresse);
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponents(g);
System.out.println("paint");
if(image != null){
g.drawImage(image, 20, 20, this);
}
}
}
and here is where I call it:
//panel image. This is my second panel which will be for the images
final JPanel second = new JPanel(new BorderLayout());
//panel button. This is the third panel for the buttons
rows = 0;
cols = 3;
hgap = 5;
vgap = 0;
JPanel third = new JPanel(new GridLayout(rows,cols,hgap,vgap));
//buttons
JButton boutonLoad1 = new JButton("Load image A");
boutonLoad1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int retour = fc.showDialog(frame, "Charger l'image");
if(retour == JFileChooser.APPROVE_OPTION){
String pathImage1 = fc.getSelectedFile().getAbsolutePath();
path1 = pathImage1;
File file = fc.getSelectedFile();
MonPanelImage panelImage1 = new MonPanelImage(file);
second.add(panelImage1, BorderLayout.WEST);
second.revalidate();
second.repaint();
}
}
});
At the very end, i add the 3 panels to my frame and set the frame to visible.
But I can't paint an image. Maybe I'm not doing it properly. Can someone help me please?
Thanks

super.paintComponents(g);
First of all it should be super.paintComponent(g), without the "s".
second.add(panelImage1, BorderLayout.WEST);
You are adding your image to a component using a BorderLayout. The BorderLayout will respect the width of your component, which is 0, so there is nothing to paint.
Whenever, you do custom painting you need to override the getPreferredSize() method to return the size of your component so the layout manager can do its job.
However, an easier solution is to just use a JLabel with an Icon. There is no need to do custom painting when you are painting the image at its real size.

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.

How to make a SWT window/shell and all the components on it adjustable?

So I have created windows/shells with buttons in an application but I want everything to resize when expanded and not to stay in one corner. I have used SWT and window builder to achieve this I used Absolute layout and now when I press full screen it is all in one corner how could I make this aesthetically pleasing so all the buttons and labels expand as well?
Please take a look at Standard layouts in SWT. Refer How to position your widgets and Understanding Layouts.
For Example below is a sample code where I have created 2 labels and 2 text in a Grid Layout which will FILL horizontally when you resize. You can change it according to your needs.
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class SampleApplication
{
protected Shell shell;
private Text text;
private Text text_1;
/**
* Launch the application.
* #param args
*/
public static void main(final String[] args)
{
try
{
SampleApplication window = new SampleApplication();
window.open();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open()
{
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents()
{
shell = new Shell();
shell.setSize(450, 224);
shell.setText("SWT Application");
shell.setLayout(new GridLayout(2, false));
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setText("Name");
lblNewLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
text = new Text(shell, SWT.BORDER);
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Label lblNewLabel_1 = new Label(shell, SWT.NONE);
lblNewLabel_1.setText("ID");
lblNewLabel_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
text_1 = new Text(shell, SWT.BORDER);
text_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
}
}

How to populate a tableview cell with an image from Sqlite database in JavaFX?

I am trying to populate a tableView cell with an image stored on a Sqlite database using JavaFX. I have found some really good information on here and feel like I am getting pretty close. If there is no image I would like it to keep the constraints to make the cells the same size always. The images stored on the database are 300x300, but the rows will be much smaller. So far the code I have is :
public void buildDataAseptic(){
listNum = 1;
data = FXCollections.observableArrayList();
try{
String SQL = "Select * from aseptic_parts_list"; //Order By id
ResultSet rs = con.createStatement().executeQuery(SQL);
while(rs.next()){
Part cm = new Part();
cm.id.set(listNum++);
if (rs.getBlob("image") != null ) {
Blob blob = rs.getBlob("image");
byte[] ndata = blob.getBytes(1, (int) blob.length());
image = new Image(new ByteArrayInputStream(ndata));
ImageView imageView = new ImageView();
imageView.setImage(image);
imageView.setFitWidth(70);
imageView.setFitHeight(80);
cm.image.set(image);
}
cm.vendor_part_number.set(rs.getString("vendor_part_number"));
cm.description.set(rs.getString("description"));
cm.quantity.set(rs.getInt("quantity"));
cm.vendor_name.set(rs.getString("vendor_name"));
cm.model_number.set(rs.getString("model_number"));
cm.equipment_id.set(rs.getString("equipment_id"));
data.add(cm);
}
tableView.setItems(data);
}
catch(Exception e){
e.printStackTrace();
System.out.println("Error on Building Data" + e.getMessage());
}
filterData();
//filterEquipIDData();
}
this is just one particular method that is called from a comboBox. All of the other data is populating fine in the table except the image. In the initialize() method I have the columns set up as:
assert tableView != null;
idCol.setCellValueFactory(
new PropertyValueFactory<Part, Integer>("id"));
imgCol.setCellValueFactory(
new PropertyValueFactory<Object,ImageView>("image"));
pnCol.setCellValueFactory(
new PropertyValueFactory<Part,String>("vendor_part_number"));
descCol.setCellValueFactory(
new PropertyValueFactory<Part,String>("description"));
quantityCol.setCellValueFactory(
new PropertyValueFactory<Part,Integer>("quantity"));
venCol.setCellValueFactory(
new PropertyValueFactory<Part,String>("vendor_name"));
mnCol.setCellValueFactory(
new PropertyValueFactory<Part,String>("model_number"));
equipmentIDCol.setCellValueFactory(
new PropertyValueFactory<Part,String>("equipment_id"));
The Part class where the image object is stored is:
public SimpleObjectProperty<Image> image = new SimpleObjectProperty<>();
public Object getImage() {
return image.get();
}
I have been fiddling with this for a few days now and feel pretty close, just no cigar, please help and thanks!
Here is an example for populating TableView cells with images.
The key to the solution is to set the cell value factory and the cell factory appropriately:
TableColumn<Fish, Image> imageColumn = new TableColumn<>("Picture");
imageColumn.setCellValueFactory(new PropertyValueFactory<>("image"));
imageColumn.setCellFactory(param -> new ImageTableCell<>());
Where the ImageTableCell class contains an ImageView as the graphic for the cell and updates the ImageView as the underlying image data changes:
private class ImageTableCell<S> extends TableCell<S, Image> {
final ImageView imageView = new ImageView();
ImageTableCell() {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Image item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
imageView.setImage(null);
setText(null);
setGraphic(null);
}
imageView.setImage(item);
setGraphic(imageView);
}
}
One thing to note about this implementation is that it assumes that all images are loaded up into the underlying data structure for the table. This means that if you had a lot of rows in the table, you would be consuming massive amounts of data as all images would be loaded into memory. An alternate solution would be for the underlying data structure just to store the address (url) of the image rather than the image data itself, then load up the image in the cell factory (possibly via an LRU cache mechanism). The trade-off between the different approaches, is speed of operation of the GUI and resources consumed as the user interacts (which is what the all in-memory approach here optimizes for), versus a slower GUI but reduced memory footprint (which is what dymanically loading images in the updateItem call would optimize for). In general, I feel it is best to try to keep the speed of the updateItem call very quick, which is why the solution is presented as is.
I won't supply a sample which also integrates SQLLite as I have no knowledge of that technology, so further integration of the solution with a database system is left up to the reader.
Complete Code
import javafx.application.Application;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.*;
import javafx.stage.Stage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ImageTable extends Application {
#Override
public void start(Stage stage) {
List<Fish> fish = Arrays.stream(fishData)
.map(data -> new Fish(data[0], new Image(data[1])))
.collect(Collectors.toList());
TableView<Fish> tableView = new TableView<>(FXCollections.observableList(fish));
TableColumn<Fish, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
tableView.getColumns().add(nameColumn);
TableColumn<Fish, Image> imageColumn = new TableColumn<>("Picture");
imageColumn.setCellValueFactory(new PropertyValueFactory<>("image"));
imageColumn.setCellFactory(param -> new ImageTableCell<>());
tableView.getColumns().add(imageColumn);
stage.setScene(new Scene(tableView));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
// image license: linkware - backlink to http://www.fasticon.com
private static final String[][] fishData = {
{ "Blue Fish", "http://icons.iconarchive.com/icons/fasticon/fish-toys/128/Blue-Fish-icon.png" },
{ "Red Fish", "http://icons.iconarchive.com/icons/fasticon/fish-toys/128/Red-Fish-icon.png" },
{ "Yellow Fish", "http://icons.iconarchive.com/icons/fasticon/fish-toys/128/Yellow-Fish-icon.png" },
{ "Green FIsh", "http://icons.iconarchive.com/icons/fasticon/fish-toys/128/Green-Fish-icon.png" }
};
private class ImageTableCell<S> extends TableCell<S, Image> {
final ImageView imageView = new ImageView();
ImageTableCell() {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Image item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
imageView.setImage(null);
setText(null);
setGraphic(null);
}
imageView.setImage(item);
setGraphic(imageView);
}
}
public static final class Fish {
private ReadOnlyStringWrapper name;
private ReadOnlyObjectWrapper<Image> image;
public Fish(String name, Image image) {
this.name = new ReadOnlyStringWrapper(name);
this.image = new ReadOnlyObjectWrapper<>(image);
}
public String getName() {
return name.get();
}
public ReadOnlyStringProperty nameProperty() {
return name.getReadOnlyProperty();
}
public Image getImage() {
return image.get();
}
public ReadOnlyObjectProperty<Image> imageProperty() {
return image.getReadOnlyProperty();
}
}
}
Thank you very much jewelsea! I ended up doing what you said, creating another folder to hold the images and using a url to reference the pictures in the folder. The code I used is:
if(rs.getString("image") != null) {
Image img = new Image(rs.getString("image"));
ImageView imageView = new ImageView();
imageView.setImage(img);
cm.image.set(imageView);
imageView.setFitWidth(130);
imageView.setFitHeight(100);
} else {
Image img = new Image("/img/NoImageFound.png");
ImageView imageView = new ImageView();
imageView.setImage(img);
cm.image.set(imageView);
imageView.setFitWidth(130);
imageView.setFitHeight(100);
}
This code queries the database for the image and if there is none there it uses an image i created for image not found. I did this because it was shortening my database results to only queries that had an image, the else shows all results from the database now. It is good to know that this will make it faster. I am building a parts database for my work with listeners for filtering parts, and that might have been too slow once the database gets really big to have all the parts directly stored on the database. Your help has sent me in the right direction, thanks a million!

JavaFX button background image

I have problem with setting backgroundImage on button in JavaFX.
Image newGame = new Image("File:/CSS/nova_hra.png");
BackgroundImage newGameBgr = new BackgroundImage(newGame, null, null, null, null);
Button buttonNewGame = new Button("Nová Hra");
Button buttonLoadGame = new Button("Načíst Hru");
Button buttonStatistics = new Button("Statistiky");
Button buttonExit = new Button("Konec");
buttonNewGame.setGraphic(new ImageView(newGame));
//buttonNewGame.setBackground(new Background(newGameBgr));
buttonExit.setMinHeight(40);
buttonLoadGame.setMinHeight(40);
buttonNewGame.setMinHeight(40);
buttonStatistics.setMinHeight(40);
buttonExit.setMinWidth(120);
buttonLoadGame.setMinWidth(120);
buttonNewGame.setMinWidth(120);
buttonStatistics.setMinWidth(120);
This does nothing with the buttonNewGame. Every time I tryed to load image with this
Image image = new Image(getClass().getResourceAsStream("a.png"));
I got runTime exception. When I used
Image image = new Image(getClass().getResourceAsStream("a.png"));
the whole image disapeard.
You can do it via css. If your background.jpg is in a package testing, simply do this:
package testing;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Pane root = new Pane();
Button button = new Button( "Click me!");
button.setStyle("-fx-background-image: url('/testing/background.jpg')");
root.getChildren().add(button);
Scene scene = new Scene(root, 800, 400);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
If you don't want to use css, you could do it like this:
BackgroundImage backgroundImage = new BackgroundImage( new Image( getClass().getResource("/testing/background.jpg").toExternalForm()), BackgroundRepeat.NO_REPEAT, BackgroundRepeat.NO_REPEAT, BackgroundPosition.DEFAULT, BackgroundSize.DEFAULT);
Background background = new Background(backgroundImage);
Button button = new Button( "Click me!");
button.setBackground(background);

How to get position of an item in ListView in JavaFX?

If I create a ListView in JavaFX like this:
ObservableList<String> elements = FXCollections.observableArrayList("John", "Doe");
ListView<String> lView = new ListView<String>(elements);
What I want to do is draw a line starting from the end of a row in the ListView, say from "John"
To do this, I need the location(x,y) of the row "John". Is it possible to get the location?
Update
This is a sample interface that I got using Swing and Piccolo2D. However, using that library is painful. I am wondering if I can do the same in JavaFX
It is possible, but it may not be as straight forward as you hoped. In order to determine the layout coordinates for a particular Cell within a ListView (or TableView/TreeView) you need to have access to that particular Cell object. The best way (and maybe only way in JavaFX 2.2) is to provide the container with a custom Cell and CellFactory that exposes each Cell. How you expose the Cell depends on what your triggers are for drawing the line.
Bases on your illustration, you'll need access to each cell once the ListViews are populated. You can do this with a List<ListCell<String>> field in the CellFactory. I'll mention one caveat here about ListCells. The ListViewSkin will reuse Cells whenever possible. That means that if you are going to try to populate and connect a list that ends up scrolling, then keeping your lines in the right place will be much more difficult. I'd recommend trying to ensure that all your list items fit on screen.
Below is an example with some notes in the comments. Take note that getting the correct coordinates for drawing your Line will probably require calculating the offset of your SceneGraph which I didn't do in this example.
package listviewcellposition;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Callback;
public class ListViewCellPosition extends Application {
// CustomCellFactory for creating CustomCells
public class CustomCellFactory implements
Callback<ListView<String>, ListCell<String>> {
List<ListCell<String>> allCells = new ArrayList<>();
#Override
public ListCell<String> call(final ListView<String> p) {
final CustomCell cell = new CustomCell();
allCells.add(cell);
return cell;
}
public List<ListCell<String>> getAllCells() {
return allCells;
}
}
// CustomCell is where the exposure occurs. Here, it's based on the
// Cell being selected in the ListView. You could choose a different
// trigger here but you'll need to explore.
public class CustomCell extends ListCell<String> {
// General display stuff
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setText(item == null ? "" : item);
setGraphic(null);
}
}
}
#Override
public void start(Stage primaryStage) {
// This pane will contain the lines after they are created.
// I set it into an AnchorPane to avoid having to deal with
// resizing.
Pane linePane = new Pane();
AnchorPane pane = new AnchorPane();
pane.setPrefSize(100, 250);
AnchorPane.setBottomAnchor(linePane, 0.0);
AnchorPane.setLeftAnchor(linePane, 0.0);
AnchorPane.setRightAnchor(linePane, 0.0);
AnchorPane.setTopAnchor(linePane, 0.0);
pane.getChildren().add(linePane);
ListView<String> lView = new ListView<>();
lView.setPrefSize(100, 250);
CustomCellFactory lCellFactory = new CustomCellFactory();
lView.setCellFactory(lCellFactory);
ListView<String> rView = new ListView<>();
rView.setPrefSize(100, 250);
CustomCellFactory rCellFactory = new CustomCellFactory();
rView.setCellFactory(rCellFactory);
lView.getItems().addAll("Bill", "Doctor", "Steve", "Joanne");
rView.getItems().addAll("Seuss", "Rowling", "King", "Shakespeare");
HBox root = new HBox();
root.getChildren().addAll(lView, pane, rView);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
connectCells(lCellFactory, "Bill", rCellFactory, "Shakespeare", linePane);
connectCells(lCellFactory, "Doctor", rCellFactory, "Seuss", linePane);
connectCells(lCellFactory, "Steve", rCellFactory, "King", linePane);
connectCells(lCellFactory, "Joanne", rCellFactory, "Rowling", linePane);
}
// Looks up the ListCell<> for each String and creates a Line
// with the coordinates from each Cell. The calculation is very
// contrived because I know that all the components have the same
// x-coordinate. You'll need more complicated calculations if your
// containers are not aligned this way.
private void connectCells(CustomCellFactory lCellFactory, String lVal,
CustomCellFactory rCellFactory, String rVal, Pane linePane) {
List<ListCell<String>> lList = lCellFactory.getAllCells();
ListCell<String> lCell = null;
for (ListCell<String> lc : lList) {
if (lc.getItem() != null && lc.getItem().equals(lVal)) {
lCell = lc;
break;
}
}
List<ListCell<String>> rList = rCellFactory.getAllCells();
ListCell<String> rCell = null;
for (ListCell<String> rc : rList) {
if (rc.getItem() != null && rc.getItem().equals(rVal)) {
rCell = rc;
break;
}
}
if (lCell != null && rCell != null) {
double startY = lCell.getLayoutY() +
(lCell.getBoundsInLocal().getHeight() / 2);
double endY = rCell.getLayoutY() +
(rCell.getBoundsInLocal().getHeight() / 2);
Line line = new Line(0, startY,
linePane.getBoundsInParent().getWidth(), endY);
line.setStrokeWidth(2);
line.setStroke(Color.BLACK);
linePane.getChildren().add(line);
}
}
public static void main(String[] args) {
launch(args);
}
}

Resources