//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;}
show java使用教程_imageshow.java
最新推荐文章于 2021-02-26 05:53:58 发布
这是一个Java程序,用于在窗口中显示图像。程序创建了一个`ImageFrame`类,继承自`JFrame`,并在其中添加了一个`ImagePanel`。`ImagePanel`类继承自`JPanel`,在`paintComponent`方法中绘制了指定路径的图像文件,确保图像居中显示。
摘要由CSDN通过智能技术生成