In LWUIT, Component of another Form are not display - java-me

I am new on J2me developer using LWUIT library. I am making two forms: one is MainMidlet.java and another is UpgradeApp.java. Problem is that whatever the component add on UpgradeApp.java the component are not displayed. Please help me.
My Code as Follows.
MainMidlet.java
package com.sun.lwuit.jewelvicinity;
import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.FlowLayout;
import com.sun.lwuit.layouts.GridLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.table.TableLayout.Constraint;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
import javax.microedition.midlet.*;
public class MainMidlet extends MIDlet implements ActionListener
{
Form frm_Main;
public Button btn_main_Search, btn_main_WishList, btn_main_UpgradeApp, btn_main_Login, btn_main_NewUser,btn_main_Help, btn_main_AboutUs, btn_main_ContactUs, btn_main_Feedback, btn_main_Terms,btn_main_Privacy, btn_main_Exit;
public Image img_main_Search, img_main_Wishlist, img_main_UpgradeApp, img_main_Login, img_main_NewUser,img_main_Help, img_main_AboutUs, img_main_ContactUs, img_main_FeedBack, img_main_Terms,img_main_Privacy, img_main_Exit;
public Command cmd_Exit, cmd_Select;
public void startApp()
{
//--- Use for third soft Button
//Display.getInstance().setThirdSoftButton(true);
Display.init(this);
try
{
Resources theme = Resources.open("/LWUITtheme.res");
UIManager.getInstance().setThemeProps(theme.getTheme(theme.getThemeResourceNames()[0]));
}
catch (IOException io)
{
io.printStackTrace();
Dialog.show("Theme Exception", io.getMessage(), "Ok", null);
}
frm_Main = new Form("Jewel Vicinity");
try
{
img_main_Search = Image.createImage("/res/btn_main_search.png");
img_main_Wishlist = Image.createImage("/res/btn_main_wishlist.png");
img_main_UpgradeApp = Image.createImage("/res/btn_main_upgradeapp.png");
img_main_Login = Image.createImage("/res/btn_main_login.png");
img_main_NewUser = Image.createImage("/res/btn_main_newuser.png");
img_main_Help = Image.createImage("/res/btn_main_help.png");
img_main_AboutUs = Image.createImage("/res/btn_main_aboutus.png");
img_main_ContactUs = Image.createImage("/res/btn_main_contactus.png");
img_main_FeedBack = Image.createImage("/res/btn_main_feedback.png");
img_main_Terms = Image.createImage("/res/btn_main_terms.png");
img_main_Privacy = Image.createImage("/res/btn_main_privacy.png");
img_main_Exit = Image.createImage("/res/btn_main_exit.png");
}
catch (IOException io)
{
io.printStackTrace();
Dialog.show("Image not Found!", io.getMessage(), "Ok", null);
}
btn_main_Search = new Button("Search", img_main_Search);
btn_main_WishList = new Button("Wish List", img_main_Wishlist);
btn_main_UpgradeApp = new Button("Upgrade", img_main_UpgradeApp);
btn_main_Login = new Button("Login", img_main_Login);
btn_main_NewUser = new Button("NewUser", img_main_NewUser);
btn_main_Help = new Button("help", img_main_Help);
btn_main_AboutUs = new Button("About Us", img_main_AboutUs);
btn_main_ContactUs = new Button("Contact Us", img_main_ContactUs);
btn_main_Feedback = new Button("FeedBack", img_main_FeedBack);
btn_main_Privacy = new Button("Privacy", img_main_Privacy);
btn_main_Terms = new Button("Terms", img_main_Terms);
btn_main_Exit = new Button("Exit", img_main_Exit);
lbl_main_WishList.setTextPosition(Component.BOTTOM);
lbl_main_WishList.setAlignment(Component.CENTER);
lbl_main_WishList.getStyle().setMargin(0, 30, 0, 30);
lbl_main_UpgradeApp = new Label("Upgrade");
cmd_Exit = new Command("Exit", 1);
cmd_Select = new Command("Select");
GridLayout grd_MenuLayout = new GridLayout(4, 3);
frm_Main.setTitle("Menu");
frm_Main.setLayout(grd_MenuLayout);
frm_Main.setScrollableY(true);
//---- Add Button On Main Form
frm_Main.addComponent(btn_main_Search);
frm_Main.addComponent(btn_main_WishList);
frm_Main.addComponent(btn_main_UpgradeApp);
frm_Main.addComponent(btn_main_Login);
frm_Main.addComponent(btn_main_NewUser);
frm_Main.addComponent(btn_main_Help);
frm_Main.addComponent(btn_main_AboutUs);
frm_Main.addComponent(btn_main_ContactUs);
frm_Main.addComponent(btn_main_Feedback);
frm_Main.addComponent(btn_main_Terms);
frm_Main.addComponent(btn_main_Privacy);
frm_Main.addComponent(btn_main_Exit);
frm_Main.addCommand(cmd_Select);
frm_Main.addCommand(cmd_Exit);
//frm_Main.setCommandListener(this);
frm_Main.addCommandListener(this);
frm_Main.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae)
{
Command cmd = ae.getCommand();
String strcmdName = cmd.getCommandName();
if(strcmdName.equals("Exit"))
{
notifyDestroyed();
}
if (strcmdName.equals("Select"))
{
if(btn_main_Search.hasFocus())
{
//Dialog.show("Search", "Search", "Ok", null);
Form frm_Search = new Form("Search");
frm_Search.show();
}
if(btn_main_UpgradeApp.hasFocus())
{
Form UpgradeApp = new Form("Upgrade App");
UpgradeApp.show();
}
}
}
}
UpgradeApp.java
package com.sun.lwuit.jewelvicinity;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.FlowLayout;
public class UpgradeApp extends Form implements ActionListener
{
Label lbl_UpgradeApp;
Command cmd_Yes, cmd_No;
Form frm_UpgradeApp;
public UpgradeApp()
{
Display.init(this);
frm_UpgradeApp = new Form("Upgrade Application");
lbl_UpgradeApp = new Label("The New Version of Jewel.");
cmd_Yes = new Command("Yes", 1);
cmd_No = new Command("No", 2);
FlowLayout flw_UpgradeLayout = new FlowLayout(CENTER);
frm_UpgradeApp.setLayout(flw_UpgradeLayout);
frm_UpgradeApp.addComponent(lbl_UpgradeApp);
frm_UpgradeApp.addCommand(cmd_No);
frm_UpgradeApp.addCommand(cmd_Yes);
frm_UpgradeApp.addCommandListener(this);
frm_UpgradeApp.setVisible(true);
frm_UpgradeApp.show();
}
public void actionPerformed(ActionEvent evt)
{
}
}

