jjzjj

java - 如何绕过 JavaFX 的 TableView "placeholder"?

coder 2024-03-07 原文

JavaFX 的 TableView 有一个 placeholder属性基本上是一个 Node,只要它为空,它就会显示在 TableView 中。如果此属性设置为 null(其默认值),它将显示为 Label 或其他一些基于文本的 Node,表示“表中没有内容”。

但是如果表格中有任何数据行,那么占位符 Node 就会消失并且 TableView 中的整个垂直空间会被行填充,包括空行如果没有足够的数据来填满整个表格。

这些空行是我想要的,即使表格是空的。换句话说,我根本不想使用占位符。有谁知道我该怎么做?

我宁愿不做一些笨拙的事情,比如在 TableView 中放一个看起来空的行,但实际上它应该是空的。

最佳答案

不幸的是,old issue在 fx9 和更高版本(包括 fx18)中仍未修复。

fx9 的原始皮肤修改(见水平线下方)似乎仍适用于 fx18。尽管可以稍微改进,因为 fx12 引入了对流和 tableHeaderRow 的访问。

在尝试将其调整为更新的 api 时,我想出了一个 - 同样肮脏 且未经测试的 - 方法。这个想法是覆盖实际的布局方法,即在布置表格的各个子项时调用的方法,注意占位符并将其替换为流程:

public class NoPlaceHolderSkin<T> extends TableViewSkin<T> {

    public NoPlaceHolderSkin(TableView<T> control) {
        super(control);
    }

    @Override
    protected void layoutInArea(Node child, double areaX, double areaY, double areaWidth,
            double areaHeight, double areaBaselineOffset, HPos halignment, VPos valignment) {
        if (child.getStyleClass().contains("placeholder")) {
            child.setVisible(false);
            child = getVirtualFlow();
            child.setVisible(true);
        }
        super.layoutInArea(child, areaX, areaY, areaWidth, areaHeight, areaBaselineOffset, halignment, valignment);
    }
}

因此在 fx9 的上下文中重新审视了黑客。有好有坏的变化:

  • 皮肤已移至公共(public)包中,现在允许在不访问隐藏类的情况下对其进行子类化(好)
  • 移动introduced a bug不允许安装自定义 VirtualFlow(已在 fx10 中修复)
  • 将来某个时候将强烈禁止对隐藏成员的反射访问(阅读:不可能)

在挖掘过程中,我注意到这些 hack 有非常轻微的故障(注意:我没有针对 fx8 运行它们,所以这些可能是 fx8 与 fx9 的差异造成的!)

  • 占位符/流的强制可见性工作正常,除非从空表开始(显示占位符)并在空表时放大表("new"区域看起来是空的)
  • 将 itemCount 伪造为非空让行在按下导航键时消失(这可能不是一个大问题,因为用户往往不会导航空表)——这在 fx9 中肯定引入,在 fx8 中工作正常

所以我决定继续执行可见性:出现轻微故障的原因是 layoutChildren 在认为占位符可见时不会对流进行布局。如果 super 没有,则通过在布局中包含流来处理。

自定义皮肤:

/**
 * TableViewSkin that doesn't show the placeholder.
 * The basic trick is keep the placeholder/flow in-/visible at all 
 * times (similar to https://stackoverflow.com/a/27543830/203657).
 * <p> 
 * 
 * Updated for fx9 plus ensure to update the layout of the flow as
 * needed.
 * 
 * @author Jeanette Winzenburg, Berlin
 */
public class NoPlaceHolderTableViewSkin<T> extends TableViewSkin<T>{

    private VirtualFlow<?> flowAlias;
    private TableHeaderRow headerAlias;
    private Parent placeholderRegionAlias;
    private ChangeListener<Boolean> visibleListener = (src, ov, nv) -> visibleChanged(nv);
    private ListChangeListener<Node> childrenListener = c -> childrenChanged(c);
    
    /**
     * Instantiates the skin.
     * @param table the table to skin.
     */
    public NoPlaceHolderTableViewSkin(TableView<T> table) {
        super(table);
        flowAlias = (VirtualFlow<?>) table.lookup(".virtual-flow");
        headerAlias = (TableHeaderRow) table.lookup(".column-header-background");
        
        // startet with a not-empty list, placeholder not yet instantiatet
        // so add alistener to the children until it will be added
        if (!installPlaceholderRegion(getChildren())) {
            installChildrenListener();
        }
    }


