我使用GUI设计器来创建JPanel
类。我正在尝试添加背景图像,但它没有显示任何内容。如果我在JLabel
某处放置JLabel
,则可以显示JPanel
。
我不认为图像路径有问题,因为我可以在另一个面板上显示此路径中保存的其他图像(使用JLabel
的setIcon()方法)。< / p>
背景图片的尺寸为1920x1080。
我已经搜索了很多帖子。有谁知道出了什么问题?
public class MenuPanel extends javax.swing.JPanel {
private final Image background;
public MenuPanel() {
initComponents();
background = new ImageIcon("/program/img/bg.jpg").getImage();
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(background, 0, 0, null);
}
@SuppressWarnings("unchecked")
private void initComponents() {
setPreferredSize(new java.awt.Dimension(800, 650));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 800, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 650, Short.MAX_VALUE)
);
}
}
public class GUI {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(800, 650));
MenuPanel m = new MenuPanel();
frame.add(m);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:-2)
您可以尝试从here实施示例。
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageTest {
public static void main(String[] args) {
ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}