You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX按钮未聚焦时底部空白问题及解决办法

移除JavaFX按钮未聚焦时底部空白的解决方案

JavaFX按钮在未获得焦点时底部会出现空白,即便自定义CSS样式也无法避免,在非纯色背景下会破坏界面美观。修改焦点样式无法解决该问题,因为空白出现在按钮未聚焦的状态下。

复现问题的最小代码

package com.example.buttonexample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        Button button1 = new Button("Login");
        Button button2 = new Button("Sign Up");
        HBox root = new HBox();
        root.setStyle("-fx-background-color: orange");
        button1.setPrefHeight(50);
        button2.setPrefHeight(50);
        root.getChildren().addAll(button1, button2);
        Scene newScene = new Scene(root);
        stage.setWidth(200);
        stage.setHeight(200);
        stage.setScene(newScene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

运行环境

  • Java版本:15
  • JavaFX版本:17.0.6
  • 操作系统:Windows 11 [Version 10.0.22631.2715]

解决方案

可以通过以下两种方式解决:

  • CSS方式:为按钮添加-fx-background-insets: 0,1,1;样式,覆盖默认的内边距配置
  • 代码方式:在Java代码中直接设置按钮的背景内边距,示例如下:
button1.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, new Insets(0,1,1,1))));

内容的提问来源于stack exchange,提问作者Danny600946

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:10:24