I have a JavaFX application with 2 tabs in a tabPane. And I would like each tab to have a default button (a button with defaultButton="true"). However, only the button in the first tab reacts on Enter key presses. The button in the second tab ignores Enter key presses.
Hypothesis: Oracle documentation states:
A default Button is the button that receives a keyboard VK_ENTER
press, if no other node in the scene consumes it.
Hence, I guess the problem is that both buttons are in a single scene. Do you know how to get 2 tabs in JavaFX, each with a working default button?
There can only be one default button: you want the button in the currently selected tab to be the default button. Simply add a listener to the selected property of each tab and make the corresponding button the default button, or use a binding to achieve the same:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class MultipleDefaultButtons extends Application {
#Override
public void start(Stage primaryStage) {
TabPane tabPane = new TabPane();
tabPane.getTabs().addAll(createTab("Tab 1"), createTab("Tab 2"));
primaryStage.setScene(new Scene(tabPane, 400, 400));
primaryStage.show();
}
private Tab createTab(String text) {
Tab tab = new Tab(text);
Label label = new Label("This is "+text);
Button ok = new Button("OK");
ok.setOnAction(e -> System.out.println("OK pressed in "+text));
VBox content = new VBox(5, label, ok);
tab.setContent(content);
ok.defaultButtonProperty().bind(tab.selectedProperty());
return tab ;
}
public static void main(String[] args) {
launch(args);
}
}
Related
I do not understand why when I left-click the MenuButton that the ContextMenu does not simply appear and stay, or disappear when I click a second time like a visibility toggle. A short code example and what I experience is detailed below.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.*;
public class BtnTest extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Scene scene = new Scene(new MenuButton("Options", null, new MenuItem("test1"), new MenuItem("test2")), 650, 500);
primaryStage.setTitle("Testing Btn");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I run this simple code in BlueJ IDE, on Windows 10
If I click on the MenuButton, the application window seems to be focused then lose focus, and the button's ContextMenu appears and then disappears.
If I click a second time, the ContextMenu appears and stays (even if I click off the application window onto another program).
If I click a third time, the ContextMenu disappears.
If I click a fourth time, the ContextMenu flickers on and off again.
If I click a fifth time, the ContextMenu appears and stays.
If I click a sixth time, the ContextMenu disappears.
And this continues to repeat.
I could be wrong, but the problem appears to be that the autoHide boolean property for the ContextMenu/PopupWindow is set to true by default. MenuButton uses a default ContextMenu when you click it to show the MenuItems.
I tried to setContextMenu for the MenuButton to a predefined ContextMenu, one with autoHide set to false, but this either causes an overlapping of events causing it to show then hide on click, or the ContextMenu is being set back to null by MenuButton?
Either way, I found a solution by switching to using a Button and a ContextMenu separately from one another, with the ContextMenu's autoHide set to false:
import javafx.geometry.Side;
import javafx.event.Event;
import javafx.event.EventHandler;
public class BtnTest2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
Button btn = new Button("Options");
MenuItem item1 = new MenuItem("test1");
MenuItem item2 = new MenuItem("test2");
ContextMenu cm = new ContextMenu();
cm.setAutoHide(false);
cm.getItems().addAll(item1, item2);
btn.addEventHandler(ActionEvent.ACTION, e -> {
cm.show(btn, Side.BOTTOM, 0, 0);
e.consume();
});
Scene scene = new Scene(btn, 650, 500);
primaryStage.setTitle("Testing Btn");
primaryStage.setScene(scene);
primaryStage.show();
}
}
I have a splitpane with each containing a anchorpane with a tableview (paneA paneB). By clicking on the button "Show" I want to open a new view depending on the selected side of the split pane.
E.G.
Pane A | Pane B
patient 1 | patient a
patient 2 | patient b
(ShowButon)
What I imagine.
private void showButton(ActionEvent e) {
if (is selected paneA){
get selected row
open view conataining information from selected row paneA
else if (is selected paneB) {
get selected row
open view conaining information from selected row paneB
}
}
For a tab view for example you can easily get the selected tab. Now is something like this possible for a splitpane?
I hope it is now more understandable.
Thanks in advance
I do not know of any way to watch which side of a SplitPane has been clicked on, but you can certainly register a listener on the Node you've placed within each side.
The example below creates a very simple interface with a VBox in each of the two SplitPane sides. We simply listen for a click on either VBox and respond accordingly:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class PaneSelectionExample extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
SplitPane splitPane = new SplitPane();
VBox.setVgrow(splitPane, Priority.ALWAYS);
// Two VBoxes with Labels
VBox box1 = new VBox() {{
setAlignment(Pos.TOP_CENTER);
getChildren().addAll(
new Label("One"),
new Label("Two"),
new Label("Three")
);
}};
VBox box2 = new VBox() {{
setAlignment(Pos.TOP_CENTER);
getChildren().addAll(
new Label("One"),
new Label("Two"),
new Label("Three")
);
}};
// Now, we'll add an EventListener to each child pane in the SplitPane to determine which
// has been clicked
box1.setOnMouseClicked(event -> System.out.println("Left Pane clicked!"));
box2.setOnMouseClicked(event -> System.out.println("Right Pane clicked!"));
// Add our VBoxes to the SplitPane
splitPane.getItems().addAll(box1, box2);
root.getChildren().add(splitPane);
// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
Incoming Opinion Alert
While this may solve your immediate question, you may want to revisit your decision to have only one Show button. Is the user going to expect that and understand which details the Show button will present?
It may be a better idea to have a separate Show button in each pane of the SplitPane; that seems more "standard" to me.
I made my program enter full-screen whenever both of the keyboard keys, alt and enter, are pressed at the same time. This mostly works as expected.
The issue is that my program will toggle full-screen mode whenever the enter key is pressed. It doesn't matter if the alt key is pressed.
How can I make it so that the program will not toggle full-screen mode when only the enter key is pressed.
I am using OpenJFX 11.
package application;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
public class Main extends Application {
final KeyCombination FullScreenKeyCombo =
new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_ANY);
#Override
public void start(Stage stage) {
GridPane grid = new GridPane();
Scene scene = new Scene(grid, 1600, 900);
stage.setScene(scene);
stage.show();
// create TextField and add to GridPane
TextField textField = new TextField();
grid.add(textField, 0, 0);
// toggle full-screen when alt + enter is pressed
scene.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
if(FullScreenKeyCombo.match(event)) {
stage.setFullScreen(!stage.isFullScreen());
}
});
}
public static void main(String[] args) {
launch(args);
}
}
In this line:
new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_ANY);
ALT_ANY means “I don’t care if the Alt key is pressed or not.”
Use ALT_DOWN instead:
new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_DOWN);
I would like to access a text area placed within a Tab. All the Tabs in the TabPane will have a TextArea. Unfortunately Tab is not an interface and there does not seem a way to change the type held inside of the TabPane so I can not see a way to make code know that there is going to be a TextArea inside of the generic tab without keeping a separate list of them somewhere outside. TabPane can only return a Tab and tab does not distinguish that it holds a TextArea and even if I make an extension of Tab and give it to the TabPane it will still only return a Tab. Keeping an outside list seems really hacky and I dont think that would ever be the intended design. So what am I missing here. I am not using FXML.
You could create your own extension of a Tab whose content is a TextArea and provide a getTextArea() method for it.
That way, you can know each Tab will have a TextArea and you can manipulate it however you would like.
Below is a simple application to demonstrate:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
// Simple UI
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
// Create the TabPane
TabPane tabPane = new TabPane();
// Create some TextAreaTabs to put into the TabPane
tabPane.getTabs().addAll(
new TextAreaTab("Tab 1", "This is tab 1!"),
new TextAreaTab("Tab 2", "This is tab 2!"),
new TextAreaTab("Tab 3", "This is tab 3!")
);
// A button to get the text from each tab
Button button = new Button("Print Text");
// Set the action for the button to loop through all the tabs in the TabPane and print the contents of its TextArea
button.setOnAction(e -> {
for (Tab tab : tabPane.getTabs()) {
// You'll need to cast the Tab to a TextAreaTab in order to access the getTextArea() method
System.out.println(tab.getText() + ": " +
((TextAreaTab) tab).getTextArea().getText());
}
});
// Add the TabPane and button to the root layout
root.getChildren().addAll(tabPane, button);
// Show the stage
primaryStage.setScene(new Scene(root));
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.show();
}
}
// This is the custom Tab that allows you to set its content to a TextArea
class TextAreaTab extends Tab {
private TextArea textArea = new TextArea();
public TextAreaTab(String tabTitle, String textAreaContent) {
// Create the tab with the title provided
super(tabTitle);
// Set the Tab to be unclosable
setClosable(false);
// Set the text for the TextArea
textArea.setText(textAreaContent);
// Set the TextArea as the content of this tab
setContent(textArea);
}
public TextArea getTextArea() {
return textArea;
}
}
A simpler option would be to simply cast the getContent() method for each Tab to a TextArea within your loop:
((Text Area) tab.getContent()).getText()
I find the first option to be more readable and flexible as you can configure all your tabs to be identical within one location.
So Im trying to have text on the left and buttons on the right, text should have constant size and buttons should resize to fill the rest of the window.
Here is my result so far:
I dont want my text over buttons, I want them to share the whole window.
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
GridPane buttons = new GridPane();
GridPane textGrid = new GridPane();
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
Button button1 = new Button();
Button button2 = new Button();
Button button3 = new Button();
Button button4 = new Button();
Button button5 = new Button();
button1.setText("Button1");
button2.setText("Button4");
button3.setText("Button3");
button4.setText("Button4");
button5.setText("Button5");
TextArea text1 = new TextArea();
text1.setText("Test");
text1.setPrefSize(100, 100);
button1.prefWidthProperty().bind(buttons.widthProperty());
button2.prefWidthProperty().bind(buttons.widthProperty());
button3.prefWidthProperty().bind(buttons.widthProperty());
button4.prefWidthProperty().bind(buttons.widthProperty());
button5.prefWidthProperty().bind(buttons.widthProperty());
button1.prefHeightProperty().bind(buttons.heightProperty());
button2.prefHeightProperty().bind(buttons.heightProperty());
button3.prefHeightProperty().bind(buttons.heightProperty());
button4.prefHeightProperty().bind(buttons.heightProperty());
button5.prefHeightProperty().bind(buttons.heightProperty());
buttons.addColumn(0, button1, button2, button3, button4, button5);
textGrid.addColumn(0, text1);
Scene scene = new Scene(root, 280, 180);
root.getChildren().addAll(buttons, textGrid);
buttons.setAlignment(Pos.TOP_RIGHT);
textGrid.setAlignment(Pos.TOP_LEFT);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
It is usually better to let the layout panes handle the layout management rather than trying to manage the layout through bindings.
Here is a sample:
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.util.stream.IntStream;
public class Main extends Application {
private static final int N_BUTTONS = 5;
#Override
public void start(Stage stage) {
VBox buttonLayout = new VBox(
10,
IntStream.range(0, N_BUTTONS)
.mapToObj(this::createButton)
.toArray(Button[]::new)
);
HBox.setHgrow(buttonLayout, Priority.ALWAYS);
TextArea textArea = new TextArea("Test");
textArea.setPrefWidth(100);
textArea.setMaxWidth(TextArea.USE_PREF_SIZE);
textArea.setMinWidth(TextArea.USE_PREF_SIZE);
HBox layout = new HBox(10, textArea, buttonLayout);
layout.setPadding(new Insets(10));
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
private Button createButton(int i) {
Button button = new Button("Button " + i);
// button.setMaxWidth(Double.MAX_VALUE);
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
VBox.setVgrow(button, Priority.ALWAYS);
return button;
}
public static void main(String[] args) {
launch(args);
}
}
Here are a couple of things I would point out based upon the sample:
As the buttons are so similar, create the buttons in a loop rather than individually in code. I use an IntStream range with a map and a toArray, but you could do the same thing with a standard for loop (which may be easier to understand).
Use combinations of standard layout panes to achieve your layout. For example the buttons are vertically spaced, so put them in a VBox, the text and the buttons are horizontal to each other, so use a HBox.
Use constraints on the layouts to massage them into performing the layout you like, for example, HBox.setHgrow(buttonLayout, Priority.ALWAYS); tells the Box to always assign any extra additional space in the Box to the buttonLayout so that the buttons will fill any remaining area.
Set constraints on the individual nodes to size them how you wish, for example the following code establishes a fixed width for the textArea, which will not vary (you could similar code to establish a fixed height if you wished):
textArea.setPrefWidth(100);
textArea.setMaxWidth(TextArea.USE_PREF_SIZE);
textArea.setMinWidth(TextArea.USE_PREF_SIZE);
Some controls will automatically expand themselves beyond their max size, buttons do not by default, to enable this behavior use the following code (if you only wanted the width to expand and not the height then you would only set the maxWidth rather than the maxSize):
button.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
Rather than defining layouts in code as in this example, instead use a tool such as SceneBuilder to create the scene visually and save the layout as an FXML file, so that the layout is separated from your code (similarly place any styling in an external CSS file).