I have created a grid in my program. Below is the code used to create the grid.
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class Grid extends JComponent {
public void paint(Graphics g) {
g.drawRect (10, 10, 800, 500);
for (int i = 10; i <= 800; i+= 10)
g.drawLine (i, 10, i, 510);
for (int i = 10; i <= 500; i+= 10)
g.drawLine (10, i, 810, i);
}
}
public class CoreControl {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setSize(840,560);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(new Grid());
window.setVisible(true);
}
}
What I want to do is to create a function which will draw a rectangle (filled with black color) based on the coordinates that I give it. Basically I want to populate certain cells of the grid with black color and my idea is to draw black filled rectangles on the cell coordinates. How do I make this function?
I tried making another class called drawRectangle and called it in the main function like so window.getContentPane().add(new drawRectangle()); however that did not work (only drawRectangle shows up and not the grid).
I also want to be able to use this function repeatedly to keep creating rectangles.
How do I do create this function?
Also if you know a better way that I should structure this program please let me know (I am new to Java so I am open to any suggestions).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…