Question

I am using grid bag layout for my Java application, but the problem is, it is not placing the components in the page start. Here is the code I am using:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Trial extends JFrame {

  JLabel banner;
  Container c;
  GridBagConstraints gbc = new GridBagConstraints();
  GridBagLayout gbl;
  public Trial()
  {
    setTitle("Attendence Manager");
    setIconImage(Toolkit.getDefaultToolkit().getImage("images/icon.png"));
    Dimension dim= Toolkit.getDefaultToolkit().getScreenSize();
    setSize(new Dimension(dim.width-20,dim.height-100));
    c= getContentPane();
    gbl= new GridBagLayout();
    setLayout(gbl);
    banner = new JLabel(new ImageIcon("images/banner.jpg"));
    gbc.anchor=GridBagConstraints.PAGE_START;
    gbc.gridx=0;
    gbc.gridy=0;
    gbc.gridwidth=GridBagConstraints.REMAINDER;
    c.add(banner,gbc);
    this.setVisible(true);
    addWindowListener(new MyWindowAdapter());
  }

  public static void main(String[] args) {
    Trial t = new Trial();
  }

}
class MyWindowAdapter extends WindowAdapter
{
  //LoginPage sp;
  public MyWindowAdapter()
  {
  }

  @Override
  public void windowClosing(WindowEvent we)
  {
    System.exit(0);
  }
}

I have also tried

gbc.anchor = GridBagConstraints.FIRST_LINE_START;

even that didn't work. This is the output I am getting:

Image

Was it helpful?

Solution

First you need to set

gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0;
gbc.weighty = 1.0;

but this will only make the JLabel to fill the whole space not the icon inside the JLabel. If you want to your image to scale and use up the whole space. I would suggest you read the image into a BufferedImage and then override the paintComponent() method to draw a scaled instance of the BufferedImage. Like this:

public Trail() {
    setTitle("Attendence Manager");
    setIconImage(Toolkit.getDefaultToolkit().getImage("images/icon.png"));
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(new Dimension(dim.width - 20, dim.height - 100));
    c = getContentPane();
    gbl = new GridBagLayout();
    setLayout(gbl);

    try {
        final BufferedImage image = ImageIO.read(new File("images/sample.jpg"));
        banner = new JLabel(){
            public void paintComponent(Graphics g) {
                g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
            }
        };
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        c.add(banner, gbc);
    }
    catch (IOException ex) {
        Logger.getLogger(Trail.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.setVisible(true);
    addWindowListener(new MyWindowAdapter());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top