1

I need help because my JPanel component doesn't display in another component. I used to work with that layout so I have some experience in that but still have problem in that case. Please don't answer to use another layout manager. Most of my project is based on GridBagLayout.

So it is my Parent container:

public class MainArea extends WorkArea
{
private static final long serialVersionUID = 1L;
private GridBagConstraints gbc;
private LogoPanel logo;

public MainArea()
{
    gbc = new GridBagConstraints();
    logo = new LogoPanel();
    JTextField tf = new JTextField(20);
    gbc.gridx = 0;
    gbc.gridy = 0;
    add(logo,gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    add(tf,gbc);
}
}

Layout manager is set in WorkArea class and it is for sure right done. JTextField I added only for tests and it is shown properly unlike logo. Here is Logo code:

public class LogoPanel extends JPanel
{
private BufferedImage image;

public LogoPanel()
{
    File imageFile = new File("images/Logo.jpg");
    try
    {
        image = ImageIO.read(imageFile);
    }
    catch (IOException e)
    {
        System.err.println("Blad odczytu logo");
        e.printStackTrace();
    }
}

@Override
public void paintComponent(Graphics g)
{
    Graphics2D g2d = (Graphics2D) g;
    Screen screen = Screen.getInstance();
    g2d.drawImage(image, screen.getScreenWidth()/2-200, screen.getScreenHeight()/2-100, this);
}   
}

Please help me. I have no idea what may be wrong here. I also tried repaint method and validate after adding but with not result.

splungebob
  • 5,357
  • 2
  • 22
  • 45
user2374573
  • 59
  • 1
  • 3
  • 11
  • Where is your call to `super.paintComponent(g)` ? Are you sure it is able to load the images well, if not, please have a look at this thread regarding, how to [add images to your Java Project](http://stackoverflow.com/a/9866659/1057230) – nIcE cOw Jun 21 '13 at 16:35

2 Answers2

2

Try overriding public Dimension getPreferredSize() in your LogoPanel class so that GridBagLayout knows how big to make your panel.

And as @nIcE cOw points out, always call super.paintComponent(g) as the first line in your paintComponent() method.

jmclellan
  • 550
  • 3
  • 12
0

try calling setVisible(true) on your logo panel

Stephan
  • 16,509
  • 7
  • 35
  • 61
  • I resolved that using setPreferredSize to LogoPanel. It is weird because if I use different layout it isn't required. Thx for advices – user2374573 Jun 21 '13 at 17:19