Hello.

I wrote my component in Java (the field on which events will take place in the game):

public class Pole extends JPanel { public static int CHECK_SIZE = 40; public Check check[][] = new Check[21][21]; public int cw, ch, width, height, focusX = 0, focusY = 0; public Game game; public MainWindow mw; public Pole(int aw, int ah) { for(int i = 0; i < 21; i++) for(int j = 0; j < 21; j++) check[j][i] = new Check(); cw = aw; ch = ah; width = cw * CHECK_SIZE + cw + 1; height = ch * CHECK_SIZE + ch + 1; setSize(width, height); addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { setFocusPixel(e.getX(), e.getY(), e.getButton()); mw.redrawStatePanel(); repaint(); } public void mouseReleased(MouseEvent e) { } }); } /* ... */ public void paintComponent(Graphics g) { /* Прорисовка сетки и объктов на ней */ } /* ... */ } 

But for some reason, when I add it to another panel, it either becomes invisible altogether, or only a piece of my component is visible. And when I follow my component, I add another one, for example:

 add(pole); add(infoLabel); 

then the next one appears somewhere on the pole, i.e. overlaps it. It seems to me that there is some problem with the size of the component, although I pointed it out with the function setSize (width, height).

By the way, if the component is simply added to the window, then everything is fine. And if you add a pole like add (pole, BorderLayout.CENTER), and then add other components on top of add (infoLabel, BorderLayout.NORTH), then everything is fine.

Help me to understand. What is the problem?

    1 answer 1

    The problem is that you have not specified the initial dimensions for the component. Therefore, the size of the panel is determined by the container where you stuffed it, and is set to the minimum values ​​(in your case, 0, 0). Everything is OK with the border lajaut, because in this lajaut manager, under the center, the most space is allocated.

    update - added sample code:

     public class DummyFrame extends JFrame { public static void main ( String[] args ) { // create special panel with defined size JPanel comp = new JPanel () ; comp.setBackground ( Color.RED ) ; comp.setPreferredSize ( new Dimension ( 150, 90 ) ) ; // create frame SplitDates splitDates = new SplitDates () ; splitDates.setSize ( 500, 500 ) ; splitDates.setBackground ( Color.BLUE ) ; splitDates.setLayout ( new FlowLayout () ) ; splitDates.setDefaultCloseOperation ( DISPOSE_ON_CLOSE ) ; splitDates.add ( comp ) ; } } 
    • @jmu, And how can I specify the initial dimensions. I after all would like specified them with the help setSize (width, height)? - Mencey
    • Added an example, this should be enough to answer your question - jmu