代码如下:
import javax.swing.*;
import javax.swing.filechooser.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.*;
import java.io.*;
public class Pic extends JFrame implements ActionListener
{
private JButton
b1 = new JButton("button1"),
b2 = new JButton("button2"),
b3 = new JButton("button3"),
b4 = new JButton("button4"),
b6 = new JButton("button6"),
b5 = new JButton("button5");
private Panel panel1 = new Panel();
private JPanel panel2 = new JPanel();
public Pic()
{
b1.addActionListener(this);
panel2.setLayout(new FlowLayout());
panel2.add(b1);
panel2.add(b2);
panel2.add(b3);
panel2.add(b4);
panel2.add(b5);
panel2.add(b6);
panel1.setBackground(Color.darkGray);
panel2.setBackground(Color.CYAN);
this.add(panel1,BorderLayout.CENTER);
this.add(panel2,BorderLayout.SOUTH);
this.setTitle("图像处理");
this.setSize(900, 700);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
Pic pic = new Pic();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == b1)
{
JFileChooser fileChooser1 = new JFileChooser();
fileChooser1.setCurrentDirectory(new File("."));
fileChooser1.setFileFilter(new javax.swing.filechooser.FileFilter()
{
public boolean accept(File f)
{
String name = f.getName().toLowerCase();
return name.endsWith(".gif")||name.endsWith(".jpg")||name.endsWith(".jpeg")||f.isDirectory();
}
public String getDescription()
{
return "Image file";
}
});
int t = fileChooser1.showOpenDialog(this);
if(t == JFileChooser.APPROVE_OPTION)
{
String name = fileChooser1.getSelectedFile().getAbsolutePath();
panel1.showImage(name);
}
}
}
}
class Panel extends JPanel
{
BufferedImage img = null;
int height,width;
public void paint(Graphics g)
{
super.paint(g);
height = img.getHeight(null);
width = img.getWidth(null);
if(height > 600&&width > 900)
{
height = height/2;
width = width/2;
}
g.drawImage(img,(this.getWidth()-width)/2,(this.getHeight()-height)/2,width,height,this);
//System.out.print("width="+width+" height="+height);
}
public void showImage(String imagename)
{
Image image1 = Toolkit.getDefaultToolkit().getImage(imagename);
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(image1, 0);
try
{
tracker.waitForID(0);
}
catch(InterruptedException e)
{
}
img = new BufferedImage(image1.getWidth(null),image1.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = img.createGraphics();
g2.drawImage(image1, 0, 0, null);
}
}
------解决方案--------------------------------------------------------
没等你按button1来初始化img对象paint方法就已经被调用了 空指针错误
public void paint(Graphics g) {
super.paint(g);
height = img.getHeight(null);
...
------解决方案--------------------------------------------------------