你知道java如何在窗体当中插入图片吗?具体的方法是什么?应该如何去实现呢?下面带着这个疑问,一起通过文章内容来找到答案吧!
首先来看一下整体的结构:
GameFrame.java:
package cn.bjsxt.test; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class GameFrame extends Frame { Image image = GameUtil.getImage("images/sun.jpg"); public void launchFrame() { setSize(500, 500); setLocation(100, 100); setVisible(true); addWindowListener(new WindowAdapter() { // 单击右键选择“source”中的“override/implement // methods”,frame里面勾选“windowClosed”点击“OK” @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } // 单击右键选择“source”中的“override/implement // methods”,window里面勾选“paint(graphic)”点击“OK” @Override public void paint(Graphics g) { g.drawLine(100, 100, 200, 200); g.drawRect(100, 100, 200, 200); g.drawOval(100, 100, 200, 200); Font f = new Font("宋体", Font.BOLD, 30); g.setFont(f); g.drawString("第一次画图", 200, 200); g.fillRect(100, 100, 20, 20); Color c = g.getColor(); g.setColor(Color.red); g.fillOval(300, 300, 20, 20); g.setColor(c); g.drawImage(image, 200, 200, null); } public static void main(String[] args) { GameFrame gf = new GameFrame(); gf.launchFrame(); } }
GameUtil.java:
package cn.bjsxt.test; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; public class GameUtil { private GameUtil() {} public static Image getImage(String path) { URL u = GameUtil.class.getClassLoader() .getResource(path); BufferedImage image = null; try { image = ImageIO.read(u); } catch (IOException e) { e.printStackTrace(); } return image; } }
下面是运行结果:
关于java在窗体当中插入图片的实现方式你都清楚了吧!假如你还有更多java编程常见问题,可以继续通过奇Q工具网来找到解决方法哦!
推荐阅读: