how to receive user data in a new window in javafx2 - window

I want to show a new window by clicking (say )on a menu item. The new window would contain two TextFields and one cancel button and one Ok button. When user gives data in the text fields and press Ok then in the parent window i should receive the values given by the user.
How can i do this?
Please show me with an example code.
Thanks

here is the solution, you click window menu then click new window, new window opens with two text fields and ok and cancel button, I get the text value from first text field and display it in the parent window. Let me know if you have any questions, I used singleton design pattern along with MVC. Let me know if you have any questions to run the code.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
/**
*
* #author Burak Firik
*/
public class ButtonListener implements MouseListener{
String value;
public ButtonListener(String str){
value=str;
}
#Override
public void mouseClicked(MouseEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
MainFrame mainGUI=singleton.getGUI();
mainGUI.setLabelValue(inputFrame.getTextField1().getText());
mainGUI.repaint();
}
#Override
public void mousePressed(MouseEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
inputFrame.setVisible(false);
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
And cancel button listener for the popup window
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Burak Firik
*/
public class CancelButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
inputFrame.setVisible(false);
}
}
And inputFrame where the popup jframe will display two text fields and two button for OK and Cancel
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
*
* #author Burak Firik
*/
public class InputFrame extends JFrame {
JTextField txt1;
JTextField txt2;
JButton btnOk;
JButton btnCancel;
public InputFrame(){
initGUI();
initHandlers();
}
void initGUI(){
this.setLayout(new BorderLayout());
this.setSize(300,300);
this.setLocation(200,200);
txt1=new JTextField(10);
txt2=new JTextField(10);
btnOk=new JButton("OK");
btnCancel=new JButton("Cancel");
JPanel northPanel=new JPanel();
northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
northPanel.add(txt1);
northPanel.add(txt2);
JPanel centerPanel=new JPanel();
centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
centerPanel.add(btnOk);
centerPanel.add(btnCancel);
add(northPanel,BorderLayout.NORTH );
add(centerPanel, BorderLayout.CENTER);
}
void initHandlers(){
ButtonListener btnListern=new ButtonListener(txt1.getText());
btnOk.addMouseListener(btnListern);
CancelButtonListener btnCancelListen=new CancelButtonListener();
btnCancel.addActionListener(btnCancelListen);
}
JFrame getInputFrame(){
return this;
}
JTextField getTextField1(){
return this.txt1;
}
JTextField getTextField2(){
return this.txt2;
}
public static void main(){
InputFrame frame=new InputFrame();
frame.setVisible(false);
}
}
mainframe where the newWindow ManuItem located;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
/**
*
* #author Burak Firik
*/
public class MainFrame extends JFrame{
private JMenuBar menuBar;
private JMenu menuWindow;
private JMenuItem menunewWindow;
private JLabel labelInputValue;
public MainFrame(){
this.setVisible(true);
this.setSize(300,300);
initGUI();
initHandlers();
}
private void initGUI() {
// Create the menu bar
this.setLayout(new BorderLayout());
menuBar = new JMenuBar();
menuWindow = new JMenu( "Window" );
menuWindow.setMnemonic( 'N' );
menuBar.add( menuWindow );
menunewWindow = CreateMenuItem( menuWindow, ITEM_PLAIN,
"New Window", null, 'N', null );
add(menuBar, BorderLayout.NORTH);
labelInputValue=new JLabel("SELAM");
add(labelInputValue, BorderLayout.CENTER);
}
public JMenuItem CreateMenuItem( JMenu menu, int iType, String sText,
ImageIcon image, int acceleratorKey,
String sToolTip )
{
// Create the item
JMenuItem menuItem;
switch( iType )
{
case ITEM_RADIO:
menuItem = new JRadioButtonMenuItem();
break;
case ITEM_CHECK:
menuItem = new JCheckBoxMenuItem();
break;
default:
menuItem = new JMenuItem();
break;
}
// Add the item test
menuItem.setText( sText );
// Add the optional icon
if( image != null )
menuItem.setIcon( image );
// Add the accelerator key
if( acceleratorKey > 0 )
menuItem.setMnemonic( acceleratorKey );
// Add the optional tool tip text
if( sToolTip != null )
menuItem.setToolTipText( sToolTip );
// Add an action handler to this menu item
menu.add( menuItem );
return menuItem;
}
private final int ITEM_PLAIN = 0; // Item types
private final int ITEM_CHECK = 1;
private final int ITEM_RADIO = 2;
private void initHandlers() {
MenuListener menuListen=new MenuListener();
menunewWindow.addActionListener(menuListen);
}
public void setLabelValue(String str){
labelInputValue.setText(str);
this.repaint();
}
}
this class contains the singleton object it is very quick for lazy programmers :))
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
/**
*
* #author Burak Firik
*/
public class MainSingleton {
private static MainSingleton singleton=null;
private MainFrame gui;
private InputFrame inputGUI;
//private constructor for singleton design pattern
private MainSingleton(){}
public static MainSingleton getMainSingleton()
{
// ONLY CONSTRUCT THE SINGLETON THE FIRST TIME
if (singleton == null)
{
singleton = new MainSingleton();
}
// GET THE SINGLETON NO MATTER WHAT
return singleton;
}
public static void main(String[] args) {
MainSingleton mainFrame=MainSingleton.getMainSingleton();
mainFrame.init();
}
public void init(){
// INITALIZE THE GUI
gui = new MainFrame();
inputGUI=new InputFrame();
}
public void requestExit()
{
// WE MAY HAVE TO SAVE CURRENT WORK
boolean continueToExit = true;
// IF THE USER REALLY WANTS TO EXIT THE APP
if (continueToExit)
{
// EXIT THE APPLICATION
System.exit(0);
}
}
public MainFrame getGUI() { return gui; }
public InputFrame getinputGUI() { return inputGUI; }
}
this is the menu listener, when you click new Window this listener will be invoked.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
/**
*
* #author Burak Firik
*/
public class MenuListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MainSingleton singleton=MainSingleton.getMainSingleton();
InputFrame inputFrame=singleton.getinputGUI();
inputFrame.setVisible(true);
}
}

