【问题标题】:How to show tooltip only on those table cells which text is ellipsized (...)?如何仅在那些文本为椭圆(...)的表格单元格上显示工具提示?
【发布时间】:2017-08-10 13:19:44
【问题描述】:

为了创建工具提示,我使用以下基于 answer 的代码。

Callback<TableColumn,TableCell> existingCellFactory   = column.getCellFactory();
column.setCellFactory(c -> {
    TableCell cell = existingCellFactory.call((TableColumn) c);
    Tooltip tooltip = new Tooltip();
    tooltip.textProperty().bind(cell.textProperty());
    cell.tooltipProperty().bind(
            Bindings.when(Bindings.or(cell.e‌mptyProperty(), cell.itemProperty().isNull()))
                    .then((Tooltip) null).otherwise(tooltip));
    return cell ;
});

问题在于,在这种情况下,当用户在任何单元格工具提示上的表格上移动鼠标时,用户会得到太多工具提示。

如何仅在那些文本较宽的单元格上显示工具提示,并在最后替换为“...”?

【问题讨论】:

标签: java javafx


【解决方案1】:

这是我解决此问题的尝试。

注意:我正在使用基于 this answercom.sun.javafx.scene.control.skin.Utils。有些方法似乎被贬低了。此答案假定您使用的是默认字体。

此应用检查表格的每个表格单元格,并确定单元格内的文本是否为椭圆形。它使用了JavaFx 实用程序。

主要

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication5 extends Application {

    private final TableView<Person> table = new TableView<>();
    private final ObservableList<Person> data =
            FXCollections.observableArrayList(new Person("A", "B"), new Person("ZZZZZZZZZZZZZZZZ","XXXXXXXXXXXXXXXX"), new Person("ZZZ", "XXX"));
    final HBox hb = new HBox();

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setWidth(450);
        stage.setHeight(550);


        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<>("firstName"));

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<>("lastName"));

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol);

        final Button addButton = new Button("Add");
        addButton.setOnAction((ActionEvent e) -> {
            data.add(new Person("ZZZZZZZZZZZZZZZZ","XXXXXXXXXXXXXXXX"));
            data.add(new Person("ZZZ", "XXX"));
         });

        hb.getChildren().addAll(addButton);
        hb.setSpacing(3);

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(table, hb);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
        //ScenicView.show(scene);

        //loop through all the table cells
        for(TableColumn tableColumn : table.getColumns())
        {
            for(int i = 0; i < table.getItems().size(); i++)
            {                
                System.out.println(tableColumn.getCellData(i) + " isCellEllipsized: " + isCellEllipsized(tableColumn.getWidth(), tableColumn.getCellData(i).toString()));
            }
        }
    }

    boolean isCellEllipsized(double tableColumnWidth, String cellData)
    {
        Text text = new Text(cellData);//Convert String to Text
        double textActualWidth = text.getBoundsInLocal().getWidth();//Get the width of the Text object
        double textComputedWidth = Utility.computeTextWidth(text.getFont(), cellData, tableColumnWidth);//Use the utility. It returns how long the text should be if it needs to be ellipsized and the actual text lengh if it does not need to be ellipsized.

        return textActualWidth > textComputedWidth;
    }
    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;

        private Person(String fName, String lName) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }
    }
} 

实用类

/*
 * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.text.Bidi;
import java.text.BreakIterator;

import static javafx.scene.control.OverrunStyle.*;
import javafx.application.Platform;
import javafx.application.ConditionalFeature;
import javafx.geometry.Bounds;
import javafx.geometry.HPos;
import javafx.geometry.Point2D;
import javafx.geometry.VPos;
import javafx.scene.control.OverrunStyle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextBoundsType;

import com.sun.javafx.scene.text.HitInfo;
import com.sun.javafx.scene.text.TextLayout;
import com.sun.javafx.tk.Toolkit;

/**
 * BE REALLY CAREFUL WITH RESTORING OR RESETTING STATE OF helper NODE AS LEFTOVER
 * STATE CAUSES REALLY ODD NASTY BUGS!
 *
 * We expect all methods to set the Font property of helper but other than that
 * any properties set should be restored to defaults.
 */
public class Utility {

    static final Text helper = new Text();
    static final double DEFAULT_WRAPPING_WIDTH = helper.getWrappingWidth();
    static final double DEFAULT_LINE_SPACING = helper.getLineSpacing();
    static final String DEFAULT_TEXT = helper.getText();
    static final TextBoundsType DEFAULT_BOUNDS_TYPE = helper
            .getBoundsType();

    /* Using TextLayout directly for simple text measurement.
     * Instead of restoring the TextLayout attributes to default values
     * (each renders the TextLayout unable to efficiently cache layout data).
     * It always sets all the attributes pertinent to calculation being performed.
     * Note that lineSpacing and boundsType are important when computing the height
     * but irrelevant when computing the width.
     *
     * Note: This code assumes that TextBoundsType#VISUAL is never used by controls.
     * */
    static final TextLayout layout = Toolkit.getToolkit()
            .getTextLayoutFactory().createLayout();

    static double getAscent(Font font, TextBoundsType boundsType) {
        layout.setContent("", font.impl_getNativeFont());
        layout.setWrapWidth(0);
        layout.setLineSpacing(0);
        if (boundsType == TextBoundsType.LOGICAL_VERTICAL_CENTER) {
            layout.setBoundsType(TextLayout.BOUNDS_CENTER);
        } else {
            layout.setBoundsType(0);
        }
        return -layout.getBounds().getMinY();
    }

    static double getLineHeight(Font font, TextBoundsType boundsType) {
        layout.setContent("", font.impl_getNativeFont());
        layout.setWrapWidth(0);
        layout.setLineSpacing(0);
        if (boundsType == TextBoundsType.LOGICAL_VERTICAL_CENTER) {
            layout.setBoundsType(TextLayout.BOUNDS_CENTER);
        } else {
            layout.setBoundsType(0);
        }
        return layout.getBounds().getHeight();
    }

    static double computeTextWidth(Font font, String text,
            double wrappingWidth) {
        layout.setContent(text != null ? text : "",
                font.impl_getNativeFont());
        layout.setWrapWidth((float) wrappingWidth);
        return layout.getBounds().getWidth();
    }    
}

这个实用程序类应该像发布的那样工作。我从 Class 中删除了一些方法来满足这个站点字符约束。我从here 获得了 Utility 类。

【讨论】:

  • 感谢您的代码,但我没有看到任何工具提示。
  • 我为作为副本关闭的答案制作了这个。这只是尝试确定单元格是否为椭圆形。您可以将其合并到您的工具提示代码中。
【解决方案2】:

这应该可以解决您的问题。

column.setCellFactory(col -> new TableCell<Object, String>()
{
    @Override
    protected void updateItem(final String item, final boolean empty)
    {
        super.updateItem(item, empty);
        setText(item);
        TableColumn tableCol = (TableColumn) col;

        if (item != null && tableCol.getWidth() < new Text(item + "  ").getLayoutBounds().getWidth())
        {
            tooltipProperty().bind(Bindings.when(Bindings.or(emptyProperty(), itemProperty().isNull())).then((Tooltip) null).otherwise(new Tooltip(item)));
        } else
        {
            tooltipProperty().bind(Bindings.when(Bindings.or(emptyProperty(), itemProperty().isNull())).then((Tooltip) null).otherwise((Tooltip) null));
        }

    }
});

【讨论】:

    猜你喜欢
    • 2018-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2019-02-20
    相关资源
    最近更新 更多