本文目錄一覽:
java swing 畫圖怎麼保存?求詳細代碼
package test;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class TestJLabel2Image {
public static void main(String ds[]) {
final JFrame f = new JFrame();
JPanel panel = new JPanel(new BorderLayout());
JLabel label = new JLabel() {
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.fillOval(0, 0, this.getWidth(), this.getHeight());
g.dispose();
}
};
panel.setPreferredSize(new Dimension(555, 555));
panel.add(label, BorderLayout.CENTER);
f.getContentPane().add(panel);
f.pack();
BufferedImage image = createImage(panel);
f.dispose();
try {
ImageIO.write(image, “png”, new File(“d:/test.png”));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static BufferedImage createImage(JPanel panel) {
int totalWidth = panel.getPreferredSize().width;
int totalHeight = panel.getPreferredSize().height;
BufferedImage panelImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = (Graphics2D) panelImage.createGraphics();
g2D.setColor(Color.WHITE);
g2D.fillRect(0, 0, totalWidth, totalHeight);
g2D.translate(0, 0);
panel.paint(g2D);
g2D.dispose();
return panelImage;
}
}
java.io.IOException是怎麼回事
IOException的故事
1. 什麼是IOException
這個你可以看看API
2. 廣泛的說,什麼時候會有IOException
比如你文件都不到的時候
你在做資料庫操作的時候資料庫底層出現問題
或者你系統IO出問題了
系統拿不到文件句柄
你說的讀著讀著突然被刪了,你可以試試,書不定真可以
你可以看有多少IOExeption個子類,差不多就有多少種類型
3. 為什麼我要捕獲IOExeption
為什麼要有checked exception,這個是java設計的問題,暫不深究
但是這個IOException的意思就是告訴你,萬一你在做io操作的時候出現異常怎麼辦
最簡單的例子是,我
Class clazz = Class.forname(“/path/to/class”);
這個時候萬一找不到這個class文件該怎麼辦,也算提醒程序員極有可能出現問題的地方,這裡不能忽略
還有一個例子是
try {
stream.close()
} catch(IOException e) {
// ignore
}
你可以看到這裡我們的IOException是忽略的,因為關閉不了,我們也沒辦法 -_-!!!
java中的import java.io.*是什麼意思 io具體又是什麼意思??
import java.io.* 這個是引用包import java.io.*這個的意思而IO則是輸入輸出流的意思,也就是inputStream,和outputStream這些類的
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/259368.html