中易网

java从GUI中读入图像并显示,求解答

答案:2  悬赏:60  
解决时间 2021-03-21 14:28
File file=null;
Image image=null;
JFileChooser fileChooser1 = new JFileChooser();
if(fileChooser1.showOpenDialog(null)==JFileChooser.APPROVE_OPTION){
file = fileChooser1.getSelectedFile(); //在GUI中选择文件
try {
image = ImageIO.read(file); //读入图像到image
//setLayout(new GridLayout(2,0,5,5));
//add(new ImageViewer(image));
Graphics g=null;
super.paintComponents(g);
if(image!=null){
g.drawImage(image,0,0,getWidth(),getHeight(),this); //画出图像
}

} catch (IOException ex) {
Logger.getLogger(graphics.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
System.out.println("NO");
}
最佳答案
import java.awt.Graphics;

import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class BackgroundJPanel extends JPanel {
private String imagePath = "";
private Image img = null;
private int widths = 0;
private int heights = 0;
public BackgroundJPanel() {
super();
}
@Override
protected void paintComponent(Graphics g) {
if (img != null) {
MediaTracker media = new MediaTracker(this);
media.addImage(img, 0);
try {
media.waitForID(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
int width = getWidth();
int height = getHeight();
if (widths != 0) {
width = widths;
}
if (heights != 0) {
height = heights;
}
// logger.debug(width + "," + height);
g.drawImage(img, 0, 0, width, height, this);
}

}

public String getImagePath() {
return imagePath;
}

public void setImagePath(String imagePath) {
this.imagePath = imagePath;
if (!imagePath.isEmpty()) {
img = Toolkit.getDefaultToolkit().getImage(
getClass().getResource(imagePath));
}
this.repaint();

}

public Image getImg() {
return img;
}

public void setImg(Image img) {
this.img = img;
}

public int getWidths() {
return widths;
}

public void setWidths(int widths) {
this.widths = widths;
}

public int getHeights() {
return heights;
}

public void setHeights(int heights) {
this.heights = heights;
}
}
这个方法是设置 JPANEL的背景图 你可以参考下
全部回答
你好! fileChooser1.showOpenDialog(null) 得到的路径、得到Image,在JFrame的paint事件中,绘上去 如有疑问,请追问。
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
准上市的互联网理财平台都有哪些比较靠谱
12000点卷是买那个50个幸运魔锤还是买那个600
电脑电源以设置为什么还是不能自劫熄屏
英语作文my view on humanistic
我怀孕四个多月,这几天胸部怎么突然变小了请
请问各位爱维尔的面包店在哪条路上,靠近哪里
适马50mm f/1.4 ex dg hsm 镜头跑焦怎么办
海魅儿玻尿酸原液和菩古玛丽玻尿酸原液哪个好
请问酒吧里的员工交了的管理费他说合同到期了
债券利息问题
冬天去哈尔滨旅游的好去处?
女朋友对我的占有欲太强怎么办 其实我并不是
二级建造师14年考过实务和法规,15年考管理要
满族语言中的加油怎么说
折笠富美子 一个字"强"啊
推荐资讯
给一下这几个字的读音,好古怪的.蘫 嵞 涙 薼
商丘市福达食品机械有限公司FDLD24-35A绿豆糕
电费单上的非分时是什么意思
三国杀姬版为什么不清楚?
CPB地址在哪,我要去那里办事
善罢干休中哪一个字错了
我的手机是vivo s7it为什么手机自带音乐播放
到广州服装批发市场,服装进货,服装拼货,请
游奇卧龙吟怎么练孩子第2阶段技能没绿是不是
黄台社区居委会地址有知道的么?有点事想过去
pdf出现乱码
自己的两个朋友不说话,参加宴会如何邀请
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?