    /**
     * Searches the given list for a Parent with style class "placeholder" and
     * wires its visibility handling if found.
     * @param addedSubList
     * @return true if placeholder found and installed, false otherwise.
     */
    protected boolean installPlaceholderRegion(
            List<? extends Node> addedSubList) {
        if (placeholderRegionAlias !=  null) 
            throw new IllegalStateException("placeholder must not be installed more than once");
        List<Node> parents = addedSubList.stream()
                .filter(e -> e.getStyleClass().contains("placeholder"))
                .collect(Collectors.toList());
        if (!parents.isEmpty()) {
            placeholderRegionAlias = (Parent) parents.get(0);
            placeholderRegionAlias.visibleProperty().addListener(visibleListener);
            visibleChanged(true);
            return true;
        }
        return false;
    }


    protected void visibleChanged(Boolean nv) {
        if (nv) {
            flowAlias.setVisible(true);
            placeholderRegionAlias.setVisible(false);
        }
    }


    /**
     * Layout of flow unconditionally.
     * 
     */
    protected void layoutFlow(double x, double y, double width,
            double height) {
        // super didn't layout the flow if empty- do it now
        final double baselineOffset = getSkinnable().getLayoutBounds().getHeight() / 2;
        double headerHeight = headerAlias.getHeight();
        y += headerHeight;
        double flowHeight = Math.floor(height - headerHeight);
        layoutInArea(flowAlias, x, y,
                width, flowHeight,
                baselineOffset, HPos.CENTER, VPos.CENTER);
    }


    /**
     * Returns a boolean indicating whether the flow should be layout.
     * This implementation returns true if table is empty.
     * @return
     */
    protected boolean shouldLayoutFlow() {
        return getItemCount() == 0;
    }


    /**
     * {@inheritDoc} <p>
     * 
     * Overridden to layout the flow always.
     */
    @Override
    protected void layoutChildren(double x, double y, double width,
            double height) {
        super.layoutChildren(x, y, width, height);
        if (shouldLayoutFlow()) {
            layoutFlow(x, y, width, height);
            
        }
    }

    /**
     * Listener callback from children modifications.
     * Meant to find the placeholder when it is added.
     * This implementation passes all added sublists to 
     * hasPlaceHolderRegion for search and install the 
     * placeholder. Removes itself as listener if installed.
     * 
     * @param c the change 
     */
    protected void childrenChanged(Change<? extends Node> c) {
        while (c.next()) {
            if (c.wasAdded()) {
                if (installPlaceholderRegion(c.getAddedSubList())) {
                    uninstallChildrenListener();
                    return;
                }
                
            }
        }
    }


    /**
     * Installs a ListChangeListener on the children which calls
     * childrenChanged on receiving change notification. 
     * 
     */
    protected void installChildrenListener() {
        getChildren().addListener(childrenListener);
    }
    
    /**
     * Uninstalls a ListChangeListener on the children:
     */
    protected void uninstallChildrenListener() {
        getChildren().removeListener(childrenListener);
    }
    
    
}

使用示例:

public class EmptyPlaceholdersInSkin extends Application {

    private Parent createContent() {
        // initially populated
        //TableView<Person> table = new TableView<>(Person.persons()) {
        // initially empty
        TableView<Person> table = new TableView<>() {

            @Override
            protected Skin<?> createDefaultSkin() {
                return new NoPlaceHolderTableViewSkin<>(this);
            }
            
        };
        TableColumn<Person, String> first = new TableColumn<>("First Name");
        first.setCellValueFactory(new PropertyValueFactory<>("firstName"));
        
        table.getColumns().addAll(first);
        
        Button clear = new Button("clear");
        clear.setOnAction(e -> table.getItems().clear());
        clear.disableProperty().bind(Bindings.isEmpty(table.getItems()));
        Button fill = new Button("populate");
        fill.setOnAction(e -> table.getItems().setAll(Person.persons()));
        fill.disableProperty().bind(Bindings.isNotEmpty(table.getItems()));
        BorderPane pane = new BorderPane(table);
        pane.setBottom(new HBox(10, clear, fill));
        return pane;
    }


    @Override
    public void start(Stage stage) throws Exception {
        stage.setScene(new Scene(createContent()));
        stage.show();
    }

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

    @SuppressWarnings("unused")
    private static final Logger LOG = Logger
            .getLogger(EmptyPlaceholdersInSkin.class.getName());

}

关于java - 如何绕过 JavaFX 的 TableView "placeholder"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16992631/

有关java - 如何绕过 JavaFX 的 TableView "placeholder"?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  5. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  6. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  7. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  8. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

随机推荐