我按照oracle关于JLayer的教程进行操作,但它不能使用这段代码

时间:2014-11-03 17:11:50

标签: java swing jlayer

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();
    }
}

面板根本不显示蓝色,但我不知道为什么。 任何人都可以帮我吗? 我只是找不到。 http://docs.oracle.com/javase/tutorial/uiswing/misc/jlayer.html

1 个答案:

答案 0 :(得分:4)

您的paint方法不会覆盖超类方法,因此不会被调用。将签名更改为:

public void paint(Graphics g, JComponent c)

...并添加@Override注释,以便将来编译器可以为您找到问题......