Search code examples
javaswingjscrollpanejtextareajoptionpane

JScrollPane acts funny inside of a JOptionsPane


I have tried to add a scroll view to a JOptionsPane, so that the information window can handle more text. It does add a scroll pane to the window. However, it acts funny on scrolling. The first visible text is shown clearly, but when you start scrolling, the text parts will overlap each other, until the text area is all black.

Do you have an explanation of how this can be and maybe a solution to the problem?

My code looks like this:

public void showInfoNoTranslation(String info) {
    frame.requestFocusInWindow();

    // create a JTextArea
    JTextArea textArea = new JTextArea(info, 6, 25);
    textArea.setEditable(false);
    textArea.setBackground(new Color(255, 255, 255, 0));
    textArea.setBorder(BorderFactory.createEmptyBorder());
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);

    // if (textArea.getLineCount() > 5) {
    JScrollPane scrollPane = new JScrollPane(textArea);
    JOptionPane.showMessageDialog(_frame, scrollPane, "title", JOptionPane.INFORMATION_MESSAGE);
}

Solution

  • Call textArea.setOpaque(false); instead of setting it's background-color to fully transparent and it will work.


    From the docs:

    public void setOpaque(boolean isOpaque)
    
    If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
    
    The default value of this property is false for JComponent. However, the default value for this property on most standard JComponent subclasses (such as JButton and JTree) is look-and-feel dependent.