From a brief review you seem to be calling Display.init(this); in a form subclass. I suggest you use a debugger and walk through the code.

Related

Call thread from another thread javafx

I have been trying to run two tasks on two threads and using their progress to be indicated on progress bar and progress indicator.
First task is copyTask and second is copy file.
The copyTask sends the file object to copyFile for file copy.
But the problem is only a single file gets copied and the file count seems to be correct.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.CountDownLatch;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
/**
* FXML Controller class
*
* #author ANIL
*/
public class ProgressIndicateController implements Initializable {
#FXML
private ProgressIndicator uploadIndicator;
#FXML
private ProgressBar uploadBar;
#FXML
private TextArea errTxt;
#FXML
private Label uploadTxt;
File f;
Thread parent,child;
CountDownLatch latch = new CountDownLatch(1);
#FXML
private Label sizeTXT;
// private CopyTask copyTask;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
// Unbind progress property
uploadBar.progressProperty().unbind();
// Bind progress property
uploadBar.progressProperty().bind(copyFile.progressProperty());
// Hủy bỏ kết nối thuộc tính progress
uploadIndicator.progressProperty().unbind();
// Bind progress property.
uploadIndicator.progressProperty().bind(copyTask.progressProperty());
// Unbind text property for Label.
uploadTxt.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
uploadTxt.textProperty().bind(copyTask.messageProperty());
// Unbind text property for Label.
sizeTXT.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
sizeTXT.textProperty().bind(copyFile.messageProperty());
// When completed tasks
copyTask.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, //
new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
List<File> copied = copyTask.getValue();
uploadTxt.textProperty().unbind();
uploadTxt.setText("Copied: " + copied.size());
}
});
copyFile.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, //
new EventHandler<WorkerStateEvent>() {
#Override
public void handle(WorkerStateEvent t) {
File copied = copyFile.getValue();
sizeTXT.textProperty().unbind();
sizeTXT.setText("Copied: " + copied.getAbsolutePath());
}
});
// Start the Task.
parent= new Thread(copyTask);
parent.start();
}
Task<List<File>> copyTask = new Task<List<File>>() {
#Override
protected List<File> call() throws Exception {
File dir = new File("F:");
File[] files = dir.listFiles();
int count = files.length;
List<File> copied = new ArrayList<File>();
int i = 0;
for (File file : files) {
if (file.isFile()) {
this.copy(file);
copied.add(file);
}
i++;
this.updateProgress(i, count);
}
return copied;
}
private void copy(File file) throws Exception {
this.updateMessage("Copying: " + file.getAbsolutePath());
f = file;
child=new Thread(copyFile);
child.start();
this.wait();
}
};
Task<File> copyFile = new Task<File>() {
#Override
protected File call() throws Exception {
InputStream is = null;
OutputStream os = null;
File dest=null;
String name=f.getName();
dest=new File("D:\\OUTPUT\\"+name);
is = new FileInputStream(f);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
double i=0.0;
double l=f.length();
while ((length = is.read(buffer)) > 0) {
i+=length;
this.updateMessage("Copying: " + i +" bytes of " + l);
os.write(buffer, 0, length);
this.updateProgress(i, l);
Thread.sleep(500);
}
is.close();
os.close();
this.notifyAll();
return dest;
}
};
}
New Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CyclicBarrier;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
/**
* FXML Controller class
*
* #author ANIL
*/
public class ProgressIndicateController implements Initializable {
#FXML
private ProgressIndicator uploadIndicator;
#FXML
private ProgressBar uploadBar;
#FXML
private TextArea errTxt;
#FXML
private Label uploadTxt;
#FXML
private Label sizeTXT;
CyclicBarrier cb = new CyclicBarrier(2);
final SimpleDoubleProperty prog1 = new SimpleDoubleProperty(0);
final SimpleDoubleProperty prog2 = new SimpleDoubleProperty(0);
final SimpleStringProperty text1 = new SimpleStringProperty("");
final SimpleStringProperty text2 = new SimpleStringProperty("");
final SimpleStringProperty err = new SimpleStringProperty("");
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
// Unbind progress property
uploadBar.progressProperty().unbind();
// Bind progress property
uploadBar.progressProperty().bind(prog2);
// Hủy bỏ kết nối thuộc tính progress
uploadIndicator.progressProperty().unbind();
// Bind progress property.
uploadIndicator.progressProperty().bind(prog1);
// Unbind text property for Label.
uploadTxt.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
uploadTxt.textProperty().bind(text1);
// Unbind text property for Label.
sizeTXT.textProperty().unbind();
// Bind the text property of Label
// with message property of Task
sizeTXT.textProperty().bind(text2);
//When completed tasks
errTxt.textProperty().unbind();
errTxt.textProperty().bind(err);
// Start the Task.
new Thread() {
#Override
public void run() {
File dir = new File("F:");
File[] files = dir.listFiles();
int count = files.length;
int i = 0;
for (File file : files) {
if (file.isFile()) {
try {
text1.setValue("Copying: " + file.getAbsolutePath());
InputStream is = null;
OutputStream os = null;
File dest = null;
String name = file.getName();
dest = new File("D:\\OUTPUT\\" + name);
is = new FileInputStream(file);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
double j = 0.0;
double l = file.length();
while ((length = is.read(buffer)) > 0) {
j += length;
text2.setValue("Copying: " + j + " bytes of " + l);
os.write(buffer, 0, length);
prog2.setValue(j / l);
Thread.sleep(100);
}
is.close();
os.close();
} catch (Exception ex) {
err.setValue(ex.toString());
}
i++;
prog1.setValue(i / count);
}
}
}
}.start();
}
}

