简体   繁体   English

Java框架中的空白框架

[英]Blank Frame in Java Frame

I have been trying to create a 10x10 grid in Java, and I tried to use the drawLines function in order to do so. 我一直在尝试用Java创建10x10网格,并尝试使用drawLines函数。 However, when I run the program, all I see is a blank window with that will not close. 但是,当我运行该程序时,看到的只是一个空白窗口,该窗口不会关闭。 These are my two classes to draw the grid. 这是我的两个绘制网格的课程。 Could someone explain why this code does not work? 有人可以解释为什么此代码不起作用吗?

import java.awt.*;

public class RandomWalk extends Canvas{

    int width, height;

    public RandomWalk(int w, int h) {
        setSize(width = w, height = h);
    }

    public void paintGrid(Graphics g) {
        width = getWidth();
        height = getHeight();
        for(int i = 0; i < 11; i++) {
            g.drawLine(i*width/10, 0, i*width/10, height);
            g.drawLine(0, i*height/10, width, i*height/10);
        }
    }
}

import java.awt.*;

public class GridViewer extends Frame{

    GridViewer(String title, int w, int h) {
        setTitle(title);
        RandomWalk grid = new RandomWalk(w, h);
        add(grid);
    }

    public static void main(String[] args) {
        new GridViewer("Random Walk", 300, 300).setVisible(true);
    }
}

Add a printout to paintGrid like : System.out.println("paintGrid invoked"); 将打印输出添加到paintGrid例如: System.out.println("paintGrid invoked");
Does it ever get invoked ? 它曾经被调用过吗?
This might help: Performing Custom Painting 这可能会有所帮助: 执行自定义绘画

You u need to override paint() method in Canvas class to achieve your goal and for the window closing, you need to add WindowListener to dispose the window (or u could simply use javax.swing.JFrame class instead of java.awt.Frame ) 您需要重写Canvas类中的paint()方法以实现您的目标,并且要关闭窗口,您需要添加WindowListener来放置窗口(或者您可以简单地使用javax.swing.JFrame类而不是java.awt.Frame

refer the below code 参考下面的代码

import java.awt.*;
import java.awt.event.*;

public class RandomWalk extends Canvas {

    int width, height;

    public RandomWalk(int w, int h) {
        setSize(width = w, height = h);
    }

    @Override
    public void paint(Graphics g) {
        width = getWidth();
        height = getHeight();
        for (int i = 0; i < 11; i++) {
            g.drawLine(i * width / 10, 0, i * width / 10, height);
            g.drawLine(0, i * height / 10, width, i * height / 10);
        }
    }
}

public class GridViewer extends Frame {

    GridViewer(String title, int w, int h) {
        setTitle(title);
        setSize(w, h);
        RandomWalk grid = new RandomWalk(w, h);
        add(grid);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                dispose();
            }
        });
    }

    public static void main(String[] args) {
        new GridViewer("Random Walk", 300, 300).setVisible(true);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM