//对于透明gif有效
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingPic extends JFrame
{
// Picture file name
protected String filename = "", lastDir;
protected ImageIcon image;
Image im;
int height, width, count = 0;
JLabel labeledPic;
JScrollPane scroller;
Container content;
// Constructor
public SwingPic()
{
// Select local system look and feel
try
{
UIManager.setLookAndFeel(UIManager.
getCrossPlatformLookAndFeelClassName());
}
catch (Exception e)
{
}
// End program when window closes
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);}
}
);
setTitle("MJF Image Viewer");
MenuBar mbar = new MenuBar();
Menu m = new Menu("File");
m.add(new MenuItem("Open"));
m.add(new MenuItem("Exit"));
mbar.add(m);
setMenuBar(mbar);
setSize(800, 600);
}
// Load image from file
public void swingdraw()
{
if(count==1) //load new image how to despote image before
{ // Create a label to hold the image as an icon
labeledPic = new JLabel(image, JLabel.CENTER);
labeledPic.setText(filename);
// Create a scroller to hold the labeled image
scroller = new JScrollPane(labeledPic);
scroller.setPreferredSize(new Dimension(height, width));
// Add the scroller to the frame's content layer
content = getContentPane();
content.add(scroller);
this.show();
// Sets window's initial size
//repaint();
}
else if(count>1) //第二次就无法更新了,请大家看看如何实现可以更新。
{ // image.setImage();
labeledPic = new JLabel(image, JLabel.CENTER);
labeledPic.setText(filename);
System.out.println("new jlabel ");
// Create a scroller to hold the labeled image
scroller = new JScrollPane(labeledPic);
scroller.setPreferredSize(new Dimension(height, width));
//Let the scroll pane know to update itself
//and its scroll bars.
scroller.revalidate();
// content = getContentPane();
// content.add(scroller);
scroller.repaint();
// this.show();
}
}
public boolean action(Event evt, Object arg)
{
if(arg.equals("Open"))
{
FileDialog d =
new FileDialog(this, "Open image file", FileDialog.LOAD);
d.setFile("*.gif;*.jpg");
d.setDirectory(lastDir);
d.show();
String f = d.getFile();
lastDir = d.getDirectory();
if(f != null)
{ //image=Toolkit.getDefaultToolkit().getImage(lastDir+f);
// image = new ImageIcon(lastDir + f);
im = Toolkit.getDefaultToolkit ().getImage (lastDir + f);
if(im==null) return false;
image=new ImageIcon(lastDir+f);
height = image.getIconHeight();
width = image.getIconWidth();
System.out.println("new image icon"+height+" "+width);
}
System.out.println("new file"+lastDir+f);
count++;
swingdraw();
//repaint();
}
else if(arg.equals("Exit"))
System.exit(0);
else
return false;
return true;
}
public static void main(String[]args)
{
SwingPic app = new SwingPic();
app.setTitle("Swing Picture Demonstration");
app.show();
}
}
本文地址:http://com.8s8s.com/it/it15333.htm