JSlider hidding Value for GTK+ and Nimbus LookAndFeel On Linux

I have this situation (JSlider Showing Values when is not required). And I don't want to show the current Value on JSlider.
Why only on Linux is shown the value in JSlider using LookAndFeel Nimbus and GTK+?
How Can I to hide this value?
The next images shown running the code on Windows 10, Cent OS 7, and MacOS Sierra
Here my code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class JSliderLAF {
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> {
JPanel jpVert = new JPanel();
jpVert.setLayout(new BoxLayout(jpVert, BoxLayout.PAGE_AXIS));
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
JSlider jsl = new JSlider();
jsl.setMajorTickSpacing(20);
jsl.setMinorTickSpacing(5);
jsl.setPaintLabels(true);
jsl.setPaintTicks(true);
jsl.setSnapToTicks(true);
JPanel jpHorz = new JPanel();
jpHorz.setLayout(new BoxLayout(jpHorz, BoxLayout.LINE_AXIS));
JLabel jlName = new JLabel(info.getName() + " : ");
JLabel jlClass = new JLabel(info.getClassName());
jpHorz.add(jsl);
jpHorz.add(Box.createRigidArea(new Dimension(5,0)));
jpHorz.add(jlName);
jpHorz.add(Box.createRigidArea(new Dimension(2,0)));
jpHorz.add(jlClass);
jpHorz.add(Box.createRigidArea(new Dimension(2,0)));
jpHorz.add(Box.createHorizontalGlue());
changeLAF(jsl,info.getClassName());
jpVert.add(jpHorz);
}
final JFrame frame = new JFrame();
frame.add(jpVert, BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
});
}
}
public static void changeLAF(Container container, String laf) {
try {
UIManager.setLookAndFeel(laf);
UIManager.put("Slider.paintValue", false);
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | UnsupportedLookAndFeelException e) {
}
SwingUtilities.updateComponentTreeUI(container);
}

