主题:怎么实现打开图像
s32032033
[专家分:10] 发布于 2007-11-22 15:51:00
请问怎么实现打开一个图像,有什么方法?不要setIcon那样的.
回复列表 (共4个回复)
沙发
haoboy0817 [专家分:880] 发布于 2007-11-22 16:23:00
package imagetest;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ShowImage extends Applet
{
private Image img;
public void init()
{
try
{
img=getImage(getDocumentBase(),"0.jpg");
} catch (Exception ex)
{
ex.printStackTrace();
}
}
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, this);
}
}
板凳
s32032033 [专家分:10] 发布于 2007-11-22 16:46:00
看不懂呀,大哥再教教呀.怎么用都不知道.我想自己选择打开哪张图.
3 楼
happyboy2007 [专家分:3900] 发布于 2007-11-22 21:10:00
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Demo extends JFrame implements ActionListener
{
private JButton but = new JButton("打开文件");
private MyPanel pan = new MyPanel();
public Demo()
{
JPanel pan = new JPanel(new FlowLayout(FlowLayout.CENTER));
pan.add(but);
this.getContentPane().add(pan,"North");
but.addActionListener(this);
this.getContentPane().add(this.pan);
this.setSize(800,600);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[]args)
{
new Demo();
}
public void actionPerformed(ActionEvent e)
{
boolean b = false;
File file = null;
do
{
try
{
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
file = fc.getSelectedFile();
if(!file.exists())
{
JOptionPane.showMessageDialog(this,"文件不存在");
b = true;
}
else
{
b=false;
this.pan.setPath(file.getCanonicalPath());
}
}
catch(Exception ex)
{
b=false;
}
}while(b);
}
}
class MyPanel extends JPanel
{
private String path="";
public void setPath(String path)
{
this.path=path;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
ImageIcon img = new ImageIcon(path);
int width = img.getIconWidth();
int height = img.getIconHeight();
g.drawImage(img.getImage(),(this.getWidth()-width)/2,(this.getHeight()-height)/2,width,height,null);
this.repaint();
}
}
4 楼
haoboy0817 [专家分:880] 发布于 2007-11-22 21:27:00
我是2楼:
我给出的程序是一个JAVA小应用程序,所以你先配置个HTML文件,代码如下:
<applet code="ShowImage.class" width="600",height="400" codebase="test">
<parm name="font" value="DialogInput" >
</applet>
然后就是正常的编译运行了:(记着把你想显示的图像放在编译后生成的包中哟
并把代码中图片名称做相应修改就行了)
javac -d . ShowImage.java
appletviewer imagetest.html
我来回复