Creating a lasting choice using CSS in a TableView in JavaFx

Update: Including project (reproducible example) and final details

I currently have an application that showcases a TableView populated with simple object instances (observable list)

The objective is to highlight selected items (rows) in the TableView.

For instance, if the user presses 'Insert', I update (in the observable list) the selected object by toggling a boolean value within it. This marking allows users to perform additional actions.

Unfortunately, using

myTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
results in losing the selection whenever a key is pressed or a mouse click occurs.

To address this issue, keyboard management is implemented as follows:


    public boolean implementListenerPackage(Scene s) {
          //initialization...
          s.setOnKeyReleased(new EventHandler<KeyEvent>() {
                @Override
                public void handle(KeyEvent ke) {
                    switch (ke.getCode()) {
                        case INSERT:
                            setObservableListObjectSelect();
                            break;
                   }
               }
        });
    }

The structure of the objects in the observable list is relatively straightforward:

public class myObject {
    private boolean selected;
    private String otherStuff = "";
// Constructor, getters, and setters follow

Furthermore, there is MouseEvent handling to manage other interactions. Upon creating the TableView, the following snippet is added:

                myTableView.setRowFactory(rftv-> {
                    TableRow<type> rowObj = new TableRow<>();
                    rowObj.setOnMousePressed(new EventHandler<MouseEvent>() {
                        @Override
                        public void handle(MouseEvent e) {
                           if (e.getClickCount() == 2 && (!rowObj.isEmpty())) {
                                SomeClass.doSomethingForDoubleClick()
                            } else { // Single click
                                SomeClass.doSomethingForSingleClick()
                            }
                        }
                    });
                    return rowObj;
                });

The goal is to modify the CSS of a row when the boolean value in myObject changes, allowing the user selection to remain highlighted even after clicking on another row.

Several strategies were attempted:

  • Extensive research was conducted to find relevant examples, however, most examples did not align with the current scenario.
  • Efforts were made to enhance the rowFactory implementation, but complications arose leading to null pointer exceptions.
  • Direct modification through keyboard management seemed complex, requiring updating the selected object, identifying selected cells, and adjusting CSS individually (based on column logic).
  • Exploration of implementing a binding mechanism between the object and the row proved challenging due to the differences in problem contexts.

The solution may be evident, yet remains elusive.


update: Considerations include:

  • Centralized keyboard management
  • Existing factory settings on the tableView.
  • Presence of multiple TableViews in the original application, necessitating automatic CSS style changes rather than hardcoded solutions.

A concise code excerpt:

package application;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.stage.Stage;
...

public class Main extends Application {

    Label lbl01 = new Label("Information");

    @Override
    public void start(Stage primaryStage) {
        try {
            ...
});

            KeyboardManagement km = new KeyboardManagement();
            km.implementListener(scene, lbl01, tv1);

            primaryStage.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

}
package application;

import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.input.KeyCode;
...

public class KeyboardManagement {
    public KeyboardManagement() {
    }
    
    ...

}

package application;


public class MyObject {

    private boolean keyboardSelected;
    private String dataA;
    private String dataB;
    private String dataC;

    public MyObject(boolean keyboardSelected, String dataA, String dataB, String dataC) {
            super();
            this.keyboardSelected = keyboardSelected;
            this.dataA = dataA;
            this.dataB = dataB;
            this.dataC = dataC;
        }

    ...

}

Answer №1

Discovered the solution!

The method is both simple and complex.

The key is to add a listener on the object property at the appropriate location.

  • Within the rowfactory definition.
  • Before the @override
  • Pass the row object as an argument and 'voila'.

Here's an example :

rowObj.itemProperty().addListener((observable, oldValue, newValue) -> updateTableRowCss(rowObj, newValue));

Key points:

  • You can attach multiple listeners to different object properties.

  • I recommend creating a separate method for the listener to call. Sometimes IDE syntax analyzers can be overwhelming. This approach helps in error detection within this type of code.

  • Based on my testing, it appears that the style modifications you make will take precedence over the preloaded style. Which is desirable.


This setup enables centralized keyboard management (as shown in this example) and mouse event management within the factory.

The cursor retains its free movement while maintaining a reusable object selection option.

The revised sample code from above:


    package application;
    
