I want to draw a grid(10x10) using java,but we have to implement
it using drawRectMethod in a JFrame,This is my program so far
impo
I'm not sure what your question is, but your implementation is slightly off...
JFrame, you're not adding any new functionality to the class and it's not a good candidate for performing custom painting against, as it's not double buffered and it has a JRootPane and contentPane between frame's surface and the user. Also, you run the risk of painting under the frames decorations. Have a look at How can I set in the midst? and How to get the EXACT middle of a screen, even when re-sized for more details.paint of top level containers (or generally), see the previous point. Instead, start with a component which extends from something like JPanel and override paintComponent instead. Also don't forget to call the paint methods super method in order to maintain the paint chain contract. Have a look at Painting in AWT and Swing and Performing Custom Painting for more detailsimport java.awt.*;
import javax.swing.*;
public class Grid {
public static void main(String[] args) {
new Grid();
}
public Grid() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int size = Math.min(getWidth() - 4, getHeight() - 4) / 10;
int width = getWidth() - (size * 2);
int height = getHeight() - (size * 2);
int y = (getHeight() - (size * 10)) / 2;
for (int horz = 0; horz < 10; horz++) {
int x = (getWidth() - (size * 10)) / 2;
for (int vert = 0; vert < 10; vert++) {
g.drawRect(x, y, size, size);
x += size;
}
y += size;
}
g2d.dispose();
}
}
}