2

The JPanel called panel only shows up as one small red square up the top center, I have tried to set the size but it doesn't seem to do anything.

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;   

public class Draw extends JFrame{

private JPanel panel;

    public Draw() {
        super("title");
        setLayout(new FlowLayout());        
        panel = new JPanel();       
        panel.setBackground(Color.RED);
        add(panel, BorderLayout.CENTER);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Aazim Abdul
  • 59
  • 2
  • 6

2 Answers2

5

The default, preferred size of a JPanel is 0x0. FlowLayout lays out components based on their preferred size, hence the component now has a preferred size of 1x1 (the line border adds a little weight).

You could try adding another component to panel...

panel.add(new JLabel("This is some text"));

Or override panels getPreferredSize method...

panel = new JPanel() {
    public Dimension getPreferredSize() {
        return new Dimension(100, 100);
    }
};
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Try this :

File Draw.java

   package com.stackovfl;

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;

    @SuppressWarnings("serial")
    class Draw extends JFrame {
    private JPanel panel;

      public Draw() {
        super("title");
        setLayout(new FlowLayout());
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(200, 300));
        panel.setBackground(Color.RED);     
        add(panel, BorderLayout.CENTER);
        /* Important to get the layout to work */
        pack();     
        /* Center the window */
        setLocationRelativeTo(null);        
        /* Important if you want to see your window :) */
        setVisible(true);
        }
    }

File Test.java (main method to launch the window) : package com.stackovfl;

import javax.swing.SwingUtilities;

public class Test {
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new Draw();
        }
    });
   }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
a_mid
  • 76
  • 6
  • Note that it is important to use the setLocationRelativeTo(null) after the pack() method. This ensures that your windows is at the center of your screen. If you try it the other way around it will not work because the pack method can modify the size of your window. – a_mid Nov 10 '13 at 19:57