javaswingjlayer

I follow the tutorial in oracle about JLayer but it doesn't work with this code


import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class MyJLayer extends JFrame {
    public static void main(String[] args) {
        MyJLayer jlayer = new MyJLayer();
        jlayer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        JButton button = new JButton("Debug Only.");
        panel.add(button);

        UI ui = new UI();
        JLayer<JPanel> jLayer = new JLayer<JPanel>(panel, ui);

        jlayer.add(jLayer);
        jlayer.setSize(100, 100);
        jlayer.setVisible(true);
    }
}
class UI extends LayerUI<JPanel>{
    public void paint(Graphics g, JPanel c){
        super.paint(g, c);
        Graphics2D g2d = (Graphics2D)g.create();
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f));
        g2d.setColor(Color.BLUE);
        g2d.fillRect(0, 0, c.getWidth(), c.getHeight());
        g2d.dispose();
    }
}

the panel doesn't display BLUE color at all, but I don't know why. Could anyone help me out? I just couldn't find out. http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html


Solution

  • Your paint method doesn't override a superclass method, so it's not being called. Change the signature to:

    public void paint(Graphics g, JComponent c)
    

    ... and add the @Override annotation so that in future, the compiler can find the problem for you...