JavaFX - How to resize a SVG Path right in a TableView

I'm having issues to render a SVG Image in a TableView with a CellFactory.
Im using this code here, but it don't work, the svg image is scaled, but it don't resize.
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.shape.SVGPath;
import javafx.scene.shape.Shape;
import javafx.stage.Stage;
public class SVGTable extends Application {
private ObservableList<SVGExample> examples;
public static void main(String[] args) {
launch(args);
}
public SVGTable() {
examples = FXCollections.observableArrayList();
examples.addAll(new SVGExample(289),
new SVGExample(42),
new SVGExample(120));
}
#Override
public void start(Stage primaryStage) throws Exception {
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
TableView<SVGExample> tableView = new TableView<>();
tableView.setMinWidth(500);
tableView.setMinHeight(400);
tableView.setItems(examples);
final TableColumn<SVGExample, Integer> ping = new TableColumn<>("Ping");
ping.setCellValueFactory(new PropertyValueFactory<>("ping"));
ping.setCellFactory(param -> new PingCell());
tableView.getColumns().add(ping);
pane.getChildren().add(tableView);
primaryStage.setScene(scene);
primaryStage.show();
}
public class SVGExample {
private final IntegerProperty ping = new SimpleIntegerProperty();
public SVGExample(int ping) {
setPing(ping);
}
public int getPing() {
return ping.get();
}
public IntegerProperty pingProperty() {
return ping;
}
public void setPing(int ping) {
this.ping.set(ping);
}
}
public class PingCell extends TableCell<SVGExample, Integer> {
private HBox hBox = new HBox();
private Label label;
private int oldValue;
private PingCell() {
label = new Label();
hBox.setAlignment(Pos.CENTER_LEFT);
oldValue = Integer.MIN_VALUE;
}
#Override
protected void updateItem(final Integer item, final boolean empty) {
if (item != null) {
label.setText(item + "ms");
int i = (item + 50) / 100;
if (i < 1)
i = 1;
if (4 < i)
i = 4;
if (i != oldValue) {
SVGPath svgPath1 = new SVGPath();
svgPath1.setContent("M149.2,8.3L127-13.9c42.4-42.4,98.7-65.8,158.5-65.8c59.8,0,116.1,23.4,158.5,65.8L421.8,8.3c-36.5-36.5-84.9-56.6-136.3-56.6C234.1-48.2,185.7-28.1,149.2,8.3z");
SVGPath svgPath2 = new SVGPath();
svgPath2.setContent("M190.9,50.1l-22.2-22.2C200-3.4,241.4-20.6,285.5-20.6c44.1,0,85.5,17.2,116.8,48.4l-22.2,22.2c-25.3-25.3-58.9-39.2-94.6-39.2C249.8,10.8,216.2,24.8,190.9,50.1z");
SVGPath svgPath3 = new SVGPath();
svgPath3.setContent("M232.7,91.8l-22.2-22.2c20.1-20.1,46.7-31.1,75-31.1s55,11.1,75,31.1l-22.2,22.2c-14.1-14.1-32.9-21.9-52.8-21.9C265.6,69.9,246.8,77.7,232.7,91.8z");
SVGPath svgPath4 = new SVGPath();
svgPath4.setContent("M285.5,98.1c-12.8,0-24.5,5.2-32.9,13.6l32.9,32.9l32.9-32.9C310,103.3,298.3,98.1,285.5,98.1z");
Shape s = SVGPath.union(SVGPath.union(SVGPath.union(svgPath1, svgPath2), svgPath3), svgPath4);
s.setScaleX(0.1);
s.setScaleY(0.1);
hBox.getChildren().clear();
hBox.getChildren().addAll(s, label);
}
setGraphic(hBox);
}
}
}
}
After run, it's look like this:
You can wrap the Shape in a Group to force re-size of layout bounds.
hBox.getChildren().addAll(new Group(s), label);
Scale is a type of transform and according to Javadocs:
Any transform, effect, or state applied to a Group will be applied to all children of that group. Such transforms and effects will NOT be included in this Group's layout bounds, however if transforms and effects are set directly on children of this Group, those will be included in this Group's layout bounds.

