Olá, estou com a seguinte dúvida. Criei um projeto em JavaFX, adicionei uma barra de Menus e tudo mais. Só que quando vou setar uma imagem e jogar em um HBox, ele me retorna o famoso java.NullPointerException e um IllegallArgumentException :evil: .
Em um dos Menus eu tenho os seguintes items: Sair, Mostrar, Apagar. Minha intenção era que, ao clicar em "Mostrar" ele mostrasse uma foto com: nome, descrição e nome cientifico de umas frutas(esse codigo é um exemplo que eu achei de como usar JavaFX no site da Oracle). Para isso eu tenho uma classe PageData onde eu tenho as variáveis: name(String), description(String), binNames(String) e image(Image) e um construtor dentro dessa classe com os parametros a serem passados a essas variaveis.
O que eu não estou conseguindo fazer é passar as imagens corretamente(eu acho!), ai ele fala que o objeto está como null, e fala que a imagem tambem não está no diretorio Claspath padrão. Alguem sabe o que pode ser? Meu código:
package main;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class Principal extends Application implements EventHandler<ActionEvent> {
/**
* @param args
*/
final PageData[] pages = new PageData[]{
new PageData("Apple",
"The apple is the pomaceous fruit of the apple tree, species Malus "
+"domestica in the rose family (Rosaceae). It is one of the most "
+"widely cultivated tree fruits, and the most widely known of "
+"the many members of genus Malus that are used by humans. "
+"The tree originated in Western Asia, where its wild ancestor, "
+"the Alma, is still found today.",
"Malus domestica"),
new PageData("Hawthorn",
"The hawthorn is a large genus of shrubs and trees in the rose "
+ "family, Rosaceae, native to temperate regions of the Northern "
+ "Hemisphere in Europe, Asia and North America. "
+ "The name hawthorn was "
+ "originally applied to the species native to northern Europe, "
+ "especially the Common Hawthorn C. monogyna, and the unmodified "
+ "name is often so used in Britain and Ireland.",
"Crataegus monogyna"),
new PageData("Ivy",
"The ivy is a flowering plant in the grape family (Vitaceae) native"
+" to eastern Asia in Japan, Korea, and northern and eastern China."
+" It is a deciduous woody vine growing to 30 m tall or more given "
+"suitable support, attaching itself by means of numerous small "
+"branched tendrils tipped with sticky disks.",
"Parthenocissus tricuspidata"),
new PageData("Quince",
"The quince is the sole member of the genus Cydonia and is native"
+" to warm-temperate southwest Asia in the Caucasus region. The "
+"immature fruit is green with dense grey-white pubescence, most "
+"of which rubs off before maturity in late autumn when the fruit "
+"changes color to yellow with hard, strongly perfumed flesh.",
"Cydonia oblonga")
};
final String[] opcoes = new String[] {
"Title",
"Binomial name",
"Picture",
"Description"
};
final ImageView pic = new ImageView();
final Label name = new Label();
final Label binName = new Label();
final Label description = new Label();
private int currentIndex = -1;
public static void main(String[] args) {
// TODO Auto-generated method stub
launch();
}
@Override
public void start(Stage stage) throws Exception {
// TODO Auto-generated method stub
stage.setTitle("Menu Sample");
Scene scene = new Scene(new VBox(), 400, 350);
scene.setFill(Color.OLDLACE);
// configuracao das fontes, tamanho e alinhamento das Letras e figuras dos Menus
name.setFont(new Font("Verdana Bold", 22));
binName.setFont(new Font("Arial Italic", 10));
pic.setFitHeight(150);
pic.setPreserveRatio(true);
description.setWrapText(true);
description.setTextAlignment(TextAlignment.JUSTIFY);
//shuffle();
MenuBar menuBar = new MenuBar();
final VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.setPadding(new Insets(0, 10, 0, 10));
vbox.getChildren().addAll(name, binName, pic, description);
// --- Menu File
Menu menuFile = new Menu("File");
// Ta dando problema aqui ele não acha esse diretorio c/ a imagem pra aparecer
// Essa pasta imagens ta dentro da pasta do projeto(DamasJavaFX), sempre deu certo qdo eu fazia c/ swing mas agr ta dando esse erro
MenuItem add = new MenuItem("Shuffle", new ImageView(new Image("../imagens/new.jpg")));
//MenuItem add = new MenuItem("Shuffle"); // voltar como era antes !!!
add.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
//shuffle();
vbox.setVisible(true);
}
});
// Apaga os Dados atuais do Vbox
MenuItem clear = new MenuItem("Clear");
clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
clear.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
vbox.setVisible(false);
}
});
// Sai do programa pelo Menu
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
System.exit(0);
}
});
menuFile.getItems().addAll(add,clear, new SeparatorMenuItem(), exit);
// --- Menu Edit
Menu menuEdit = new Menu("Edit");
// --- Menu View
Menu menuView = new Menu("View");
menuBar.getMenus().addAll(menuFile, menuEdit, menuView);
// add menuBar no Scene, usa o cast no Scene, pois ao criar o Scene, inicia-se uma instancia de VBox
((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);
stage.setScene(scene);
stage.show();
}
// calcula o indice dos elementos no array, do tipo PageData
private void shuffle() {
int i = currentIndex;
while (i == currentIndex) { // nada selecionado(indice -1), deixa td como esta
i = (int) (Math.random() * pages.length);
}
pic.setImage(pages[i].image); // seta a ImageView, com a Image setada
name.setText(pages[i].name);
binName.setText("(" + pages[i].binNames + ")");
description.setText(pages[i].description);
currentIndex = i;
}
// Classe onde vao ser passados os dados selecionados
private class PageData {
public String name;
public String description;
public String binNames;
public Image image;
public PageData(String name, String description, String binNames) {
this.name = name;
this.description = description;
this.binNames = binNames;
// Nome da img selecionada concatenada com a extensao
image = new Image(getClass().getResourceAsStream(name+".jpg"));
}
}
@Override
public void handle(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}