2010-12-20 62 views
1

我正在爲我的Java應用程序使用網格包佈局,但問題在於,它不是將組件放置在頁面開始處。這裏是我使用的代碼:GridBagLayout不在頁面開始處放置組件

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; 

即使沒有工作。這是我得到的輸出:您需要設置

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

Image

回答

1

第一,但這樣只會讓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()); 
} 
相關問題