JTable, JTextArea or JEditorPane to highlight lines of code?
Asked Answered
W

2

6

Update:

I've found a partial solution in this answer here, by adding the following code:

class CustomRenderer extends DefaultTableCellRenderer 
{
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
    {
        Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        c.setBackground(new java.awt.Color(255, 72, 72));
        return c;
    }
}

And then passing it to my JTable object:

jTable2.setDefaultRenderer(String.class, new CustomRenderer());

This works correctly and now the table rows are coloured red:

Psuedocode Panel

The only thing I need to know now is how to restrict the colouring to a single row and a single cell.

After further research I need a setCellRender() method so that I can set the custom render on a particular cell, but this method doesn't exist.


Question:

I want to create a visual component of step-by-step pseudocode execution.

To do this I have created a JTable and now I am looking for ways to highlight each row (or cell since there is only one column) to display which line is being executed.

I've included a mockup below on the final GUI. As you can see in the Pseudocode panel I've highlighted the final row.

Please ignore the arrows they are not strictly related to the question.

Wireframe

I've started to implement the mockup in Netbeans Matisse (this is 1 of 3 algorithms). However I don't know how to highlight the single line code line 1 in the JTable component.

Would it be easier to use a different type of component?

Later I'll also need to be able to re-color individual cells as show in the mockup's Table JPanel. How can this be implemented?

Partial implementation

Weitman answered 6/3, 2012 at 21:9 Comment(4)
I can set the custom render on a particular cell - no that's not what you need :-) Instead, you need a custom renderer which decides about the visuals of its rendering component based on the parameters passed into the getXXCellRendererComponent, see f.i. docs.oracle.com/javase/tutorial/uiswing/components/table.htmlRihana
I see. So I set the custom renderer to all cells and then check which cell needs highlighting within the custom renderer method? I still don't know how to check what cell I am in within the custom renderer method.Weitman
I don't understand what you don't understand ;-) The parameters of the method tell you all you need to know. You did read the tutorial I linked to above, didn't you?Rihana
If I do a condition statement in my getTableCellRendererComponent method - if(column == 0 && row == 1) c.setBackground(new java.awt.Color(255, 72, 72)); it still paints all cells red.Weitman
C
3

1) use JTextPane for supporting styled text, there you have three choices

  • use HighLighter

  • use Html formatted text (Java6 in current form supporting <= Html3.2 and with reduced supporting of css, sure in compare with Html5)

  • combine both a.m. options together

  • write own EditorKit or HtmlEditorKit (thanks to @stryba)

2) for JTable pass desired value to the prepareRenderer() rather than implement getTableCellRendererComponent()

3) if value for JSlider is modifiable (from another JComponents) then look for BoundedRangeModel

Cabrales answered 6/3, 2012 at 21:31 Comment(6)
Just to add one more possible to point 1) you can also create your own EditorKit with its own View, which is a more work but usually outperforms the other optionsBrigette
@Brigette thank you for notice, hmmm for all EditorKit or HtmlEditorKit rellated questions is there our (JTextComponent's King @StanislavL),Cabrales
-1 for 2) (time to start a quest against that spreading not quite correct advice :-) that's not the general way to achieve visual cell decorations in application code, instead custom renderers are. The basic rule is: never-ever extend a JSomething for application needs, they are meant to be used as-is. That said: extending core components with additional functionality (in this context f.i. add api to allow custom striping) is fine: this allows to re-use the extended component without further extension in all your applications, they can configure the custom component as appropriate.Rihana
This answer and the comment above have left me slightly confused. I assume that I should extend JTable in a custom class and ?override? the prepareRenderer() method. I should confess also that I am not very well experience with Java Swing.Weitman
1) maybe would be better waiting for @kleopatra's reply, 2) this comment is about pass desired value and be sure basically her honesty have got true, and more than valuable, in the case that you know something about Swing, 3) I have to notice this not possible to answering your question without edit your question with a SSCCE, 4) I take this question as interview only,Cabrales
hmmm... as often as I read the bullets in your comment, I can't make much sense out of them, except the part about the SSCCE :-)Rihana
U
2

A small code for your help, how to achieve highlighting specific text literal with desired background on JTextPane :

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;

public class TextPaneTest extends JFrame
{
    private JPanel topPanel;
    private JTextPane tPane;

    public TextPaneTest()
    {
        topPanel = new JPanel();        

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);            

        EmptyBorder eb = new EmptyBorder(new Insets(10, 10, 10, 10));

        tPane = new JTextPane();                
        tPane.setBorder(eb);
        //tPane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
        tPane.setMargin(new Insets(5, 5, 5, 5));

        topPanel.add(tPane);

        appendToPane(tPane, "My Name is Too Good.\n", Color.RED, Color.YELLOW);
        appendToPane(tPane, "I wish I could be ONE of THE BEST on ", Color.BLUE, Color.WHITE);
        appendToPane(tPane, "Stack", Color.PINK, Color.WHITE);
        appendToPane(tPane, "Over", Color.YELLOW, Color.RED.brighter());
        appendToPane(tPane, "flow", Color.BLACK, Color.GREEN.darker());

        getContentPane().add(topPanel);

        pack();
        setVisible(true);   
    }

    private void appendToPane(JTextPane tp, String msg, Color c, Color bColor)
    {
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        aset = sc.addAttribute(aset, StyleConstants.Background, bColor);
        //  aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);

        aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
        aset = sc.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);

        int len = tp.getDocument().getLength();
        tp.setCaretPosition(len);
        tp.setCharacterAttributes(aset, false);
        tp.replaceSelection(msg);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new TextPaneTest();
                }
            });
    }
}

Here is the output :

JTEXTPANE TEXT HIGHLIGHTING

Un answered 7/3, 2012 at 4:58 Comment(2)
Thank you for your answer. Although that addresses another issue I have in the Calculations Area it still doesn't address the problem I am having with colouring JTable cells.Weitman
@Ash : Ahhh... Wish I could help you on JTable s, but my knowledge in them is way too short. I am sorry about that. But hoping this answer might help you somewhere in your endeavour and hopefully you might find your answer soon :-)Un

© 2022 - 2024 — McMap. All rights reserved.