Related

Issues running/debugging mapbox android code examples

I am trying to get started with mapbox android and can't get any of the example projects to work.
My problem is with the imports
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import com.mapbox.mapboxandroiddemo.R;
I get I "cannot resolve symbol annotation", "cannot resolve symbol v7" and "cannot resolve symbol mapboxandroiddemo".
I feel like this is some android problem that I am just not understanding correctly so if anyone has some insight that would be amazing. I have tried taking out some code and using the recommended bug fixes but all that has done is break my project.
Here is the entire MainActivity.java file
package com.example.mapboxtut;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxandroiddemo.R;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.utils.BitmapUtils;
import static com.mapbox.mapboxsdk.style.expressions.Expression.get;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textField;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.textOffset;
/**
* Use the {#link MapView#addOnStyleImageMissingListener(MapView.OnStyleImageMissingListener)}
* to handle the situation where a SymbolLayer tries using a missing image as an icon. If an icon-image
* cannot be found in a map style, a custom image can be provided to the map via
* the listener.
*/
public class MissingIconActivity extends AppCompatActivity {
private static final String ICON_SOURCE_ID = "ICON_SOURCE_ID";
private static final String ICON_LAYER_ID = "ICON_LAYER_ID";
private static final String PROFILE_NAME = "PROFILE_NAME";
private static final String CARLOS = "Carlos";
private static final String ANTONY = "Antony";
private static final String MARIA = "Maria";
private static final String LUCIANA = "Luciana";
private MapView mapView;
private MapboxMap mapboxMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
setContentView(R.layout.activity_styles_missing_icon);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
// Add Features which represent the location of each profile photo SymbolLayer icon
Feature carlosFeature = Feature.fromGeometry(Point.fromLngLat(-7.9760742,
41.2778064));
carlosFeature.addStringProperty(PROFILE_NAME, CARLOS);
Feature antonyFeature = Feature.fromGeometry(Point.fromLngLat(-8.0639648,
37.5445773));
antonyFeature.addStringProperty(PROFILE_NAME, ANTONY);
Feature mariaFeature = Feature.fromGeometry(Point.fromLngLat(-9.1845703,
38.9764924));
mariaFeature.addStringProperty(PROFILE_NAME, MARIA);
Feature lucianaFeature = Feature.fromGeometry(Point.fromLngLat(-7.5146484,
40.2459915));
lucianaFeature.addStringProperty(PROFILE_NAME, LUCIANA);
// Use a URL to build and add a Style object to the map. Then add a source to the Style.
mapboxMap.setStyle(
new Style.Builder().fromUrl(Style.LIGHT)
.withSource(new GeoJsonSource(ICON_SOURCE_ID,
FeatureCollection.fromFeatures(new Feature[] {
carlosFeature,
antonyFeature,
mariaFeature,
lucianaFeature}))),
new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
MissingIconActivity.this.mapboxMap = mapboxMap;
// Add a SymbolLayer to the style. iconImage is set to a value that will
// be used later in the addOnStyleImageMissingListener below
style.addLayer(new SymbolLayer(ICON_LAYER_ID, ICON_SOURCE_ID).withProperties(
iconImage(get(PROFILE_NAME)),
iconIgnorePlacement(true),
iconAllowOverlap(true),
textField(get(PROFILE_NAME)),
textIgnorePlacement(true),
textAllowOverlap(true),
textOffset(new Float[] {0f, 2f})
));
}
});
}
});
// Use the listener to match the id with the appropriate person. The correct profile photo is
// given to the map during "runtime".
mapView.addOnStyleImageMissingListener(new MapView.OnStyleImageMissingListener() {
#Override
public void onStyleImageMissing(#NonNull String id) {
switch (id) {
case CARLOS:
addImage(id, R.drawable.carlos);
break;
case ANTONY:
addImage(id, R.drawable.antony);
break;
case MARIA:
addImage(id, R.drawable.maria);
break;
case LUCIANA:
addImage(id, R.drawable.luciana);
break;
default:
addImage(id, R.drawable.carlos);
break;
}
}
});
}
private void addImage(String id, int drawableImage) {
Style style = mapboxMap.getStyle();
if (style != null) {
style.addImageAsync(id, BitmapUtils.getBitmapFromDrawable(
getResources().getDrawable(drawableImage)));
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}

Drag and drop with JavaFX TreeView

I implemented Drag and Drop feature as recommended in other threads in this forum. I have a cellFactory on a TreeView and set the events on the cells.
tvProject.setCellFactory(new Callback<TreeView<PlanningItem>, TreeCell<PlanningItem>>() {
#Override
public PlanningCheckBoxTreeCell call(TreeView<PlanningItem> siTreeView) {
final PlanningCheckBoxTreeCell source = new PlanningCheckBoxTreeCell();
final PlanningCheckBoxTreeCell target = new PlanningCheckBoxTreeCell();
source.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture */
System.out.println("onDragDetected");
/* allow any transfer mode */
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
event.consume();
}
});
target.setOnDragOver(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data is dragged over the target */
System.out.println("onDragOver");
...
event.consume();
}
});
The setOnDragDetected is executed/hit as wanted but all other events are NOT (I did not post them all here: setOnDragOver,setOnDragEntered,setOnDragExited,setOnDragDropped,setOnDragDone).
The PlanningCheckBoxTreeCell is a custom implementation of a treecell as follows:
public class PlanningCheckBoxTreeCell extends CheckBoxTreeCell<PlanningItem> {
public PlanningCheckBoxTreeCell() {
}
#Override
public void updateItem(PlanningItem item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setText(null);
}
}
}
UPDATE PlanningItem:
package at.v2c2.testplaygroundui;
import java.io.Serializable;
public class PlanningItem implements Serializable {
private static final long serialVersionUID = 1L;
private Double scene = null;
private Integer path = null;
private String move = null;
/**
* #return the scene
*/
public Double getScene() {
return scene;
}
/**
* #param scene the scene to set
*/
private void setScene(Double scene) {
this.scene = scene;
}
/**
* #return the path
*/
public Integer getPath() {
return path;
}
/**
* #param path the path to set
*/
private void setPath(Integer path) {
this.path = path;
}
/**
* #return the move
*/
public String getMove() {
return move;
}
/**
* #param move the move to set
*/
private void setMove(String move) {
this.move = move;
}
public PlanningItem(Object item) {
super();
if (item instanceof Double) {
setScene((Double) item);
} else if (item instanceof Integer) {
setPath((Integer) item);
} else if (item instanceof String) {
setMove((String) item);
}
}
}
UPDATE The MCVE:
package at.v2c2.testplaygroundui;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
public final class TestplaygroundUi extends Application {
private final DataFormat objectDataFormat = new DataFormat("application/x-java-serialized-object");
/**
* Constructor.
*/
public TestplaygroundUi() {
// empty.
}
/**
* #param args Program arguments.
*/
public static void main(final String[] args) {
launch(args);
}
#Override
public void start(final Stage primaryStage) throws Exception {
TreeItem<PlanningItem> treeItemRoot = new TreeItem<>(new PlanningItem(1.0));
TreeItem<PlanningItem> nodeItemA = new TreeItem<>(new PlanningItem(2));
TreeItem<PlanningItem> nodeItemB = new TreeItem<>(new PlanningItem(2));
treeItemRoot.getChildren().addAll(nodeItemA, nodeItemB);
TreeItem<PlanningItem> nodeItemA1 = new TreeItem<>(new PlanningItem("A1"));
TreeItem<PlanningItem> nodeItemB1 = new TreeItem<>(new PlanningItem("B1"));
nodeItemA.getChildren().addAll(nodeItemA1);
nodeItemB.getChildren().addAll(nodeItemB1);
TreeView<PlanningItem> treeView = new TreeView<>(treeItemRoot);
treeView.setCellFactory(new Callback<TreeView<PlanningItem>, TreeCell<PlanningItem>>() {
#Override
public TreeCell<PlanningItem> call(TreeView<PlanningItem> siTreeView) {
final TreeCell<PlanningItem> cell = new TreeCell<>();
cell.setOnDragDetected(new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
/* drag was detected, start drag-and-drop gesture */
System.out.println("onDragDetected");
/* allow any transfer mode */
Dragboard db = cell.startDragAndDrop(TransferMode.MOVE);
/* put a string on dragboard */
ClipboardContent content = new ClipboardContent();
content.put(objectDataFormat, cell.getItem());
// content.putString("Hello");// cell.getText());
db.setContent(content);
event.consume();
}
});
cell.setOnDragOver(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data is dragged over the target */
System.out.println("onDragOver");
/*
* accept it only if it is not dragged from the same node and if it has a string data
*/
if (event.getGestureSource() != cell && event.getDragboard().hasString()) {
/* allow for both copying and moving, whatever user chooses */
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
event.consume();
}
});
cell.setOnDragEntered(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* the drag-and-drop gesture entered the target */
System.out.println("onDragEntered");
/* show to the user that it is an actual gesture target */
if (event.getGestureSource() != cell && event.getDragboard().hasString()) {
// target.setFill(Color.GREEN);
}
event.consume();
}
});
cell.setOnDragExited(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
System.out.println("onDragExited");
/* mouse moved away, remove the graphical cues */
// target.setFill(Color.BLACK);
event.consume();
}
});
cell.setOnDragDropped(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* data dropped */
System.out.println("onDragDropped");
/* if there is a string data on dragboard, read it and use it */
Dragboard db = event.getDragboard();
boolean success = false;
if (db.hasString()) {
cell.setText(db.getString());
success = true;
}
/*
* let the source know whether the string was successfully transferred and used
*/
event.setDropCompleted(success);
event.consume();
}
});
cell.setOnDragDone(new EventHandler<DragEvent>() {
public void handle(DragEvent event) {
/* the drag-and-drop gesture ended */
System.out.println("onDragDone");
/* if the data was successfully moved, clear it */
if (event.getTransferMode() == TransferMode.MOVE) {
cell.setText("");
}
event.consume();
}
});
return cell;
};
});
StackPane root = new StackPane();
root.getChildren().add(treeView);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.setTitle("Test TreeView");
primaryStage.show();
}
}
Thanks in advance

