GridBagLayout不在页面开始时放置组件

时间:2010-12-20 10:14:16

标签: java user-interface swing gridbaglayout

我正在为我的Java应用程序使用网格包布局,但问题是,它不是将组件放在页面中。这是我正在使用的代码:

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);
  }
}

我也试过

gbc.anchor = GridBagConstraints.FIRST_LINE_START;

即使这样也行不通。这是我得到的输出:

Image

1 个答案:

答案 0 :(得分:1)

首先你需要设置

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

但这只会使JLabel填满整个空间而不是JLabel内的图标。如果您希望图像缩放并耗尽整个空间。我建议您将图像读入BufferedImage,然后覆盖paintComponent()方法以绘制BufferedImage的缩放实例。像这样:

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());
}