Search code examples
javaswingscrolljscrollpane

Scroll through JLabel held in JScrollPane


I have a JScrollPane that holds a JLabel using the following code:

//Create TEXT LOG JPanel textLogPane = new JScrollPane(logLabel); textLogPane.setPreferredSize(textLogPaneDim); //textLogPane.setOpaque(true); textLogPane.setBorder(BorderFactory.createLineBorder(Color.BLACK)); textLogPane.getViewport().setBackground(Color.DARK_GRAY);

The JLabel, logLabel, is represented by a string with an HTML encoding using
for carriage returns. I display certain images based on the contents of certain lines and I would like to be able to scroll the JScrollPane, textLogPane, to show that line whenever I am displaying that graphic. I know the contents of the line that I want to display but I can't seem to figure out how to get it to scroll down(or up) to the relevant line.

If need be I can change to something other than a JLabel as long as I can keep the HTML encoding and have it look just like multiple lines of text.

Sorry if this is a repeat I tried searching but couldn't find any results.

Thanks


Solution

  • You can do some custom maths and use scrollRectToVisible() in your viewport. I don't know how to compute the rect of a specific line in your JLabel. A better solution would be to stick your strings into a JList instead, perhaps with a custom renderer for the html, and use

    list.ensureIndexIsVisible(list.getSelectedIndex());