Edit next row on tab

When i put all code in a SSCCE, it works as expected i.e first and third cells are editable. When tab on last column, takes to next row.
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.beans.property.ListProperty;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Yunus
*/
public class CollectionForm extends Application{
private TableView table = new TableView();
private ObservableList<Collection> collectionList = FXCollections.<Collection>observableArrayList();
ListProperty<Collection> collectionListProperty = new SimpleListProperty<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
// single cell selection mode
table.getSelectionModel().setCellSelectionEnabled(true);
//Create a custom cell factory so that cells can support editing.
Callback<TableColumn, TableCell> editableFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
return new EditableTableCell();
}
};
//A custom cell factory that creates cells that only accept numerical input.
Callback<TableColumn, TableCell> numericFactory = new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(TableColumn p) {
return new NumericEditableTableCell();
}
};
Button b = createSaveCollectionBtn();
//Create columns
TableColumn colMNO = createMNOColumn(editableFactory);
TableColumn colName = createNameColumn(editableFactory);
TableColumn colQty = createQuantityColumn(numericFactory);
table.getColumns().addAll(colMNO, colName, colQty);
//Make the table editable
table.setEditable(true);
collectionListProperty.set(collectionList);
table.itemsProperty().bindBidirectional(collectionListProperty);
collectionList.add(new Collection());
collectionList.add(new Collection());
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.getChildren().addAll(b, table);
vbox.setPadding(new Insets(10, 0, 0, 10));
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
private void handleCollection(ActionEvent event){
for (Collection collection : collectionList) {
System.out.println("MNO: "+collection.getMno()+" Quantity: "+collection.getQuantity());
}
}
private Button createSaveCollectionBtn(){
Button btn = new Button("Save Collection");
btn.setId("btnSaveCollection");
btn.setOnAction(this::handleCollection);
return btn;
}
private TableColumn createQuantityColumn(Callback<TableColumn, TableCell> editableFactory) {
TableColumn colQty = new TableColumn("Quantity");
colQty.setMinWidth(25);
colQty.setId("colQty");
colQty.setCellValueFactory(new PropertyValueFactory("quantity"));
colQty.setCellFactory(editableFactory);
colQty.setOnEditCommit(new EventHandler<CellEditEvent<Collection, Long>>() {
#Override
public void handle(CellEditEvent<Collection, Long> t) {
((Collection) t.getTableView().getItems().get(t.getTablePosition().getRow())).setQuantity(t.getNewValue());
}
});
return colQty;
}
private TableColumn createMNOColumn(Callback<TableColumn, TableCell> editableFactory) {
TableColumn colMno = new TableColumn("M/NO");
colMno.setMinWidth(25);
colMno.setId("colMNO");
colMno.setCellValueFactory(new PropertyValueFactory("mno"));
colMno.setCellFactory(editableFactory);
colMno.setOnEditCommit(new EventHandler<CellEditEvent<Collection, String>>() {
#Override
public void handle(CellEditEvent<Collection, String> t) {
((Collection) t.getTableView().getItems().get(t.getTablePosition().getRow())).setMno(t.getNewValue());
}
});
return colMno;
}
private TableColumn createNameColumn(Callback<TableColumn, TableCell> editableFactory) {
TableColumn colName = new TableColumn("Name");
colName.setEditable(false);
colName.setMinWidth(100);
colName.setId("colName");
colName.setCellValueFactory(new PropertyValueFactory<Collection, String>("name"));
colName.setCellFactory(editableFactory);
//Modifying the firstName property
colName.setOnEditCommit(new EventHandler<CellEditEvent<Collection, String>>() {
#Override
public void handle(CellEditEvent<Collection, String> t) {
((Collection) t.getTableView().getItems().get(t.getTablePosition().getRow())).setName(t.getNewValue());
}
});
return colName;
}
/**
*
* #author Graham Smith
*/
public class EditableTableCell<S extends Object, T extends String> extends AbstractEditableTableCell<S, T> {
public EditableTableCell() {
}
#Override
protected String getString() {
return getItem() == null ? "" : getItem().toString();
}
#Override
protected void commitHelper( boolean losingFocus ) {
commitEdit(((T) textField.getText()));
}
}
/**
*
* #author Graham Smith
*/
public class NumericEditableTableCell<S extends Object, T extends Number> extends AbstractEditableTableCell<S, T> {
private final NumberFormat format;
private boolean emptyZero;
private boolean completeParse;
/**
* Creates a new {#code NumericEditableTableCell} which treats empty strings as zero,
* will parse integers only and will fail if is can't parse the whole string.
*/
public NumericEditableTableCell() {
this( NumberFormat.getInstance(), true, true, true );
}
/**
* The integerOnly and completeParse settings have a complex relationship and care needs
* to be take to get the correct result.
* <ul>
* <li>If you want to accept only integers and you want to parse the whole string then
* set both integerOnly and completeParse to true. Strings such as 1.5 will be rejected
* as invalid. A string such as 1000 will be accepted as the number 1000.</li>
* <li>If you only want integers but don't care about parsing the whole string set
* integerOnly to true and completeParse to false. This will parse a string such as
* 1.5 and provide the number 1. The downside of this combination is that it will accept
* the string 1x and return the number 1 also.</li>
* <li>If you want to accept decimals and want to parse the whole string set integerOnly
* to false and completeParse to true. This will accept a string like 1.5 and return
* the number 1.5. A string such as 1.5x will be rejected.</li>
* <li>If you want to accept decimals and don't care about parsing the whole string set
* both integerOnly and completeParse to false. This will accept a string like 1.5x and
* return the number 1.5. A string like x1.5 will be rejected because ti doesn't start
* with a number. The downside of this combination is that a string like 1.5x3 will
* provide the number 1.5.</li>
* </ul>
*
* #param format the {#code NumberFormat} to use to format this cell.
* #param emptyZero if true an empty cell will be treated as zero.
* #param integerOnly if true only the integer part of the string is parsed.
* #param completeParse if true an exception will be thrown if the whole string given can't be parsed.
*/
public NumericEditableTableCell( NumberFormat format, boolean emptyZero, boolean integerOnly, boolean completeParse ) {
this.format = format;
this.emptyZero = emptyZero;
this.completeParse = completeParse;
format.setParseIntegerOnly(integerOnly);
}
#Override
protected String getString() {
return getItem() == null ? "" : format.format(getItem());
}
/**
* Parses the value of the text field and if matches the set format
* commits the edit otherwise it returns the cell to it's previous value.
*/
#Override
protected void commitHelper( boolean losingFocus ) {
if( textField == null ) {
return;
}
try {
String input = textField.getText();
if (input == null || input.length() == 0) {
if(emptyZero) {
setText( format.format(0) );
commitEdit( (T)new Integer( 0 ));
}
return;
}
int startIndex = 0;
ParsePosition position = new ParsePosition(startIndex);
Number parsedNumber = format.parse(input, position);
if (completeParse && position.getIndex() != input.length()) {
throw new ParseException("Failed to parse complete string: " + input, position.getIndex());
}
if (position.getIndex() == startIndex ) {
throw new ParseException("Failed to parse a number from the string: " + input, position.getIndex());
}
commitEdit( (T)parsedNumber );
} catch (ParseException ex) {
//Most of the time we don't mind if there is a parse exception as it
//indicates duff user data but in the case where we are losing focus
//it means the user has clicked away with bad data in the cell. In that
//situation we want to just cancel the editing and show them the old
//value.
if( losingFocus ) {
cancelEdit();
}
}
}
}
/**
* Provides the basis for an editable table cell using a text field. Sub-classes can provide formatters for display and a
* commitHelper to control when editing is committed.
*
* #author Graham Smith
*/
public abstract class AbstractEditableTableCell<S, T> extends TableCell<S, T> {
protected TextField textField;
public AbstractEditableTableCell() {
}
/**
* Any action attempting to commit an edit should call this method rather than commit the edit directly itself. This
* method will perform any validation and conversion required on the value. For text values that normally means this
* method just commits the edit but for numeric values, for example, it may first parse the given input. <p> The only
* situation that needs to be treated specially is when the field is losing focus. If you user hits enter to commit the
* cell with bad data we can happily cancel the commit and force them to enter a real value. If they click away from the
* cell though we want to give them their old value back.
*
* #param losingFocus true if the reason for the call was because the field is losing focus.
*/
protected abstract void commitHelper(boolean losingFocus);
/**
* Provides the string representation of the value of this cell when the cell is not being edited.
*/
protected abstract String getString();
#Override
public void startEdit() {
super.startEdit();
if (textField == null) {
createTextField();
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
Platform.runLater(new Runnable() {
#Override
public void run() {
textField.selectAll();
textField.requestFocus();
}
});
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(getString());
setContentDisplay(ContentDisplay.TEXT_ONLY);
//Once the edit has been cancelled we no longer need the text field
//so we mark it for cleanup here. Note though that you have to handle
//this situation in the focus listener which gets fired at the end
//of the editing.
textField = null;
}
#Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
setText(getString());
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitHelper(false);
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitHelper(false);
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
TablePosition focusedCellPosition = getTableView().getFocusModel().getFocusedCell();
if (nextColumn != null) {
//if( focusedCellPosition.getColumn() ){}focusedCellPosition.getTableColumn()
System.out.println("Column: "+focusedCellPosition.getColumn());
System.out.println("nextColumn.getId();: "+nextColumn.getId());
if( nextColumn.getId().equals("colMNO") ){
collectionList.add(new Collection());
getTableView().edit((getTableRow().getIndex())+1,getTableView().getColumns().get(0) );
getTableView().layout();
} else {
getTableView().edit(getTableRow().getIndex(), nextColumn);
}
}else{
getTableView().edit((getTableRow().getIndex())+1,getTableView().getColumns().get(0) );
}
}
}
});
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
//This focus listener fires at the end of cell editing when focus is lost
//and when enter is pressed (because that causes the text field to lose focus).
//The problem is that if enter is pressed then cancelEdit is called before this
//listener runs and therefore the text field has been cleaned up. If the
//text field is null we don't commit the edit. This has the useful side effect
//of stopping the double commit.
if (!newValue && textField != null) {
commitHelper(true);
}
}
});
}
/**
*
* #param forward true gets the column to the right, false the column to the left of the current column
* #return
*/
private TableColumn<S, ?> getNextColumn(boolean forward) {
List<TableColumn<S, ?>> columns = new ArrayList<>();
for (TableColumn<S, ?> column : getTableView().getColumns()) {
columns.addAll(getLeaves(column));
}
//There is no other column that supports editing.
if (columns.size() < 2) {
return null;
}
int currentIndex = columns.indexOf(getTableColumn());
int nextIndex = currentIndex;
if (forward) {
nextIndex++;
if (nextIndex > columns.size() - 1) {
nextIndex = 0;
}
} else {
nextIndex--;
if (nextIndex < 0) {
nextIndex = columns.size() - 1;
}
}
return columns.get(nextIndex);
}
private List<TableColumn<S, ?>> getLeaves(TableColumn<S, ?> root) {
List<TableColumn<S, ?>> columns = new ArrayList<>();
if (root.getColumns().isEmpty()) {
//We only want the leaves that are editable.
if (root.isEditable()) {
columns.add(root);
}
return columns;
} else {
for (TableColumn<S, ?> column : root.getColumns()) {
columns.addAll(getLeaves(column));
}
return columns;
}
}
}
public class Collection {
private int id;
private String mno;
private String name;
private float quantity;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMno() {
return mno;
}
public void setMno(String mno) {
this.mno = mno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getQuantity() {
return quantity;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
}
}
The problem is when i take the same code to a controller and add this table programmatically, does not work as before: it jumps next line and go to third.
Before asking the TableView to edit the cell it's important to make sure that it has focus, that the cell in question is in view, and that the view layout is up to date. This is probably because of the way TableView uses virtual cells.
Add these three lines before any call to TableView#edit:
getTableView().requestFocus();
getTableView().scrollTo(rowToEdit);
getTableView().layout();
// getTableView().edit goes here.
This solved this problem for me.

Special right-click-event in java

So, here's the scenario: I have a basic JTextField in a frame and want to give the user the option, to right click in the textfield and then, like in Eclipse or Microsoft Word, give him in a popup-menu the option to copy the text or paste text he already has created.
How do I make this special kind of right click event?
That's a short version of the program, I have so far:
import java.awt.*;
import javax.swing.*;
public class TestClass extends JFrame{
private JFrame frame;
private JTextField textField;
/**
* Main method
* #param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestClass window = new TestClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the window
*/
public TestClass() {
initialize();
}
/**
* Initialize components (TextField)
*/
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 200, 100);
textField = new JTextField();
textField.setText("TextField");
textField.setFont(new Font("Arial", Font.PLAIN, 20));
frame.add(textField);
}
}
You should use Mouse Event to register an event for you then you must use a popupmenu to be popped up when you click so far here is an example code for you!
privatevoidformMouseClicked(java.awt.event.MouseEventevt){
if (evt.isPopupTrigger()){
pop.show(evt.getComponent(),evt.getX(), evt.getY());
}
}
private void textfiledMousePressed(java.awt. event.MouseEvent evt) {
if (evt.getModifiers() == MouseEvent.BUTTON3_MASK){
p.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
This can also be done for right click

gwt widget - mutually-exclusive toggle button

I want a hybrid of a ToggleButton and RadioButton.
I want the "mutually-exclusive" part of RadioButton, and the gui look and behavior of ToggleButton(up and down states).
Does one already exist?
I've adapted kirushik's solution and created a simple "ToggleButtonPanel" widget that takes an arbitrary number of ToggleButtons (and possibly any other widgets you'd like to add) and a panel of your choosing (defaults to VerticalPanel) and makes the buttons mutually exclusive.
What's nice about this is that the panel itself fires ClickEvents when the buttons are clicked. This way, you can add a single ClickHandler to the ToggleGroupPanel and then determine which button was clicked using event.getSource()
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class ToggleButtonPanel extends Composite implements HasWidgets, HasClickHandlers{
public ToggleButtonPanel() {
this(new VerticalPanel());
}
public ToggleButtonPanel(Panel panel){
this.panel = panel;
initWidget(panel);
}
#Override
public void add(Widget w) {
if(w instanceof ToggleButton){
ToggleButton button = (ToggleButton) w;
button.addClickHandler(handler);
}
panel.add(w);
}
#Override
public void clear() {
panel.clear();
}
#Override
public Iterator<Widget> iterator() {
return panel.iterator();
}
#Override
public boolean remove(Widget w) {
return panel.remove(w);
}
#Override
public void setWidth(String width) {
panel.setWidth(width);
};
#Override
public void setHeight(String height) {
panel.setHeight(height);
}
private final Panel panel;
private ClickHandler handler = new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Iterator<Widget> itr = panel.iterator();
while(itr.hasNext()){
Widget w = itr.next();
if(w instanceof ToggleButton){
ToggleButton button = (ToggleButton) w;
button.setDown(false);
if(event.getSource().equals(button)) {
button.setDown(true);
}
}
}
for(ClickHandler h : handlers){
h.onClick(event);
}
}
};
private List<ClickHandler> handlers = new ArrayList<ClickHandler>();
#Override
public HandlerRegistration addClickHandler(final ClickHandler handler) {
handlers.add(handler);
return new HandlerRegistration() {
#Override
public void removeHandler() {
handlers.remove(handler);
}
};
}
}
Here is my pure-gwt variant:
class ThreeStateMachine extends FlowPanel{
// This is the main part - it will unset all the buttons in parent widget
// and then set only clicked one.
// One mutual handler works faster and is generally better for code reuse
private final ClickHandler toggleToThis = new ClickHandler() {
#Override
public void onClick(ClickEvent clickEvent) {
for(Widget b: ThreeStateMachine.this.getChildren()){
((ToggleButton)b).setDown(false);
}
((ToggleButton)clickEvent.getSource()).setDown(true);
}
};
private ThreeStateMachine() { // Create out widget and populat it with buttons
super();
ToggleButton b = new ToggleButton("one");
b.setDown(true);
b.addClickHandler(toggleToThis);
this.add(b);
b = new ToggleButton("two");
b.addClickHandler(toggleToThis);
this.add(b);
b = new ToggleButton("three");
b.addClickHandler(toggleToThis);
this.add(b);
}
}
Surely, one'll need css styles for gwt-ToggleButton with variants (-up-hovering etc.)
I have something that is both not in an extension library, and not dependent on a panel like the other answers. Define this class which manages the buttons. We're adding a new click listener to the buttons, which is in addition to whatever click handler you attached in the "GUI Content" class. I can't copy and paste this in, so hopefully it's syntatically correct.
public class MutuallyExclusiveToggleButtonCollection {
List<ToggleButton> m_toggleButtons = new ArrayList<ToggleButton>();
public void add(ToggleButton button) {
m_toggleButtons.add(button);
button.addClickListener(new ExclusiveButtonClickHandler());
}
private class ExclusiveButtonClickHandler impelments ClickHandler {
public void onClick(ClickEvent event) {
for(ToggleButton button : m_toggleButtons) {
boolean isSource = event.getSource().equals(button);
button.setIsDown(isSource);
}
}
}
Came across the same need, heres another solution that does away with the separate handler and works nicely in UIBinder with a declaration like:
<my:RadioToggleButton buttonGroup="btnGroup" text="Button 1" />
Here's the extended class:
import java.util.HashMap;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.ToggleButton;
public class RadioToggleButton extends ToggleButton
{
private static HashMap<String,ButtonGroup> buttonGroups = new HashMap<>();
private ButtonGroup buttonGroup;
public #UiConstructor RadioToggleButton( String buttonGroupName )
{
buttonGroup = buttonGroups.get( buttonGroupName );
if( buttonGroup == null ){
buttonGroups.put( buttonGroupName, buttonGroup = new ButtonGroup() );
}
buttonGroup.addButton( this );
}
#Override
public void setDown( boolean isDown )
{
if( isDown ){
RadioToggleButton btn = buttonGroup.pressedBtn;
if( btn != null ){
btn.setDown( false );
}
buttonGroup.pressedBtn = this;
}
super.setDown( isDown );
}
private class ButtonGroup implements ClickHandler
{
RadioToggleButton pressedBtn = null;
public void addButton( ToggleButton button )
{
button.addClickHandler( this );
}
#Override
public void onClick( ClickEvent event )
{
Object obj = event.getSource();
if( pressedBtn != null ){
pressedBtn.setDown( false );
}
pressedBtn = (RadioToggleButton)obj;
pressedBtn.setDown( true );
}
}
}
gwt-ext toggleButtons
"This example illustrates Toggle Buttons. When clicked, such Buttons toggle their 'pressed' state.
The Bold, Italic and Underline toggle Buttons operate independently with respect to their toggle state while the text alignment icon Buttons belong to the same toggle group and so when one of them is click, the previously pressed Button returns to its normal state."
Register an additional ClickHandler on all the ToggleButtons.
For example, ToggleButtons home, tree, summary, detail.
public class Abc extends Composite implements ClickHandler {
ToggleButton home, tree, summary, detail
public Abc() {
// all your UiBinder initializations... blah, blah....
home.addClickHandler(this);
tree.addClickHandler(this);
summary.addClickHandler(this);
detail.addClickHandler(this);
}
#Override
public void onClick(ClickEvent p_event) {
Object v_source = p_event.getSource();
home.setDown(home==v_source);
tree.setDown(tree==v_source);
summary.setDown(summary==v_source);
detail.setDown(detail==v_source);
}
}
Of course, you just need to add all the other boilerplate code and register additional ClickHandlers for each ToggleButton.

Resources