gpt4 book ai didi

Javafx 按钮突出显示

转载 作者:行者123 更新时间:2023-11-30 01:59:10 27 4
gpt4 key购买 nike

enter image description here

我想做的是,请参阅随附的屏幕截图。一旦我点击按钮 1-4 之间的按钮,它就会以红色突出显示,保持突出显示状态,直到我选择按钮 1 和按钮 4 之间的任何其他按钮,然后突出显示所选按钮应该是突出显示。我可以用集中属性来做到这一点。但我的场景上还有其他按钮,例如按钮 5,6 和 7。一旦我单击任何其他按钮或单击另一个控件焦点和红色消失。但我希望单击的按钮保持突出显示状态,或者显示选择了哪个按钮(按钮 1 和按钮 4 之间)的标志。

最佳答案

我建议为此使用 ToggleGroupToggleButtonToggleGroup 允许您的用户一次只能选择一个按钮。选择该按钮后,您可以设置所需的样式。

在下面的示例程序中,组中有 6 个切换按钮,并且在任何给定时间只能选择一个。所选按钮将具有红色背景(突出显示)。您创建的任何没有此样式的按钮都不会受到影响。

下面的代码也被注释了:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ButtonHighlights 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);

// Create a ToggleGroup to hold the list of ToggleButtons. This will allow us to allow the selection of only one
// ToggleButton at a time
ToggleGroup toggleGroup = new ToggleGroup();

// Create our 6 ToggleButtons. For this sample, I will use a for loop to add them to the ToggleGroup. This is
// not necessary for the main functionality to work, but is used here to save time and space
for (int i = 0; i < 6; i++) {
ToggleButton button = new ToggleButton("Button #" + i);

// If you want different styling for the button when it's selected other than the default, you can either
// use an external CSS stylesheet, or apply the style in a listener like this:
button.selectedProperty().addListener((observable, oldValue, newValue) -> {

// If selected, color the background red
if (newValue) {
button.setStyle(
"-fx-background-color: red;" +
"-fx-text-fill: white");
} else {
button.setStyle(null);
}
});

// Add the button to our ToggleGroup
toggleGroup.getToggles().add(button);
}

// Add all our buttons to the scene
for (Toggle button :
toggleGroup.getToggles()) {
root.getChildren().add((ToggleButton) button);
}

// Show the Stage
primaryStage.setWidth(300);
primaryStage.setHeight(300);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}

The Result:

screenshot

关于Javafx 按钮突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464570/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com