    import javafx.application.Application;
    // Remaining Java code has been omitted for brevity

See the final outcome

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Making Bootstrap div stretch vertically with absolutely positioned content

Is there a way to make the middle div expand vertically on screen sizes smaller than 1000px without causing the text to flow under the image in the third div? Even clearing floats doesn't seem to solve the issue. This code is based on Bootstrap 4.4. ...

Encountering an org.openqa.selenium.NoSuchSessionException error due to an invalid session ID while using Cucumber in a

I am utilizing Selenium, Cucumber, and TestNG for my testing purposes and I have a unique requirement where I need to close and reopen a new browser in between my test feature. This is necessary because the application I am testing does not have a logout f ...

what is the method to adjust vertical spacing on word wrap using css?

My initial question on this forum. I've noticed that my text is being cut off because it's too long for the given space. I'm wondering if there's a way to decrease the vertical spacing between the rows using CSS? ...

How can a borderless text field be created using Material UI?

Today, I delved into using Material UI for my React project. My goal is to create a registration form similar to this one. Essentially, I want 5 input text fields without any borders and with a simple background color effect when active. However, I'm ...

Issue with Payara 4.1.2.174 Deployment - Security Policy Linking Error Causing Module State Inconsistency

We encountered an issue with linking the security policy - Inconsistent Module State upon deployment from Jenkins. Although we are aware of a workaround involving deleting the security police from generated (Glassfish: Error in linking security policy for ...

Limiting style changes to specific labels in Highcharts

Can someone assist me in bolding only the middle elements of a highcharts x axis? I have tried to apply a solution in the provided fiddle but it doesn't work as expected. Specifically, I am looking to bold the x-axis labels for June or July. http://j ...

Changing the property types in subclasses in Java Android can be achieved by using overrides

I'm currently working on incorporating the MVP (Model-View-Presenter) pattern into my Android app, but I've hit a roadblock. I'm trying to create an abstract base presenter with a view class property of a generic type ViewInterface. However, ...

CSS/Jade/HTML: struggling to get boxes to align properly on the same line

I'm currently working with a Jade template that looks like this: extends layout block content h2 Characters and Portraits div(id="portraitsBox") - var portraits = ["Clown-Fox", "Dragon-Bear", "Fish-Bear", "Deer-Wolf", "Salamander-Ant", "Sid ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

What is the best way to anchor text to a specific area of an image when resizing?

I am struggling with maintaining consistent formatting for the center text on my splash/masthead/full page image, regardless of resizing. The image I am working with can be viewed [here]1 Originally, I attempted to incorporate the text into the backgrou ...

Guide on how to implement a jQuery toggle feature using pre-existing HTML markup

<div class="rsvp"> <div class="block"> <span class="rsvpNote"> <h4 class="rsvpTitle"> <a href="#" class="blockExpand" click="toggleRSVP(this); return false;"><span class="arrow"></spa ...

Postpone the execution of the toggleClass function

I have a tab that, when clicked, fades in to reveal content loaded with AJAX. However, the content loads immediately upon clicking the button. I attempted to use toggleClass with delay, but it was unsuccessful. How can I effectively delay the loading of t ...

Is it beneficial to control the versions of Java EE web application artifacts?

I currently have several Maven-based Java web applications that I deploy but do not release. Upon reflection, I've noticed that I rarely update the versions of the generated artifacts, as it seems like unnecessary work - updating versions across all ...

Issue with Spyscroll functionality

Having some trouble getting Spyscroll to work. Can anyone help me identify the issue? I've been at it all day... I've attempted both the javascript and html+css setups, but neither seem to be functioning correctly. Manually adding the "active" c ...

javascriptretrieve the second class from the element

HTML Code : <span class="button" onclick="javascript:buttonClicked();">Log In</span> <div class="modal-bg" style="display: none;"> <div class="modal"> <span>Log In<a href="#close" class="close">&# ...

Try applying CSS rotate3d to a div that is already rotated

Having trouble with the axis of a rotated div. Currently, the diamond rotates within its sides and I want it to rotate from the top center. Check out this example: http://jsfiddle.net/DtQd8/ HTML <div class="diamond"> <div class="diamondIn ...

What could be causing my tab code to not function flawlessly?

I am attempting to implement a tab concept on my website. For example, the tab names are Monday...Tue.. up to Sunday. Each tab contains an image file based on the days (size 460*620). When I run my page, it shows all images, but what I need is for the imag ...

Dynamic styling with jQuery input focus animation

Whenever I interact with the input field, I want my border colors to animate in and fade out smoothly. But I'm facing some challenges. Here is how I've set it up: HTML <input type="text" id="search-input" placeholder=&quo ...

Tips for Aligning an Image Just Above a Card in Mobile and Tablet Screens with Tailwind CSS

https://i.stack.imgur.com/tPXEQ.jpg https://i.stack.imgur.com/3XkJo.jpg Just a heads up, this code snippet performs well on desktop but may have some issues on mobile and tablet devices. If anyone in the StackOverflow Community can offer some assistance, ...

Exploring Webpack: Unveiling the Contrasts Between Production and Development CSS Bundles

Can you explain the differences in CSS between production and development when compiling with webpack? I've noticed that the production stylesheet seems to consider the entire website, whereas the development mode appears to only focus on the specifi ...