Domanda

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

È stato utile?

Soluzione

If you add these to the bottom, right before setVisbile(true) it should work

  setDefaultCloseOperation(EXIT_ON_CLOSE);
  pack();
  setTitle("");
  setVisible(true);

The important part is the pack() You shouldn't set the size of the frame. instead pack it so it respects all preferred sizes of components

Tested and it works fine

Altri suggerimenti

You get that effect because you use GridBagLayout.

You can fix that with help of GridLayout, for example add components like next:

setLayout(new GridLayout(5,5,5,5));

for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
        cells[i][j] = new Cell();
        add(cells[i][j]);
    }
}

enter image description here

or use pack() method as recommended.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top