将图像添加到JPanel背景中

时间:2011-08-27 21:57:06

标签: java swing jpanel image-resizing

如何将图像添加到JPanel背景中。图像不会缩放或调整大小。感谢。

2 个答案:

答案 0 :(得分:2)

/**
 * @author
 *
 */
public class ImagePanel extends JPanel {

    private Image image = null;

    public ImagePanel(String filename) {
        this.image = new ImageIcon(filename).getImage();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        ImagePanel panel = new ImagePanel("resources/image.jpg");

        JFrame frame = new JFrame("Frame");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel, BorderLayout.CENTER);
        frame.setVisible(true);
    }
}

答案 1 :(得分:-1)

您可以覆盖以下方法之一:

JComponent.paint(Graphics g)
JComponent.paintComponent(Graphics g)