How to force repaint of JTable, JScrollPane?

I’m creating a top-down parser, that checks the syntax of a given source code according to a given grammar, then displays the result, within a simple GUI.

Basically, the user selects the grammar and source files, clicks “Check Syntax” and the result is displayed like in the picture…

First time

And it initially works fine. However, when selecting different files or updating a selected file, then clicking the “Check Syntax” button again, some graphical issues start to occur after interactions such as scrolling, resizing, or clicking rows:

After modifying input files

The issues are more apparent when resizing the window:

enter image description here

Here is the structure, of the frame:

JFrame frame
  JPanel headerPanel
    ...
  JPanel bodyPanel
    JLabel tableTitle
    JScrollPane tableScrollPane
      JTable table
    JLabel tableSummary

I’ve tried methods such as revalidate() and repaint() on components where issues happen, but they only fixed those of labels…

I’ve also tried using a SwingWorker but it didn’t solve the issue.

Here is the code portion that might be relevant:

                ...

                var tableScrollPane = new JScrollPane(table);
                tableScrollPane.setBorder(new MatteBorder(0,1,0,1, palette.get("strongTeal")));
                tableScrollPane.setBackground(palette.get("strongTeal"));
                tableScrollPane.revalidate();
                tableScrollPane.repaint();

                ...

                var bodyPanel = new JPanel();
                bodyPanel.setLayout(new BorderLayout());
                bodyPanel.add(tableTitle, BorderLayout.NORTH);
                bodyPanel.add(tableScrollPane, BorderLayout.CENTER);
                bodyPanel.add(tableSummary, BorderLayout.SOUTH);
                bodyPanel.setBorder(new EmptyBorder(45,45,45,45));
                bodyPanel.revalidate();
                bodyPanel.repaint();

                frame.add(bodyPanel, BorderLayout.CENTER);
                frame.setVisible(true);

                ...

Any ideas on how to force the frame or target components to redraw completely (that is to forget about previous state, and only show the newest information when scrolling, resizing, etc…), ultimately overcoming these issues? Thank you.

Answer

. However, when selecting different files or updating a selected file, then clicking the “Check Syntax” button again, some graphical issues start to occur

Don’t keep creating new components. The old components are still added to the frame. So now you have two sets of components.

Instead, you can replace:

  1. the data in the JTable by using table.setModel( yourTableModel )
  2. the component in the JScrollPane by using scrollPane.setViewportView( yourTable )

Leave a Reply

Your email address will not be published. Required fields are marked *