各位,我想在我的主窗体中加一张图片,不知道怎么加,能解决一下吗?最好是贴出几个例子 , 给我详细解说一下,图片的例子在网上找了一些,但都没看懂,不知道为什么要那样写,反正你们写的越详细越好,谢谢啦!!!
------解决方案--------------------
- Java code
import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Image;import java.awt.RenderingHints;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.SwingUtilities;@SuppressWarnings("serial")public class ImagePanel extends JPanel { private Image image; public ImagePanel(String imagePath) { image = new ImageIcon(imagePath).getImage(); } @Override protected void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.drawImage(image, 0, 0, getWidth(), getHeight(), null); } private static void createGuiAndShow() { JFrame frame = new JFrame("Image Demo"); frame.getContentPane().add(new ImagePanel("box.png")); // box.png是图片的路径 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 500); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createGuiAndShow(); } }); }}