我写了一个简单的程序来绘制图像,我根本无法让它工作。它应该只在框架内的窗格中显示 1 张图片。ps 有我不需要的 prolly 进口,我尝试了很多不同的东西。
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.*;
import javax.imageio.ImageIO;
public class ShowImage {
private Graphics g;
private BufferedImage lionImage=null;
private JFrame frame;
private JPanel totalGUI,values;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public JPanel createContentPane(){
totalGUI = new JPanel();
totalGUI.setLayout(null);
values = new JPanel();
values.setLayout(null);
values.setLocation(10, 10);
values.setSize(490, 290);
values.setBackground(Color.WHITE);
totalGUI.add(values);
getImage();
Graphics g = values.getGraphics();
g.drawImage(lionImage,100,100,null);
totalGUI.setOpaque(true);
return totalGUI;
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Calculator");
ShowImage demo = new ShowImage();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setVisible(true);
}
void getImage(){
try{
lionImage =ImageIO.read(new File("imgres.jpg"));// *see note
}catch (IOException e){}
}
}
我得到了错误。我不知道问题是什么。
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ShowImage.createContentPane(ShowImage.java:43)
at ShowImage.createAndShowGUI(ShowImage.java:55)
at ShowImage.access$0(ShowImage.java:50)
at ShowImage$1.run(ShowImage.java:23)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)