0

到目前为止,这是我的代码,其中包含一些打印行,只是为了确保它实际上甚至进入了该方法。出于某种原因,在画布上没有绘制任何东西,就绘图而言,我有一个与此类似的程序,它工作正常。这个有什么问题?

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.*;

public class gameOfLife implements ActionListener {
  private int height;
  private int width;
  private Graphics g;
  private JPanel panel;
  private JFrame frame;
  int[][] board= new int[40][40];

  /**
  * @param args
  */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    gameOfLife gui = new gameOfLife();
  }

  public gameOfLife() {
    int height=400;
    int width=400;
    frame= new JFrame("Keegan's Game Of Life");
    frame.setSize(new Dimension(height,width));
    frame.setLayout(new BorderLayout());
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
    g=frame.getGraphics();
    drawBoard();
  } 

  public void drawBoard() {
    g.setColor(Color.BLUE);
    g.drawLine(0, 0, 50, 50);
    g.fillOval(50,50,10,10);
    System.out.println("Done Drawing");
    g.drawString("IT WORKED!", 100, 100);
  }

  @Override
  public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
  }
}
4

2 回答 2

2

Let's start with g=frame.getGraphics();

This is a very bad idea and not how custom painting is performed. getGraphics may return null and is generally only a snap shot of the last paint cycle. Anything painted to the Graphics context via this method will be destroyed on the next repaint cycle.

You should never maintain a reference to any Graphics context, they are transient and may not be the same object between paint cycles

Instead, create yourself a custom component (something like JPanel) and override it's paintComponent method

Check out Performing Custom Painting for more details

Updated

You can check out this simple example for an idea...

于 2013-02-08T04:53:58.030 回答
0

You can override paint(Graphics g) in your canvas, otherwise the drawing will disappear once the canvas is invalidated (e.g. moved or covered by another windows).

It might be easier to let your class extends JFrame and override the paint methods, otherwise you can use anonymous class e.g.

frame = new JFrame("Keegan's Game Of Life") { //override paint here }

However, if your application aims to create animation for Game Of Life, you should not be doing this in a JFrame, consider using JPanel or Canvas

于 2013-02-08T04:53:14.613 回答