I am drawing an image on JTextArea
background, it is drawn using other look and feels (Metal, Windows etc) but when I use Nimbus
Look And Feel it does not draw image What can be the possible problem and how to fix that?
Here is the code I am using
Image TextArea Class
public class ImageTextArea extends JTextArea{
File image;
public ImageTextArea(File image)
{
setOpaque(false);
this.image=image;
}
@Override
public void paintComponent(final Graphics g)
{
try
{
// Scale the image to fit by specifying width,height
g.drawImage(new ImageIcon(image.getAbsolutePath()).getImage(),0,0,getWidth(),getHeight(),this);
super.paintComponent(g);
}catch(Exception e){}
}
}
And the Test class
public class TestImageTextArea extends javax.swing.JFrame {
private ImageTextArea tx;
public TestImageTextArea() {
tx = new ImageTextArea(new File("img.jpg"));
setTitle("this is a jtextarea with image");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel mainp = new JPanel(new BorderLayout());
add(mainp);
mainp.add(new JScrollPane(tx), BorderLayout.CENTER);
setSize(400, 400);
}
public static void main(String args[]) {
/*
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {
System.out.println("Unable to use Nimbus LnF: "+ex);
}
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TestImageTextArea().setVisible(true);
}
});
}
}
When I remove the comments it does not draw image.
Basically, when you call
super.paintComponent
, it will call the UI delgate'supdate
method. This is where the magic happens.Below is the Nimbus's
SynthTextAreaUI
implementationAs you can see, it actually paints the background, with out regard for the opaque state of the component, then calls
paint
, which will call theBasicTextUI.paint
method (viasuper.paint
)This is important, as
BasicTextUI.paint
actually paints the text.So, how does that help us? Normally, I'd crucify someone for not calling
super.paintComponent
, but this is exactly what we're going to do, but we're going to do it knowing in advance what responsibility we're taking on.First, we're going to take over the responsibilities of
update
, fill the background, paint our background and then callpaint
on the UI delegate.Make no mistake. If you don't do this right, it will screw not only this component but probably most of the other components on your screen.