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:

First you need to set
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
BufferedImageand then override thepaintComponent()method to draw a scaled instance of the BufferedImage. Like this: