Adjust the CSS styling for a newly added row in a JavaFX TableView

Apologies for any errors, I am French. I am currently facing an issue with an empty tableView in my project. There is a button labeled "Add" that adds a row to the tableView when clicked. Another button labeled "Cancel" appears when a row in the tableView is selected. However, the problem arises when clicking "Cancel" and then adding a new row, as the CSS class ".cancel" is applied to a different row without having clicked on the "Add" button.

I suspect there may be an issue with the row index.

In the initialize method:

articleTable.setRowFactory(param -> new TableRow<LigneTicket>() {
        @Override
        protected void updateItem(LigneTicket paramT, boolean empty) {
            super.updateItem(paramT, empty);
            if (!isEmpty() && paramT != null && paramT.getArticle().isArticleCanceled()) {
                getStyleClass().add("cancel");
            }
        }
    });

My code for the "Cancel" button:

public void cancelLigneTicket() {
    int indexSelected = articleTable.getSelectionModel().getSelectedIndex();
    articleTable.getItems().get(indexSelected).getArticle().setArticleAnnuler(true);

    articleTable.getSelectionModel().clearSelection();

    List<LigneTicket> items = new ArrayList<>(articleTable.getItems());

    articleTable.getItems().setAll(items);

    buttonAnnulArt.setVisible(false);

Please assist me with this issue. Thank you.

Answer №1

TableRows are specifically designed for displaying table items, but they aren't limited to just one item.

Here's what can happen with a row r:

  1. The item in r is changed to a canceled item, which adds the cancel CSS class.
  2. The item in r is updated to a non-canceled item, but the cancel CSS class is not removed.

To avoid unnecessary memory consumption and multiple additions of the style class, you must ensure that the class is removed when needed. Here's an example code snippet:

boolean canceled = !empty && paramT != null && paramT.getArticle().isArticleCanceled());
if (canceled) {
     if (!getStyleClass().contains("cancel"))
          getStyleClass().add("cancel");
} else {
     getStyleClass().remove("cancel");
}

You can also utilize PseudoClass for handling the cancel state:

private static final PseudoClass CANCELED = PseudoClass.getPseudoClass("cancel");

...
pseudoClassStateChanged(CANCELED, !empty && paramT != null && paramT.getArticle().isArticleCanceled());

Additionally, it is recommended to use TableView.refresh method (available in JavaFX >= 8u60) for updating cell items instead of copying and setting the items again.

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

What is the best way to capture the input value upon pressing the "Enter" key?

My first question here is about implementing the addtodo(todo) code. After trying it out successfully, I wanted to make it work when typing and pressing enter. However, despite attempting some other methods, I couldn't get it to work. I didn't re ...

Applying toggle() using css to manipulate various elements at once

Is there a way to toggle multiple divs of varying heights, all with the same class? What is the most effective approach to achieve this? http://jsfiddle.net/hS6RH/41/ $('.smallify').on('click', function() { if ($(this).parent(&apo ...

Positioning the HTML form in the middle of the page

The given HTML code generates a form within a table, but despite aligning the table to the center, it remains on the left side of the webpage. <!DOCTYPE html> <html> <head> <style>input.textfill { float: right; }&l ...

How can I prevent text highlighting on a website?

Is there a way to lock the copy button on my site without restricting the save as button, which is activated by right click? I want users to be able to save the website as an HTML file, but prevent them from copying text. Can this be achieved using Javas ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

Aligning the navigation links vertically

I am working on aligning my navigation bar vertically, even when I scroll the page. I found a method in another thread which suggests using the following CSS code for vertical alignment: #container { position: absolute; top: 50%; height: 400p ...

Issue with compiling Tailwindcss in nextjs JIT mode

Our current project involves using tailwindcss and things were going smoothly until the clients requested a "pixel perfect" design. This meant that every element needed to be set in pixels instead of rem units. Instead of adding countless classes like h-1p ...

HTML: Attempting to extract the inner div from the outer div and relocate it outside of the outer div

I am attempting to extract an inner div from an outer div and relocate it outside of the outer div. https://i.stack.imgur.com/NSS7B.png <div class="vc_gitem-zone-mini"> <div class="vc_gitem_row.............."></div> <div> I Would ...

Tips for inserting an HTML table into a div element using JQuery/JavaScript

I currently have a navigation bar with only two items. While I may potentially add more items in the future, for now I am content with just these two. Upon opening the page, my goal is to display the content of the first item in the navigation bar. Each it ...

I am having trouble getting my dropdown to line up with the drop button labeled "MORE"

Despite trying multiple approaches, I am still struggling to align the dropdown content with the dropbtn. My goal is to have the content consistently positioned below the more menu. HTML: ` <html> <meta name="viewport" content="width=device-widt ...

Full comprehension with a width of 100%

Here is an example where .flex2 has 2 children. 1st child - width: 300px 2nd child - width: 100% .b{ height: 50px; } .flex2{ margin-top: 20px; display: flex; .box{ background-color: blue; width: 300px; } .box1{ backgroun ...

Incorporate a horizontal scrollbar feature within an HTML section

Currently, I am in the process of learning vue js and would like to create a layout that includes two sections. The first section should occupy 3 grids on the screen, be fixed, and not scrollable, with a division into 4 vertical parts. The second section s ...

Is it possible to eliminate jagged edges in CSS 2D rasterization by applying anti-aliasing to subpixels?

It appears that the HTML/CSS engine automatically rounds values to the nearest whole px unit. It would be interesting to see non-discrete sizing options (floats). A closer look reveals that in Chrome, widths/heights are rounded to the nearest physical pix ...

A Step-by-Step Guide to Setting Up a Scoreboard for Your Rock Paper Scissors Game

I'm new to JavaScript and I want to create a rock, paper, scissors game from scratch. My Game Plan: Once the user clicks on an option (rock, paper, scissors), the game will display their score and the computer's score along with the result of t ...

I'm having trouble getting my .click method to work with the <div id=menuButton>. Can anyone help me figure out why this is happening?

Here is the HTML code I created for a dropdown menu. Initially, in the CSS file, the menu is set to display: none; <!doctype html> <html> <head> <title>DropDown Menu</title> <link rel="stylesheet" href="normalize ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

The relationship between formatting context and atomic inline-level boxes is crucial for understanding

Check out this link for more information on inline boxes An inline box is a unique element that falls under the category of both inline-level and participates in its containing inline formatting context. When a non-replaced element has a 'display&ap ...

What is the best way to customize the default button style for buttons in Angular Datables?

After integrating buttons into my Angular Datatables, I noticed that they have default styling, which makes them stand out from the rest of my web page (refer to the Column Visibility button in the screenshot below): https://i.sstatic.net/w7Y8g.png I att ...

Ways to eliminate extra space from the edges of a container

Trying to wrap my page in a Material UI container component, but there's this persistent whitespace on the outside that no matter how much I tweak the margin and padding, it just won't disappear. Any CSS wizard out there with a workaround to make ...