2

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

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

2 回答 2

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);
        }
于 2013-10-26T13:19:54.597 回答
1

用于super.paintComponent(g);自定义绘画代码而不是paintComponents. paintComponents留给 API 在需要时调用

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

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

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

于 2013-10-26T13:24:07.887 回答