我正在尝试在中心布局的顶部和按钮上显示文本。但是输出有点奇怪。它显示了很多按钮。这段代码有什么问题?
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);
}
}