So I'm currently making a JavaFX GUI (with SceneBuilder) for a Connect4 game, and I was wondering if there's a way to 'group' objects together so that I can perform an action on all of them together?
Examples of what I mean:
I have 7 buttons for the columns (colButton1-7) and I want to disable all of them at once.
I use Ellipses for counters (counter1-40) and would like to change the color of all of them to white.
I searched around but couldn't find anything. I know how to do both for an individual object, but can't think of a way to easily apply the changes to all of them at the same time. Any help would be appreciated :)
There is no grouping mechanism to perform a single action on all of the members of the same group. On the contrary, you can have a single group/container to hold all your controls and apply the same action to each of its member.
For example, lets say I have a VBox containing Buttons and I want to disable them all.
for(Node node:vBox.getChildren()) {
node.setDisable(true);
}
or, to set Styling
for(Node node:vBox.getChildren()) {
node.setStyle("-fx-something");
}
For disabling, if you disable a node, then all it's child nodes will have disabled set to true. So you can do:
VBox buttonHolder = new VBox();
Button button = new Button(...);
buttonHolder.getChildren().add(button);
// repeat as necessary...
buttonHolder.setDisable(true); // all buttons in the VBox will now be disbaled
For styled properties, such as the fill of a shape, you should use an external style sheet. If you change the style class of the parent, then with an appropriate external style sheet you can change the style of all the children in one shot.
E.g.
Pane counterPane = new Pane();
for (int i=0; i<numCounters; i++) {
Ellipse counter = new Ellipse(...);
counter.getStyleClass().add("counter");
counterPane.getChildren().add(counter);
}
// ...
counterPane.getStyleClass().add("counter-pane"); // all counters white
// change to red:
counterPane.getStyleClass().remove("counter-pane");
counterPane.getStyleClass().add("warning");
External style sheet:
.counter-pane > .counter {
-fx-fill: white ;
}
.warning > .counter {
-fx-fill : red ;
}
Related
This is a problem I've been trying to deal with for a good hour now, so I figured I might as well ask this question. My goal/question is about the behaviour of the list supplied by pane.getChildren(). To explain better, here's a bit of example code.
VBox pane1 = new VBox();
Label label1 = new Label("a");
Label label2 = new Label("b");
pane1.getChildren().addAll(label1,label2);
System.out.println(pane1.getChildren().size());
for (int i=0; i<pane1.getChildren().size(); i++) {
System.out.println(i + pane1.getChildren().get(i).(??????????)
}
The list pane1.getChildren() is of a size 2, but the pane1.getChildren().get(i) doesn't allow me to use Label related methods (such as getText(), which is the one I'm interested in accessing). What exactly is happening here, why isn't pane1.getChildren().get(i) acknowledged as a Label?
Also worth adding, that if i run
for (int i=0; i<pane1.getChildren().size(); i++) {
System.out.println(i + pane1.getChildren().get(i).getClass().getName());
}
the console output says, that the name of the class is "javafx.scene.control.Label".
I'd love some clarification on this little problem, and thank you in advance!
Pane.getChildren() returns an ObservableList<Node>, so pane1.getChildren().get(i) has a compile-time type of Node, not Label.
It's not clear why you need to do this: you already have the references to the labels without iterating through the pane's list of children. So you can just do
Stream.of(label1, label2).map(Label::getText).forEach(text -> {
// whatever you need to do with the text...
});
If you really want to get this from the pane's children list, just do the obvious downcast:
for (Node n : pane1.getChildren()) {
String text = ((Label) n).getText();
// ...
}
or
pane1.getChildren().stream()
.map(Label.class::cast)
.map(Label::getText)
.forEach(text -> {
// whatever you need to do with text...
});
but of course this will not work (without extra checks) if you put something in the pane that is not a label.
If you need to downcast it can be done in a stream:
pane1.getChildren()
.stream()
.filter(Label.class::isInstance)
.map(Label.class::cast)
.forEach(label -> System.out.println(label.getText()));
This filters all children to just be labels, then maps them as such.
I want to loop through each object of a list. For each entry I want to create a GUI object that looks like this:
A checkbox on the left
An image in the center
(later) A label on the left
My problem is, that each label has a different length and it looks rather strange if not all pictures are on the same line (as seen vertically). Is there a possibility by either java or css to align the ImageVew in center of the HBox?
imageView.setLayoutX(filterBox.getWidth()/2); didn't do the trick unfortunatly. And no -fx-align: right; or -fx-float: right; seems to be existing.
I included what I have so far.
VBox filtersBox = new VBox();
HBox filterBox;
for(Filter filter : filters.getFilters()){
if(!filter.isComplex()){
filterBox = new HBox();
filterBox.getStyleClass().add("filter");
ImageView imageView = new ImageView();
[image view stuff]
final CheckBox cbox = new CheckBox(filter.getName().toString());
filterBox.getChildren().addAll(cbox, imageView);
filtersBox.getChildren().addAll(filterBox);
}
}
As far as I'm aware, this is impossible.
I see two ways you can achieve this layout, though:
Have all the checkboxes have the same (constant) preferred width. This way your image views should line up.
Use a GridPane, and add rows instead of HBoxes
I'd like to define descriptions for Grid header cells, similarly to how AbstractComponent.setDescription(String description) works (i.e. tooltip shown on mouse hover). As the Grid doesn't support this in itself, I tried adding a Label component into the header cell, and then use setDescription() on the label. I can get the info tooltip working like this, but the downside is that clicking on the label component doesn't trigger sorting. If I want to sort the column, I need to click the header cell on the really narrow area that's left between the right edge of the label component and the column border, where the sorting indicator will be shown. If you look at the screenshot below, the highlighted area is the label component, and in order to trigger sorting, the user needs to click on the space on the right side of the component.
Is there a better way to apply descriptions to header cells than the one I described? And if not, is there a way to make the sorting work properly when the header cell contains a Component?
Based on the answer from kukis, I managed to come up with a simpler solution that doesn't require any JavaScript. Instead of adding a Label component into the header cell, I'm adding a div element manually with StaticCell.setHtml(), and setting the title attribute on it:
#Override
protected void init(VaadinRequest request) {
Grid grid = new Grid();
grid.addColumn("to");
grid.addColumn("the");
grid.addColumn("moon");
Grid.HeaderRow headerRow = grid.getDefaultHeaderRow();
headerRow.getCell("to").setHtml("<div title='Hello world'>to</div>");
headerRow.getCell("the").setHtml("<div title='Hello world 2'>the</div>");
headerRow.getCell("moon").setHtml("<div title='Hello world 3'>moon</div>");
grid.addRow("1","2","3");
grid.addRow("d","v","w");
grid.addRow("g","s","h");
setContent(new VerticalLayout(grid));
}
Feature added to Vaadin 8.4.0
Feature added to Grid in Vaadin 8.4.0.
Ticket:
https://github.com/vaadin/framework/pull/10489
Release notes:
https://vaadin.com/download/release/8.4/8.4.0/release-notes.html
Grid headers and footers now support tooltips.
Well, since Grid doesn't support it by itself you can always use JavaScript to achieve desired behaviour. SSCCE:
private final String SCRIPT;
{
StringBuilder b = new StringBuilder();
b.append("var grid = document.getElementById('mygrid');\n");
b.append("var child = grid.getElementsByClassName('v-grid-tablewrapper')[0];\n");
b.append("child = child.firstChild.firstChild.firstChild;\n");
b.append("child.childNodes[0].title='Hello world';\n");
b.append("child.childNodes[1].title='Hello world 2';\n");
b.append("child.childNodes[2].title='Hello world 3';\n");
SCRIPT = b.toString();
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
Grid grid = new Grid();
grid.addColumn("to");
grid.addColumn("the");
grid.addColumn("moon");
grid.addRow("1","2","3");
grid.addRow("d","v","w");
grid.addRow("g","s","h");
grid.setId("mygrid");
setContent(layout);
layout.addComponent(grid);
JavaScript.getCurrent().execute(SCRIPT);
}
Another possibility would be to develop your own Grid in GWT based on the Grid provided by Vaadin Team but it is a way higher cost approach.
Another solution would be to, as you have tried, put label in a column and propagate the label-clicked-event to the Grid.
I use my own utillity finction:
public static Grid setHeaderCellDescription(Grid grid, int rowIndex, String property, String description) {
Grid.HeaderCell cell;
String cellHeader = "<span title=\"%s\">%s</span>";
cell = grid.getHeaderRow(rowIndex).getCell(property);
cell.setHtml(String.format(cellHeader, description, cell.getText()));
return grid;
}
You may add some additional checks if need (existing of cell and row number).
Or other variant - instead setHtml use cetComponent.
Grid.HeaderCell cell = grid.getHeaderRow(rowIndex).getCell(property);
Label newLabel = new Label(cell.getText());
newLabel.setDescription(description);
cell.setComponent(newLabel);
Update for Vaadin 23: you can use your own Component as a column header with this method: com.vaadin.flow.component.grid.Grid.Column#setHeader(com.vaadin.flow.component.Component).
So you can use e.g. a Span with a title:
Span headerComponent = new Span();
headerComponent.setText("Your header text");
headerComponent.getElement().setProperty("title", "Your tooltip text");
column.setHeader(headerComponent);
I have a GridPane which I'm filling with various graphical/textual elements.
For the text, single line labels gets the right size. The same happens to e.g. images
of various sizes (the grid is stretched to give space for the image).
However, for multiline text elements (a.e. a label containing text with newlines in it), it clips the element at one line height... How can I force an UI element (like a label) to take up enough space to display its content?
Here's some code (scala):
val chatPanel = new GridPane {
setFitToWidth(true)
setFitToHeight(true)
setManaged(true)
setMaxWidth(10000)
setMaxHeight(10000)
}
def sendTextInfoBlock(title:String,message:String) {
val button = new Label(message) {
// setWrapText(true)
// setMinHeight(100) <- this works, but of course doesn't match the required height
}
// val button = new Button(message)
chatPanel.add(button,1,row)
the message is a text with newlines, like "this is a long\nand interresting\nmessage"
I gave up, stacked a VBox full of labels (one label per line of text), and just styled it
like a button. That worked well at least.
I have grid layout witch some fields added like that:
private Component userDetailsTab(final User user) {
final GridLayout details = new GridLayout(2, 1);
details.setMargin(true);
details.setSpacing(true);
details.addComponent(createDetailLabel(Messages.User_Name));
final Component username = createDetailValue(user.getName());
details.addComponent(username);
...
I have also Layout click listener which replace labels on text field, it looks like that:
final TextField tf = new TextField();
details.addListener(new LayoutClickListener() {
private static final long serialVersionUID = -7374243623325736476L;
#Override
public void layoutClick(LayoutClickEvent event) {
Component com = event.getChildComponent();
if (event.getChildComponent() instanceof Label) {
Label label = (Label)event.getChildComponent();
details.replaceComponent(com, tf);
tf.setValue(label.getValue());
}
}
});
In future I want to enable click on label, edit it and write changes to database after clicking somewhere else (on different label for example).
Now when I click on 1st label and then on 2nd label, effect is: 1st has value of 2nd and 2nd is text field witch value of 2nd. Why it's going that way? What should i do to after clicking on 1st and then 2nd get 1st label witch value of 1st?
You don't need to swap between Labels and TextFields, you can just use a TextField and style it look like a Label when it's not focused.
When I tried to create click-to-edit labels, it created a ton of extra work for me. I'd discourage it (and do as Patton suggests in the comments).
However, if you're going to insist on trying to create in-place editing, you will want to do the following:
Create a new class that extends a layout (e.g. HorizontalLayout), which can swap out a label for a text field
use LayoutClickListener to removeComponent(myLabel) and addComponent(myTextField)
use BlurListener to swap back to the label
use ValueChangeListener on the text field to copy its value to the label
This is a still a bad idea because:
Users cannot see affordances as easily (they can't tell what's editable)
Users cannot use the keyboard to tab to the field they want to edit
It adds unncessary complexity (maintenance time, etc).
I would recommend, if you want in-place editing, just show the text field, and save the new value with the BlurListener.