JavaFX: Adding rows to TableView with a HashMap binding

Suppose that I have a map collection:
ObserableHashMap<K,V> map = FXCollections.observableHashMap();
I put 1 record into this map during fxml controller initialization, then wrap it as ObservableList:
ObservableList<ObserableHashMap.Entry<K,V>> list = FXCollections.observableArrayList(map.entrySet());
then setitems for my tableView.setItems(list);
Everything is fine when I run this JavaFX app and 1 record is showing.
Question is that:
When I add more records later to my map, my TableView will not refresh these records.
How could I bind a dynamical map collection into my TableView?
Thanks
If you use an ObservableList of ObservableMaps as your TableView's data structure
ObservableList<ObservableMap> rowMaps = FXCollections.observableArrayList();
tableView.setItems(rowMaps);
and implement your own ObservableMapValueFactory
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableMap;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.util.Callback;
public class ObservableMapValueFactory<V> implements
Callback<TableColumn.CellDataFeatures<ObservableMap, V>, ObservableValue<V>> {
private final Object key;
public ObservableMapValueFactory(Object key) {
this.key = key;
}
#Override
public ObservableValue<V> call(CellDataFeatures<ObservableMap, V> features) {
final ObservableMap map = features.getValue();
final ObjectProperty<V> property = new SimpleObjectProperty<V>((V) map.get(key));
map.addListener(new MapChangeListener<Object, V>() {
public void onChanged(Change<?, ? extends V> change) {
if (key.equals(change.getKey())) {
property.set((V) map.get(key));
}
}
});
return property;
}
}
and then set it as the cell value factory for your column(s)
column.setCellValueFactory(new ObservableMapValueFactory<String>(columnId));
all changes to your data are reflected in the TableView, even changes only affecting the ObservableMaps.
You can bind a map directly to a TableView, consider this example from the JavaFX documentation :
import java.util.HashMap;
import java.util.Map;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class TableViewSample extends Application {
public static final String Column1MapKey = "A";
public static final String Column2MapKey = "B";
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(300);
stage.setHeight(500);
final Label label = new Label("Student IDs");
label.setFont(new Font("Arial", 20));
TableColumn<Map, String> firstDataColumn = new TableColumn<>("Class A");
TableColumn<Map, String> secondDataColumn = new TableColumn<>("Class B");
firstDataColumn.setCellValueFactory(new MapValueFactory(Column1MapKey));
firstDataColumn.setMinWidth(130);
secondDataColumn.setCellValueFactory(new MapValueFactory(Column2MapKey));
secondDataColumn.setMinWidth(130);
TableView table_view = new TableView<>(generateDataInMap());
table_view.setEditable(true);
table_view.getSelectionModel().setCellSelectionEnabled(true);
table_view.getColumns().setAll(firstDataColumn, secondDataColumn);
Callback<TableColumn<Map, String>, TableCell<Map, String>>
cellFactoryForMap = new Callback<TableColumn<Map, String>,
TableCell<Map, String>>() {
#Override
public TableCell call(TableColumn p) {
return new TextFieldTableCell(new StringConverter() {
#Override
public String toString(Object t) {
return t.toString();
}
#Override
public Object fromString(String string) {
return string;
}
});
}
};
firstDataColumn.setCellFactory(cellFactoryForMap);
secondDataColumn.setCellFactory(cellFactoryForMap);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table_view);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
private ObservableList<Map> generateDataInMap() {
int max = 10;
ObservableList<Map> allData = FXCollections.observableArrayList();
for (int i = 1; i < max; i++) {
Map<String, String> dataRow = new HashMap<>();
String value1 = "A" + i;
String value2 = "B" + i;
dataRow.put(Column1MapKey, value1);
dataRow.put(Column2MapKey, value2);
allData.add(dataRow);
}
return allData;
}
}
More information can be found here
The answer from ItachiUchiha use the columns as keys and the rows as individual maps. If you'd like one map with the rows as keys->values, you'll have to add a listener to the map that will change the list when you add or delete. I did something similar here. https://stackoverflow.com/a/21339428/2855515

