Wednesday, July 22, 2009

How to display a non-scrolling background for a Java JScrollPane

To add a background text (or image) to the back of a JTextArea that is inside a JScrollPane, you can use the following code. The advantage here is that the background text/image does NOT scroll with the text in the JTextArea. See screenshot below.
Here's the code:
public static void main(String[] args) {


JFrame frame = new JFrame("Overlay test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JScrollPane scroll = new JScrollPane();
scroll.getViewport().setBackground(Color.WHITE);

scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll.setPreferredSize( new Dimension(400,100));
frame.add(scroll);

final String text = "English";

final JTextArea ta = new JTextArea() {

 {setOpaque(false);}  // instance initializer

 public void paintComponent (Graphics g) {
   g.setFont(new Font("Verdana",Font.ITALIC,20));
   g.setColor(Color.LIGHT_GRAY);

   Rectangle rect = getVisibleRect();
   int x = rect.width + rect.x - 14*text.length();
   int y = rect.y + 20; // approx. height of the text
   g.drawString(text, x, y);
   super.paintComponent(g);
 }
};

ta.setText("This text area contains an overlayed text that is BEHIND this text and does not scroll");
ta.setPreferredSize( new Dimension(600,100));
scroll.setViewportView(ta);
frame.pack();
frame.setVisible(true);
}

No comments:

Post a Comment