【发布时间】:2021-03-13 15:26:12
【问题描述】:
我有这段代码,我正在尝试在背景中添加图片显示作为墙纸。我用这个stackoverflow post 作为参考,但它没有用。我的图像被添加到面板中,尽管不是作为背景。可能是什么问题?
旁注,.setLocation() 也不会更新按钮的位置。提前致谢!
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.sql.*;
class APP extends JPanel
{
JFrame frame = new JFrame();
JPanel panel;
class ImagePanel extends JComponent {
Image image;
public ImagePanel(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 100, 25, this);
}
}
public APP(){
JLabel picLabel = new JLabel();
try {
BufferedImage image = ImageIO.read(getClass().getResource("login_bg.jpg"));
this.setContentPane(new ImagePanel(image));
picLabel = new JLabel(new ImageIcon(image));
//picLabel.setBounds(100, 25, 843, 568);
} catch (IOException e){
e.printStackTrace();
}
panel = new JPanel(); // used to do padding like in HTML
panel.setBorder(BorderFactory.createEmptyBorder(50, 350, 300, 350));
panel.setLayout(null));
panel.add(picLabel);
frame.add(panel, BorderLayout.CENTER);
frame.getContentPane();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Drone Delivery");
frame.pack();
frame.setVisible(true);
}
}
【问题讨论】:
-
pastebin 因为它有 100 多行 - 帖子是正确的minimal reproducible example。我们对您的整个申请不感兴趣。创建一个框架只需要几行代码,而创建一个带有图像的 JLabel 或在面板上对图像进行自定义绘制应该只需要几行代码。在尝试解决问题时简化问题..
-
@camickr 是的,你说得对,我刚刚更新了代码以提高可读性
-
代码应该贴在这里。我们应该能够复制/粘贴/编译/测试并看到所描述的问题。
-
仍然不是 MRE。 1)代码不会编译。我们无权访问
GhostText类。 MigLayout 是第 3 方布局,与所述问题无关。 2) ActionListener 代码与所述问题无关。正如我在第一条评论中所说,您需要一个 JFrame,您将自定义组件作为背景添加到框架中。然后将单个组件添加到后台组件中。人们总是在测试之前编写整个应用程序,这总是让我感到惊讶。提示:1) 扩展 JPanel,而不是 JComponent。 2)然后您需要设置背景组件的布局管理器。 -
你是想要上课的人 - 不。您被要求提供minimal reproducible example。只有与问题直接相关的代码才包含在“MRE”中。其他一切都无关紧要。我给了你一些代码示例来简化问题。