我正在尝试通过覆盖paintComponent
方法将图像绘制到JPanel上。但是,我根本没有运气,我不知道为什么。
这是我目前获得的代码:
DrawPanel
public class DrawPanel extends JPanel{
private Image backgroundImg;
public DrawPanel()
{
backgroundImg = Toolkit.getDefaultToolkit().createImage("C:\\Users\\Administrator\\workspace\\Scrub\\src\\loginBackground.png");
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backgroundImg, 0, 0, null);
}
}
LoginWindow Class
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LoginWindow extends Window{
private DrawPanel panel;
public LoginWindow(int width, int height)
{
super("", width, height);
panel = new DrawPanel();
this.add(panel);
panel.setVisible(true);
}
}
主要
public class Main
{
public static void main(String[] args)
{
LoginWindow loginWindow = new LoginWindow(500, 300);
}
}
答案 0 :(得分:3)
这可能不起作用的原因很多
ImageIO.read
,因为如果出现问题,它会抛出IOException
例如
public class DrawPanel extends JPanel{
//...
public Dimension getPreferredSize() {
return backgroundImg == null ? new Dimesion(100, 100) : new Dimension(backgroundImg.getWidth(this), backgroundImg.gtHeight(this));
}
然后在你的Window类......
public LoginWindow(int width, int height)
{
super("", width, height);
panel = new DrawPanel();
this.add(panel);
// Swing components are visible by default
//panel.setVisible(true);
// windows aren't
setVisible(true);
}
更简单的孤独就是使用JLabel
...
setLayout(new BorderLayout());
BufferedImage img = ImageIO.read(new File(...));
JLabel label = new JLabel(new ImageIcon(img));
add(label);
setVisible(true);