java - Swing 添加图像不起作用

标签 java image swing paintcomponent

所以我上课了

public class ImagePanel extends JPanel {
BufferedImage lionImage;

public ImagePanel(){
    try {
         lionImage = ImageIO.read (new File ("imgres.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }

}

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    if (lionImage != null) {
       g.drawImage(lionImage, 0, 0, this);
    }
}

public BufferedImage getLionImage() {
    return lionImage;
}

public void setLionImage(BufferedImage lionImage) {
    this.lionImage = lionImage;
}
}

然后我做了一个测试类

public class test {

public static void main (String [] args) throws Exception {
ImagePanel test = new ImagePanel();
JFrame frame = new JFrame ("Image");

frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane ().setLayout (new BorderLayout ());

frame.add(test);

frame.pack ();
frame.setVisible (true);
}
}

一切正常,简单地制作一个框架,制作一个 ImagePanel,将其添加到框架中。

然后我在实际工作中尝试了它。

public class Enviroment implements Runnable, ActionListener{ 
private JFrame frame;
private JPanel enviromentPanel,totalGUI,enviromentButtonPanel;
private JButton newFrogButton, resetButton, hungryButton;
private JTextField enterName;
private JLabel hungryLabel;
private ArrayList<Frog> frogs = new ArrayList<Frog>();
private ArrayList<Fly> flys = new ArrayList<Fly>();



public Enviroment(){
 JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("[=] Hungry Cyber Pet [=]");

    frame.setContentPane(runEnviroment());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(740, 800);
    frame.setVisible(true);

}



public JPanel runEnviroment(){

JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);

JPanel enviromentPanel = new JPanel();
enviromentPanel.setLayout(null);
enviromentPanel.setLocation(10, 10);
enviromentPanel.setSize(700, 700);
enviromentPanel.setBackground(Color.WHITE);
totalGUI.add(enviromentPanel);


JPanel enviromentButtonPanel = new JPanel();
FlowLayout experimentLayout = new FlowLayout();
enviromentButtonPanel.setLayout(experimentLayout);
enviromentButtonPanel.setLocation(10, 710);
enviromentButtonPanel.setSize(700, 50);
totalGUI.add(enviromentButtonPanel);

newFrogButton = new JButton("New Frog");
newFrogButton.setLocation(0, 0);
newFrogButton.setSize(120, 30);
newFrogButton.addActionListener(this);
enviromentButtonPanel.add(newFrogButton);

enterName = new JTextField("Enter name");
enterName.setLocation(140,0);
enterName.setSize(120,30);
enviromentButtonPanel.add(enterName);

hungryButton = new JButton("Hungry!");
hungryButton.setLocation(280, 0);
hungryButton.setSize(120, 30);
hungryButton.addActionListener(this);
enviromentButtonPanel.add(hungryButton);

resetButton = new JButton("Reset");
resetButton.setLocation(420, 0);
resetButton.setSize(120, 30);
resetButton.addActionListener(this);
enviromentButtonPanel.add(resetButton);


totalGUI.setOpaque(true);

return totalGUI;
}
 public void draw(){
 ImagePanel frogImage = new ImagePanel();
 enviromentPanel.add(frogImage);
}
public void actionPerformed(ActionEvent e) {
 if(e.getSource() == newFrogButton){
     Frog frog = new Frog(enterName.getText());
     frogs.add(frog);
     draw();
     System.out.println(frogs);
     Fly fly = new Fly();
     flys.add(fly);
     System.out.println(flys);
  }
  else if(e.getSource() == hungryButton){
  }
  else if(e.getSource() == resetButton){
      frogs.clear();
      flys.clear();
      System.out.println(frogs);
      System.out.println(flys);


  }
}

执行draw()方法时会显示错误。

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Enviroment.draw(Enviroment.java:91)
at Enviroment.actionPerformed(Enviroment.java:97)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(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.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.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)

在任何人说话之前,图像就已经存在并且运行良好。怎么了?

Frog 和苍蝇类很简单。

public class Fly {
private int xPosition;
private int yPosition;
private boolean eaten;

public Fly(){
    Random randomGenerator = new Random();
    xPosition = randomGenerator.nextInt(100);
    yPosition = randomGenerator.nextInt(100);
    eaten = false;
}

public int getxPosition() {
    return xPosition;
}

public void setxPosition(int xPosition) {
    this.xPosition = xPosition;
}

public int getyPosition() {
    return yPosition;
}

public void setyPosition(int yPosition) {
    this.yPosition = yPosition;
}

public boolean isEaten() {
    return eaten;
}

public void setEaten(boolean eaten) {
    this.eaten = eaten;
}

public void move(){
      Random randomGenerator = new Random();

        int xChange = -10 + randomGenerator.nextInt(20);
        int yChange = -10 + randomGenerator.nextInt(20);
        xPosition = xPosition + xChange;
        yPosition = yPosition + yChange;
        move();
}

@Override
public String toString() {
    return "Fly [xPosition=" + xPosition + ", yPosition=" + yPosition
            + ", eaten=" + eaten + "]";
}
}

 public class Frog {
@Override
public String toString() {
    return "Frog [xPosition=" + xPosition + ", yPosition=" + yPosition
            + ", name=" + name + ", hungry=" + hungry + "]";
}
private int xPosition;
private int yPosition;
private BufferedImage lionImage=null;
private String name;
private boolean hungry;

public Frog(String newName){
    Random randomGenerator = new Random();
    xPosition = randomGenerator.nextInt(100);
    yPosition = randomGenerator.nextInt(100);
    name = newName;
    hungry = false;
    getImage();
}
public void getImage(){
    try{
    lionImage =ImageIO.read(new File("imgres.jpg"));
    }catch (IOException e){}
    }
public void move(){
    Random randomGenerator = new Random();

    int xChange = -10 + randomGenerator.nextInt(20);
    int yChange = -10 + randomGenerator.nextInt(20);
    xPosition = xPosition + xChange;
    yPosition = yPosition + yChange;
    move();
}
public void moveHungry(){

}
public void eat(){

}
public int getxPosition() {
    return xPosition;
}
public void setxPosition(int xPosition) {
    this.xPosition = xPosition;
}
public int getyPosition() {
    return yPosition;
}
public void setyPosition(int yPosition) {
    this.yPosition = yPosition;
}
public BufferedImage getLionImage() {
    return lionImage;
}
public void setLionImage(BufferedImage lionImage) {
    this.lionImage = lionImage;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public boolean isHungry() {
    return hungry;
}
public void setHungry(boolean hungry) {
    this.hungry = hungry;
}
public void bounce(){

}
 }

最佳答案

您将环境面板创建为局部变量,类变量为空。

您的代码应该是:

//  JPanel enviromentPanel = new JPanel();
enviromentPanel = new JPanel();
enviromentPanel.setLayout(null);
enviromentPanel.setLocation(10, 10);
enviromentPanel.setSize(700, 700);

另外,不要使用空布局。使用适当的布局管理器来布局您的组件。

关于java - Swing 添加图像不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14816241/

相关文章:

image - 如何在 JavaFX 的 TextArea 中将内嵌图像添加到字符串的末尾?

java - 在 JComboBox Java 中添加文本到字符串

java |如何在 "forever"循环运行时关闭 JFrame?

java - JComboBox 转字符串涉及短信

java - Codenameone 通过模拟器分享 Facebook

java - 功能或错误 : unable to override enum method with default implementation of UnsupportedOperationException

javascript - 这就是为什么要使用 Blob 设置 <img> 内容,而不使用 FileReader 或 URL.createObjectURL

javascript - 使用 Firebase 存储上传 base64 图像

java - addactionListener(this) 如何正确放置这行代码?

java - Mockito varargs 参数匹配器的使用无效