how to add same background color for all pane in javafx? - javafx-8

I want to maintain single background color(black) for all panes, and for all views. i don't want write css for every view. i am using only vbox and hbox mostly. and very few table views. is there any easy way to write css once and apply to all. thank you in advance

You don't write a css for every view, you give every element the same style class.
Pane pane = new Pane();
pane.getStyleClass().add("bg-black-style");
Somewhere you need to add the stylesheet to the scene
scene.getStylesheets().add("css-file.css");
And in the css file
.bg-black-style {
-fx-background-color: black;
}
This way every thing that should look the same has it's style all in one place.

You can just use .pane in CSS class, and it will work for all the panes.
.pane{
-fx-background-color: black;
}
Same works with .button etc.

You can apply the style sheet to the entire application like this:
package hacks;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
import java.net.URL;
/**
* Created by BDay on 7/10/17.<br>
* <br>
* CssStyle sets the style for the entire project
*/
public class CssStyle extends Application {
private String yourCss = "YourResource.css";
public CssStyle() {
try {
Application.setUserAgentStylesheet(getCss()); //null sets default style
} catch (NullPointerException ex) {
System.out.println(yourCss + " resource not found");
}
}
private Button button = new Button("Button Text");
private TextArea textArea = new TextArea("you text here");
private ObservableList<String> listItems = FXCollections.observableArrayList("one", "two", "three");
private ListView listView = new ListView<String>(listItems);
private FlowPane root = new FlowPane(button, textArea, listView);
private Scene scene = new Scene(root);
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setScene(scene);
primaryStage.show();
}
private String getCss() throws NullPointerException {
ClassLoader classLoader = getClass().getClassLoader();
URL resource = classLoader.getResource(yourCss);
String asString = resource.toExternalForm(); //throws null
return asString;
}
}

Related

I am making a new form using JavaFX. I need a Pop up text field within the form to add new category

adding new category within the same window
I am making a new form using javafx to add new item to an inventory, if I need to add new category into the Item form, I must be able to do within the frame itself by popping up a new text field as shown in the red box. Is there any way to do the same in JavaFX?
Two different approaches. You could use a TextField and setEditable(false). Then make the TextField's setEditable(true) after a double-click on the TextFeild. The first half of the code shows this approach. Another option is to use a Label. When the Label is double-clicked, hide the Label and show a TextField or TextArea. Type your data into one of these nodes and when enter is pressed, remove the TextField or TextArea and show the text in your Label. The second half of the code show this approach.
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
*
* #author blj0011
*/
public class JavaFXApplication7 extends Application {
#Override
public void start(Stage primaryStage) {
VBox root = new VBox();
StackPane stackPane = new StackPane();
TextField textField = new TextField("Text");
textField.setEditable(false);//Set Editiable to false
textField.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){
if(mouseEvent.getClickCount() == 2){
textField.setEditable(true);//On double click set editable to true
textField.setOnKeyPressed(event ->{
if(event.getCode().toString().equals("ENTER"))
{
textField.setEditable(false);//On enter set editable to false
}
});
}
}
}
});
Label label = new Label("Test");
VBox.setVgrow(label, Priority.ALWAYS);
label.wrapTextProperty().set(true);
label.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if(mouseEvent.getButton().equals(MouseButton.PRIMARY)){
if(mouseEvent.getClickCount() == 2){
label.setVisible(false);
TextArea textarea = new TextArea(label.getText());
textarea.setPrefHeight(label.getHeight() + 10);
stackPane.getChildren().add(textarea);
textarea.setOnKeyPressed(event ->{
System.out.println(event.getCode());
if(event.getCode().toString().equals("ENTER"))
{
label.setText(textarea.getText());
stackPane.getChildren().remove(textarea);
label.setVisible(true);
}
});
}
}
}
});
stackPane.getChildren().add(label);
root.getChildren().add(textField);
root.getChildren().add(stackPane);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Can I select text within a label in JavaFX 8 [duplicate]

