I got class Main that extends JFrame
, and class Cell
that extends JComponent
.
Cell
fills a rectangle (square, sized 50,50) in it's paintComponent()
.
I'm trying to draw on the JFrame
25 Cell
instances. Their size should be 50,50 (same as the squares they paint), but for some reason, when the program starts, none of them are visible.
However, when I enlarge the window, suddenly the black squares apear as they should.
Why don't they display in the smaller (250,250) window too (the one that starts when the program starts)?
Here's the code:
Class Main:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class Main extends JFrame
{
Cell[][] cells = new Cell[5][5];
public Main(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(250,250);
setTitle("");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5,5,5,5);
for(int i=0;i<5;i++){
gbc.gridy = i+1;
gbc.gridx = 1;
for(int j=0;j<5;j++){
gbc.gridx = j+1;
cells[i][j] = new Cell();
add(cells[i][j], gbc);
}
}
setVisible(true);
}
public static void main(String[] args)
{
Main m = new Main();
}
}
Class Cell:
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class Cell extends JComponent
{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(1, 1, 50, 50);
}
public Dimension getPreferredSize(){
return new Dimension(50,50);
}
}
Thanks