设置背景图像后,JButton会多次显示

时间:2013-10-26 13:03:34

标签: java swing

我正在尝试在顶部显示文本,在中心布局中显示按钮。但输出有点奇怪。它显示了很多按钮。这段代码有什么问题?

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.awt.Toolkit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ImagePaneTest {

    public static void main(String a[]) {
        TransparentPanel transparentPanel = new TransparentPanel(
                new BorderLayout());

        JPanel p = new JPanel();
        JLabel la = new JLabel("Title");
        p.add(la);
        p.setOpaque(false);

        JPanel p1 = new JPanel();
        JButton la1 = new JButton("Button");
        p1.add(la1);
        p1.setOpaque(false);

        JFrame fr = new JFrame();

        fr.getContentPane().add(transparentPanel);
        transparentPanel.add(p, BorderLayout.NORTH);
        transparentPanel.add(p1, BorderLayout.CENTER);

        fr.setSize(500, 500);
        fr.setVisible(true);
    }

}

class TransparentPanel extends JPanel {

    public TransparentPanel(LayoutManager l) {
        super.setLayout(l);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponents(g);

        Image image = Toolkit.getDefaultToolkit().getImage(
                ImagePaneTest.class.getResource("/images/startback.jpg"));

        g.drawImage(image, 0, 0, null);
    }
}

2 个答案:

答案 0 :(得分:2)

应为super.paintComponent(g);

@Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Image image = Toolkit.getDefaultToolkit().getImage(
                    ImagePaneTest.class.getResource("/images/startback.jpg"));

            g.drawImage(image, 0, 0, null);
        }

答案 1 :(得分:1)

使用super.paintComponent(g);代替paintComponents自定义绘画代码。 paintComponents已离职 到需要时调用的API

来自http://www.oracle.com/technetwork/java/painting-140037.html

  

Swing程序应覆盖paintComponent()而不是覆盖   涂料()。尽管API允许,但通常没有理由   覆盖paintBorder()或paintComponents()(如果你这样做,请确保   你知道你在做什么!)。

编辑:我刚看到你压倒paintComponent,所以超级电话应该也是paintComponent