当前位置: 技术问答>java相关
awt里有哪个类可以显示gif或jpg图片?
来源: 互联网 发布时间:2017-03-23
本文导语: 我用forte,在awt面板里找不到可以显示图片的控件啊,swing有一个JLabel可以显示图片,请问awt哪个控件可以? | 可以实现的! 从文件a.gif中加载一个图标,并创建一个以此图标为标记的JButton,代...
我用forte,在awt面板里找不到可以显示图片的控件啊,swing有一个JLabel可以显示图片,请问awt哪个控件可以?
|
可以实现的!
从文件a.gif中加载一个图标,并创建一个以此图标为标记的JButton,代码实现如下:
ImageIcon a= new ImageIcon("a.gif"):
JButton button= new JButton(a);
JPanel pane=new JPane();
pane.add(button);
setContentPane(pane);
从文件a.gif中加载一个图标,并创建一个以此图标为标记的JButton,代码实现如下:
ImageIcon a= new ImageIcon("a.gif"):
JButton button= new JButton(a);
JPanel pane=new JPane();
pane.add(button);
setContentPane(pane);
|
import java.awt.*;
import java.awt.event.*;
public class ImagePain extends Frame
{
public ImagePain()
{
ImageCanvas images = new ImageCanvas("images\photo.jpg");
add(images);
}
public static void main(String[] args)
{
ImagePain f = new ImagePain();
f.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e)
{
System.exit(0);
}
});
f.setSize(800, 600);
f.show();
}
class ImageCanvas extends Canvas
{
Image i;
public ImageCanvas(String imageName)
{
i = Toolkit.getDefaultToolkit().getImage(imageName);
MediaTracker mt = new MediaTracker(this);
try
{
mt.addImage(i,0);
mt.waitForID(0);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public void paint(Graphics g)
{
g.drawImage(i,0,0,this);
}
public Dimension getPreferredSize()
{
int w = i.getWidth( this );
int h = i.getHeight( this );
return new Dimension( w, h );
}
}
}
import java.awt.event.*;
public class ImagePain extends Frame
{
public ImagePain()
{
ImageCanvas images = new ImageCanvas("images\photo.jpg");
add(images);
}
public static void main(String[] args)
{
ImagePain f = new ImagePain();
f.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e)
{
System.exit(0);
}
});
f.setSize(800, 600);
f.show();
}
class ImageCanvas extends Canvas
{
Image i;
public ImageCanvas(String imageName)
{
i = Toolkit.getDefaultToolkit().getImage(imageName);
MediaTracker mt = new MediaTracker(this);
try
{
mt.addImage(i,0);
mt.waitForID(0);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public void paint(Graphics g)
{
g.drawImage(i,0,0,this);
}
public Dimension getPreferredSize()
{
int w = i.getWidth( this );
int h = i.getHeight( this );
return new Dimension( w, h );
}
}
}
|
panel
|
javax.swing.JLabel