I am getting a NullPointerException when trying to use the Service class

I am getting a NullPointerException which is as follows:
java.lang.NullPointerException
file:/K:/Learner/JavaFx2/ProductApplication/dist/run166129449/ProductApplication.jar!/com/product/app/view/viewsingle.fxml
at com.product.app.controller.ViewSingleController.initialize(ViewSingleController.java:70)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
And my ViewSingleController is as follows:
package com.product.app.controller;
import com.product.app.model.Product;
import com.product.app.service.ViewProductsService;
import com.product.app.util.JSONParser;
import com.product.app.util.TagConstants;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* FXML Controller class
*
* #author Arun Joseph
*/
public class ViewSingleController implements Initializable {
private static String action = "";
#FXML
private TextField txtID;
#FXML
private TextField txtName;
#FXML
private TextField txtPrice;
#FXML
private TextArea txtDesc;
#FXML
private Region veil;
#FXML
private ProgressIndicator p;
private ViewProductsService service = new ViewProductsService();
private JSONObject product = null;
private JSONParser parser = new JSONParser();
private int pid = 1;
public void setPid(int pid) {
this.pid = pid;
}
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
p.setMaxSize(150, 150);
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
Product product = new Product();
service.start();
ObservableList<Product> products = service.valueProperty().get();
products.get(pid);
txtID.textProperty().set(String.valueOf(products.get(pid).getPid()));
//product = service.valueProperty().get().get(pid);
//txtID.setText(String.valueOf(product.getPid()));
txtName.textProperty().set(product.getName());
txtPrice.textProperty().set(String.valueOf(product.getPrize()));
txtDesc.textProperty().set(product.getDescription());
}
private SomeService someService = new SomeService();
#FXML
private void handleUpdateButtonClick(ActionEvent event) {
action = "update";
someService.start();
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
}
#FXML
private void handleDeleteButtonClick(ActionEvent event) {
action = "delete";
someService.start();
p.progressProperty().bind(service.progressProperty());
veil.visibleProperty().bind(service.runningProperty());
p.visibleProperty().bind(service.runningProperty());
}
#FXML
private void handleCancelButtonClick(ActionEvent event) {
closeStage();
}
private void closeStage() {
ViewSingleController.stage.close();
}
private static Stage stage = null;
public static void setStage(Stage stage) {
ViewSingleController.stage = stage;
}
private class SomeService extends Service<String> {
#Override
protected Task<String> createTask() {
return new SomeTask();
}
private class SomeTask extends Task<String> {
#Override
protected String call() throws Exception {
String result = "";
int success = 0;
List<NameValuePair> params = new ArrayList<NameValuePair>();
switch (action) {
case "update":
params.add(new BasicNameValuePair("pid", txtID.getText()));
params.add(new BasicNameValuePair("name", txtName.getText()));
params.add(new BasicNameValuePair("price", txtPrice.getText()));
params.add(new BasicNameValuePair("description", txtDesc.getText()));
product = parser.makeHttpRequest(TagConstants.url_update_product_with_id, "POST", params);
success = product.getInt(TagConstants.TAG_SUCCESS);
if (success == 1) {
result = "Successfully Updated the product";
JOptionPane.showMessageDialog(null, result);
closeStage();
}
break;
case "delete":
params.add(new BasicNameValuePair("pid", txtID.getText()));
product = parser.makeHttpRequest(TagConstants.url_delete_product_with_id, "POST", params);
success = product.getInt(TagConstants.TAG_SUCCESS);
if (success == 1) {
result = "Successfully Deleted the product";
JOptionPane.showMessageDialog(null, result);
closeStage();
}
break;
}
return result;
}
}
}
}
Please help me on how to fix this null pointer problem really help required. Thank you in advance
Inspect the line ViewSingleController.java:70. Put a breakpoint there. Run the program in a debugger and see what variables/fields are null.
The Exception happens on line 70, as you can see from the StackTrace.
On line 70, you call:
txtPrice.textProperty().set(String.valueOf(product.getPrize()));
The NullPointerException means that you are trying to access a method of an object that does not exist. Here, this might be txtPrice, textProperty, product or getPrize.
Skimming over your code, I'd guess it might be txtPrice, because you only set it as a member variable via
private TextField txtPrice;
but you never initialize it. Thus, txtPrice is null and txtPrice.textProperty().set will probably throw the NullPointer.

Resources