import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.stream.FileImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FunctionChangeBack extends JPanel
{
JMenuBar bar ;
JMenu menu ;
JMenuItem openFile ;
JFrame frame ;
public FunctionChangeBack ()
{
panelSet () ;
barSet () ;
frameSet () ;
}
public void paintComponent (Graphics g)
{
super.paintComponent(g) ;
}
public void panelSet ()
{
}
public void frameSet ()
{
frame = new JFrame () ;
frame.setLayout(null) ;
frame.add(bar) ;
frame.add(this) ;
frame.setVisible(true) ;
frame.setSize(1024, 768) ;
}
public void barSet ()
{
bar = new JMenuBar () ;
menu = new JMenu ("打开") ;
openFile = new JMenuItem ("文件") ;
openFile.addActionListener(new ActionListener ()
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser jfc = new JFileChooser ("src\\game2\\image") ;
int rs = jfc.showOpenDialog(FunctionChangeBack.this) ;
FileNameExtensionFilter fnef = new FileNameExtensionFilter ("JPGFile","jpg") ;
jfc.addChoosableFileFilter(fnef) ;
if(rs == JFileChooser.APPROVE_OPTION)
{
try
{
File file = jfc.getSelectedFile() ;
FileImageInputStream fiis = new FileImageInputStream (file) ;
FileInputStream fis = new FileInputStream (file) ;
byte[] by = new byte[fis.available()] ;
while(fiis.read(by) != -1)
{
fiis.flush() ;
}
fiis.close() ;
fis.close() ;
FunctionChangeBack.this.getImage(by) ;
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
});
menu.add(openFile) ;
bar.add(menu) ;
bar.setBounds(0, 0, 1024, 50) ;
}
public void getImage(byte[] by)
{
System.out.println(by.length) ;
ImageIcon icon = new ImageIcon (by) ;
Image image = this.createImage(1024,768) ;
Graphics gg = image.getGraphics() ;
Graphics g = this.getGraphics() ;
System.out.println(icon.getIconWidth()+" "+icon.getIconHeight()) ;
gg.drawImage(icon.getImage(), 0, 0, 1024, 768, this) ;
g.drawImage(image, 0, 0, 1024, 768, this) ;
}
public static void main (String [] args)
{
new FunctionChangeBack () ;
}
}
我已经从硬盘里面拿到了一张图片了,由我自己写的getimage方法里面的两个println语句可以看出我可以输出这张图片的宽和高,但是为什么画出的图没有显示在面板上呢?多谢各位解答!