<Swing Dev> Background/Foreground colors and Gtk Look and Feel

Joel Uckelman uckelman at nomic.net
Thu Jun 25 20:04:35 UTC 2009


Thus spake Alexander Potochkin:
> Hello Joel
> 
> If you just need to have a multiple line JLabel,
> you may be interested in following discussion:
> 
> http://www.coderanch.com/t/338648/Swing-AWT-SWT-JFace/java/Multiple-lines-JLa
> bel
> 
> Thanks
> alexp
>

I wrote a brief demo just to test what they suggest:

import javax.swing.*;

public class Test {
  public static final String loremIpsum = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

  public static void main(String[] arg) throws Exception {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        final JTextArea area = new JTextArea(loremIpsum, 20, 20);
        area.setEditable(false);
        area.setCursor(null);
        area.setOpaque(false);
        area.setFont(UIManager.getFont("Label.font"));
        area.setWrapStyleWord(true);
        area.setLineWrap(true);

        final JScrollPane scroll = new JScrollPane(
          area,
          JScrollPane.VERTICAL_SCROLLBAR_NEVER,
          JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
        );

        scroll.getViewport().setOpaque(false);

        final JFrame frame = new JFrame();
        frame.add(scroll);
        frame.pack();
        frame.setVisible(true);
      }
    });
  }
}

My observation is that it is only by chance that this has the desired
behavior. The JTextArea ends up with the background color that a JLabel
would have because it just happens that in the LAF I'm using, JScrollPane
and JLabel have the same background color---but there is no necessary 
connection between them. There could just as easily be a LAF where
JScrollPane and JLabel do not share the same background color, and in
that case I'm right back where I started, as there's also no guarantee
that setBackground() will work.

So, I contend that this is still not a solution.

-- 
J.



More information about the swing-dev mailing list