I have been trying to create a 10x10 grid in Java, and I tried to use the drawLines function in order to do so. 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");
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
)
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.