gpt4 book ai didi

java - JButton设置背景图片后多次显示

转载 作者:行者123 更新时间:2023-11-30 08:29:11 25 4
gpt4 key购买 nike

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

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

最佳答案

应该是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);
}

关于java - JButton设置背景图片后多次显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19607044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com