当前位置: 首页 > 知识库问答 >
问题:

AWT-EventQueue-0导出

司空思聪
2023-03-14

多谢了。

package feedingschedule;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
 *
 * @author ManagerCompufi
 */
public class FillDemo extends JFrame implements ActionListener {
  public static final int WIDTH_S = 300;
  public static final int HEIGHT_S = 200;
  public static final int FILL_WITH = 300;
  public static final int FILL_HEIGHT = 100;
  public static final int CIRCLE_SIZE = 10;
  public static final int PAUSE = 100;

  private final JPanel box;  

 public static void main(String[] args) {

   FillDemo gui = new FillDemo();
   gui.setVisible(true);

 }


 public FillDemo(){
   setSize(WIDTH_S, HEIGHT_S);
   setTitle("FillDemo");
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLayout(new BorderLayout());
   box = new JPanel();

   JPanel buttonPanel = new JPanel();
   buttonPanel.setLayout(new FlowLayout());
   JButton startButton = new JButton();
   startButton.addActionListener(this);
   buttonPanel.add(startButton);
   add(buttonPanel, "South");
 }


  @Override
  public void actionPerformed(ActionEvent e) {
    fill();
  }

  public void fill(){
    Graphics g = box.getGraphics();
      for (int y = 0; y < FILL_HEIGHT; y = y + CIRCLE_SIZE)
        for (int x = 0; x < FILL_WITH; x = x + CIRCLE_SIZE){
        g.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE);
        doNothing(PAUSE);

      }
  }

  public void doNothing(int milliseconds){
    try {
      Thread.sleep(milliseconds);
    }
    catch (InterruptedException e) {
      System.out.println("Unexpected interrup");
      System.exit(0);
    }

  }
}

共有1个答案

邵阳德
2023-03-14

进入你的程序,

 Graphics g = box.getGraphics(); // which returns null

然后,您尝试对其执行一些操作,

 g.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE); // which leads to NullPointerException

所以,最好把支票也放在那边,

Graphics g = box.getGraphics(); 
if(g != null){
        for (int y = 0; y < FILL_HEIGHT; y = y + CIRCLE_SIZE)
            for (int x = 0; x < FILL_WITH; x = x + CIRCLE_SIZE){
                ......
            }
    }
 类似资料: