2012-11-27 41 views
0

我做了一個自定義組件,所以我可以顯示圖像等,但它拒絕正確使用錨點並居中頂部。有沒有人有修復?另外,如果任何人都可以指向我更簡單的佈局,我可能會切換,但我已經使用了很多GridBag,因此很難。一般測試如何修復GridBagConstraint的自定義組件錨點?

測試類:

package com.launcher.test; 

import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

import com.launcher.swing.ModViewer; 

public class Test extends JFrame implements ActionListener { 
private static final long serialVersionUID = 1L; 

public GridBagConstraints gbc = new GridBagConstraints(); 

public static void main(String[] args) { 
    new Test(); 
} 

public Test() { 
    super("Super Installer"); 
    JPanel j = new JPanel(new GridBagLayout()); 
    addObjs(j); 
    this.add(j); 
    this.setSize(500, 500); 
    this.setVisible(true); 
} 

public void addObjs(JPanel j) { 
    setGBC(0, 0); 
    gbc.weighty = 1.0; 
    gbc.anchor = GridBagConstraints.NORTHWEST; 
    gbc.gridwidth = 2; 
    gbc.gridheight = 2; 
    gbc.ipadx = 50; 
    j.add(new ModViewer(), gbc); 
    setGBC(2, 0); 
    gbc.fill = GridBagConstraints.HORIZONTAL; 
    gbc.anchor = GridBagConstraints.NORTHEAST; 
    j.add(new JButton("Add Mod")); 
} 

private void setGBC(int i, int j) { 
    gbc.gridx = i; 
    gbc.gridy = j; 
} 

@Override 
public void actionPerformed(ActionEvent e) { 
} 

} 

ModViewer類,基本上是一個盒子:

package com.launcher.swing; 

import java.awt.Color; 
import java.awt.Dimension; 

import javax.swing.BorderFactory; 
import javax.swing.JPanel; 

import com.launcher.Main; 

@SuppressWarnings("serial") 
public class ModViewer extends JPanel { 

public ModViewer() { 
    setBorder(BorderFactory.createCompoundBorder(
      BorderFactory.createLineBorder(Color.black), 
      BorderFactory.createEmptyBorder(0, 0, 250, 250))); 
    setPreferredSize(new Dimension(250, 250)); 
} 
} 

回答

1

要獲得定位爲GridBagConstraints.NORTHWEST錨位置的工作,你需要設置的權重中X軸:

gbc.weightx = 1.0; 
+0

非常感謝!我無法弄清楚,但現在它效果很好! –