I just want to create copiable label in JavaFX.
I have tried to create TextField that have no background, have no focus border and default background color, but I have no success.
I have found a lot of questions how to remove focus background from control but all of that looks like "hacks".
Is there are any standard solution to implement copyable text?
You can create a TextField without the border and background color with css:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CopyableLabel extends Application {
#Override
public void start(Stage primaryStage) {
TextField copyable = new TextField("Copy this");
copyable.setEditable(false);
copyable.getStyleClass().add("copyable-label");
TextField tf2 = new TextField();
VBox root = new VBox();
root.getChildren().addAll(copyable, tf2);
Scene scene = new Scene(root, 250, 150);
scene.getStylesheets().add(getClass().getResource("copyable-text.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
and
copyable-text.css:
.copyable-label, .copyable-label:focused {
-fx-background-color: transparent ;
-fx-background-insets: 0px ;
}
This is the solution I used, where there is a small button besides the label to be able to copy the text:
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import org.controlsfx.glyphfont.FontAwesome;
import org.controlsfx.glyphfont.Glyph;
import java.util.Locale;
public class CopiableLabel extends Label
{
public CopiableLabel()
{
addCopyButton();
}
public CopiableLabel(String text)
{
super(text);
addCopyButton();
}
public CopiableLabel(String text, Node graphic)
{
super(text, graphic);
}
private void addCopyButton()
{
Button button = new Button();
button.visibleProperty().bind(textProperty().isEmpty().not());
button.managedProperty().bind(textProperty().isEmpty().not());
button.setFocusTraversable(false);
button.setPadding(new Insets(0.0, 4.0, 0.0, 4.0));
button.setOnAction(actionEvent -> AppUtils.copyToClipboard(getText()));
Glyph clipboardIcon = AppUtils.createFontAwesomeIcon(FontAwesome.Glyph.CLIPBOARD);
clipboardIcon.setFontSize(8.0);
button.setGraphic(clipboardIcon);
setGraphic(button);
setContentDisplay(ContentDisplay.RIGHT);
}
}

JavaFX 8 TextArea loose focus on tab

Is it possible to change the default behaviour of a JavaFX TextArea, so that pressing Tab passes the focus to the next component?
While #ItachiUchiha solution works, as he states, it depends on the layout (box in his sample).
Based on this question, you can modify the default behavior of a TextArea, regardless of the layout.
But you will need to use for this private API, which may change at any time without notice.
In this sample Tab and Shitf+Tab will have the desired behavior, while Ctrl+Tab will insert "\t" on the text area.
#Override
public void start(Stage primaryStage) {
TextArea area = new TextArea();
area.addEventFilter(KeyEvent.KEY_PRESSED, (KeyEvent event) -> {
if (event.getCode() == KeyCode.TAB) {
TextAreaSkin skin = (TextAreaSkin) area.getSkin();
if (skin.getBehavior() instanceof TextAreaBehavior) {
TextAreaBehavior behavior = (TextAreaBehavior) skin.getBehavior();
if (event.isControlDown()) {
behavior.callAction("InsertTab");
} else if (event.isShiftDown()) {
behavior.callAction("TraversePrevious");
} else {
behavior.callAction("TraverseNext");
}
event.consume();
}
}
});
VBox root = new VBox(20, new Button("Button 1"), area, new Button("Button 2"));
Scene scene = new Scene(root, 400, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
Well, you definitely can do this, but it depends on the Layout to which the TextArea is added to. I have created a simple example where a TextArea and a TextField are both added to a VBox. There is a keyEventHandler which monitors the keyPress event on the TextArea and sends the focus to the next child(if any)
import java.util.Iterator;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TextAreaTabFocus extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
VBox box = new VBox();
TextArea textArea = new TextArea();
TextField textField = new TextField();
box.getChildren().addAll(textArea, textField);
final EventHandler<KeyEvent> keyEventHandler =
keyEvent -> {
if (keyEvent.getCode() == KeyCode.TAB) {
Iterator<Node> itr = box.getChildren().iterator();
while(itr.hasNext()) {
if(itr.next() == keyEvent.getSource()) {
if(itr.hasNext()){
itr.next().requestFocus();
}
//If TextArea is the last child
else {
box.getChildren().get(0).requestFocus();
}
break;
}
}
keyEvent.consume();
}
};
textArea.setOnKeyPressed(keyEventHandler);
Scene scene = new Scene(box, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

drawing rectangle in drawing issue

We are creating some graphical applications to the our project. We are using Draw2d and GEF technologies in our project. We have to draw one rectangle in the draw area. The functionality is as follows.
Use click the rectangle button from the toolbar.
Changes cursor to Cross curson symbol.
When the user clicks the area and drag the mouse, it shows the rectangle based on the dragging of the mouse.
Till now it is working fine. Now the issue is, we have zoom in and zoom out functionality.
When the use zoom in and draw the rectangle, it is not coming in the desired position.
It is going below parts of the area.Then user has to scroll and see the rectangle. This problem happens only when we use zoom in and zoom out.
How to ressolve this issue? Please see my code below.
package draw2dview;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.FigureCanvas;
import org.eclipse.draw2d.FreeformLayout;
import org.eclipse.draw2d.FreeformViewport;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.ScalableFigure;
import org.eclipse.draw2d.ScalableFreeformLayeredPane;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.DefaultEditDomain;
import org.eclipse.gef.EditDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPartFactory;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.editparts.ScalableFreeformRootEditPart;
import org.eclipse.gef.editparts.ScalableRootEditPart;
import org.eclipse.gef.editparts.ZoomManager;
import org.eclipse.gef.ui.actions.ZoomInAction;
import org.eclipse.gef.ui.actions.ZoomOutAction;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;
public class View extends ViewPart implements org.eclipse.swt.events.MouseListener {
public static final String ID = "draw2dview.view";
private Action drawAction;
private ScalableFreeformLayeredPane root;
ScalableRootEditPart editPart = null ;
private XYLayout layout;
private ZoomManager zoomManager ;
EditDomain editDomain = new DefaultEditDomain(null);
GraphicalViewer graphicalViewer = new ScrollingGraphicalViewer();
ScalableFreeformRootEditPart rootEditPart = new ScalableFreeformRootEditPart();
private FigureCanvas createContents(Composite parent){
root = new ScalableFreeformLayeredPane();
zoomManager = new ZoomManager(root,new FreeformViewport());
root.setFont(parent.getFont());
//layout = new XYLayout();
layout= new FreeformLayout();
root.setLayoutManager(layout);
FigureCanvas figureCanvas = new FigureCanvas(parent,SWT.DOUBLE_BUFFERED);
figureCanvas.addMouseListener(this);
figureCanvas.setBackground(ColorConstants.white);
LightweightSystem lws = new LightweightSystem(figureCanvas);
lws.setContents(root);
return figureCanvas ;
}
private IFigure createPersonFigure() {
RectangleFigure rectangleFigure = new RectangleFigure();
rectangleFigure.setBackgroundColor(ColorConstants.blue);
rectangleFigure.setLayoutManager(new ToolbarLayout());
rectangleFigure.setPreferredSize(100, 100);
return rectangleFigure ;
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
public void createPartControl(Composite parent) {
/* graphicalViewer.createControl(parent);
editDomain.addViewer(graphicalViewer);
graphicalViewer.setRootEditPart(rootEditPart);*/
createContents(parent);
createAction();
contributeToActionBars();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
addToToolBar(bars.getToolBarManager());
}
private void addToToolBar(IToolBarManager toolBarManager2){
toolBarManager2.add(drawAction);
toolBarManager2.add(new ZoomInAction(zoomManager));
toolBarManager2.add(new ZoomOutAction(zoomManager));
}
private void createAction() {
drawAction = new Action() {
public void run() {
System.out.println("execued..");
}
};
drawAction.setText("Draw");
drawAction.setImageDescriptor(Activator.getImageDescriptor("icons/alt_window_16.gif"));
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
// viewer.getControl().setFocus();
}
#Override
public void mouseDoubleClick(org.eclipse.swt.events.MouseEvent e) {
}
#Override
public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
System.out.println("inside..Mousedeown:: "+e.x+","+e.y);
IFigure personFigure = createPersonFigure();
root.add(personFigure);
layout.setConstraint(personFigure, new Rectangle(new Point(e.x,e.y),personFigure.getPreferredSize()));
//layout.setConstraint(personFigure, new Rectangle(new Point(e.x,e.y),personFigure.getPreferredSize()));
}
#Override
public void mouseUp(org.eclipse.swt.events.MouseEvent e) {
}
}
You will need to scale your mouse event coordinates according to the zoom level your zoom manager is currently using. The mouse events are absolute pixels, but your ZoomManger is causing a scale factor to be applied to your figure's coordinates. I think you will also need to take into account your ViewPort's client area.
First, when you constuct your ZoomManager pass in the ViewPort from your FigureCanvas:
zoomManager = new ZoomManager(root, figureCanvas.getViewPort());
Then try something like:
double scaleFactor = zoomManager.getZoom();
Rectangle r = figureCanvas.getViewport().getClientArea();
layout.setConstraint(personFigure, new Rectangle(new Point((e.x + r.x) * scaleFactor,(e.y + r.y) * scaleFactor),personFigure.getPreferredSize()));
This may need tweaked to get it right, let me know....
You have to translate from absolute coordinates obtained from the mouse event to relative coordinates to the person figure's parent:
#Override
public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
System.out.println("inside..Mousedeown:: "+e.x+","+e.y);
IFigure personFigure = createPersonFigure();
root.add(personFigure);
Point p = new PrecisionPoint(e.x,e.y);
personFigure.translateToRelative(p);
layout.setConstraint(personFigure, new Rectangle(p,personFigure.getPreferredSize()));
}
For more information look at draw2d help

windowbuilder tutorial not functioning

I am trying to do a tutorial that allows one to Add and Remove stocks and witness their price and change. This tutorial demonstrates how to use the GUI builder, GWT Designer, to create and design a Stock Watcher application based on the GWT tutorial.
http://code.google.com/webtoolkit/tools/gwtdesigner/tutorials/stockwatcher.html#design_ui
So far I have SW.java:
package edu.gatech.client;
import java.util.ArrayList;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class SW implements EntryPoint {
private RootPanel rootPanel;
private FlexTable stocksFlexTable;
private HorizontalPanel addPanel;
private VerticalPanel mainWindow;
private TextBox newSymbolTextBox;
private Button addButton;
private Label lastUpdatedLabel;
private ArrayList <String> stocks = new ArrayList<String>(); //Add this line
public void onModuleLoad() {
rootPanel = RootPanel.get();
mainWindow = new VerticalPanel();
rootPanel.add(mainWindow, 10, 10);
mainWindow.setSize("267px", "175px");
FlexTable stocksFlexTable = new FlexTable();
//Add these lines
stocksFlexTable.setText(0, 0, "Symbol");
stocksFlexTable.setText(0, 1, "Price");
stocksFlexTable.setText(0, 2, "Change");
stocksFlexTable.setText(0, 3, "Remove");
mainWindow.add(stocksFlexTable);
addPanel = new HorizontalPanel();
rootPanel.add(addPanel, 10, 200);
addPanel.setSize("267px", "68px");
newSymbolTextBox = new TextBox();
newSymbolTextBox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER){
addStock();
}
}
});
addPanel.add(newSymbolTextBox);
newSymbolTextBox.setWidth("211px");
addButton = new Button("Add");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
addStock();
}
});
addPanel.add(addButton);
lastUpdatedLabel = new Label("New Label");
rootPanel.add(lastUpdatedLabel, 48, 274);
}
private void addStock() {
final String symbol = newSymbolTextBox.getText().toUpperCase().trim();
newSymbolTextBox.setFocus(true);
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
if (!symbol.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + symbol + "' is not a valid symbol.");
newSymbolTextBox.selectAll();
return;
}
newSymbolTextBox.setText("");
// don't add the stock if it's already in the watch list
if (stocks.contains(symbol))
return;
// add the stock to the list
int row = stocksFlexTable.getRowCount();
stocks.add(symbol);
stocksFlexTable.setText(row, 0, symbol);
// add button to remove this stock from the list
Button removeStock = new Button("x");
removeStock.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
int removedIndex = stocks.indexOf(symbol);
stocks.remove(removedIndex);
stocksFlexTable.removeRow(removedIndex + 1);
}
});
stocksFlexTable.setWidget(row, 3, removeStock);
}
}
When I run the web application, I cannot Add a stock. The program does, however, distinguish between bad stock names and acceptable ones. Instead I get an "uncaught exception escaped" error and the program doesn't really do anything. How do I troubleshoot this?
Use the debugger and single step through the code. Set a breakpoint on addStock's first line and find which line crashes. Once you find which line you then instrument the line to find out what aspect is causing the problem - assuming you can't deduce the problem by looking at the line.