show java使用教程_imageshow.java

这是一个Java程序,用于在窗口中显示图像。程序创建了一个`ImageFrame`类,继承自`JFrame`,并在其中添加了一个`ImagePanel`。`ImagePanel`类继承自`JPanel`,在`paintComponent`方法中绘制了指定路径的图像文件,确保图像居中显示。
摘要由CSDN通过智能技术生成

//ImageShowimport java.awt.*;import javax.swing.*;public class ImageShow{ public static void main(String[] args){ ImageFrame frame = new ImageFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.show();}}class ImageFrame extends JFrame{public ImageFrame(){setTitle("ImageShow");setSize(WIDTH, HEIGHT);// 将panel加入到frameImagePanel panel = new ImagePanel();Container contentPane = getContentPane();contentPane.add(panel);} public static final int WIDTH = 300;public static final int HEIGHT = 200; }class ImagePanel extends JPanel{ public ImagePanel(){ // 得到image图像文件image = Toolkit.getDefaultToolkit().getImage("back.gif");MediaTracker tracker = new MediaTracker(this);tracker.addImage(image, 1);try{tracker.waitForID(1); } catch (InterruptedException exception) {} } public void paintComponent(Graphics g) { super.paintComponent(g); //得到image的尺寸 int imageWidth = image.getWidth(this); int imageHeight = image.getHeight(this); //得到窗口的尺寸 int FrameWidth = getWidth(); int FrameHeight = getHeight(); // 算出image的坐标,使image显示在窗口正中间 int x = (FrameWidth - imageWidth ) / 2; int y = (FrameHeight - imageHeight ) / 2; //显示image g.drawImage(image, x, y, null); } private Image image;}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值