在GridBagLayout中填充JLists

时间:2013-07-04 07:31:59

标签: java swing jlist gridbaglayout preferredsize

我有两个JLists应该JPanel GridBagLayout填充相等的空间。目前它看起来像这样:

enter image description here

如图所示,大多数内容的JList都会获得更多空间。试图给他们平等的空间:

bgConstraints.weightx = 0.5;

但似乎没有像我希望的那样有效。任何想法如何使这两个JLists在内容和JFrame大小上独立地具有相同的width(并且不必更宽)?

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class GridBagTest {

    public static void main(String[] arg){
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 0.5;
        c.weighty = 1;
        panel.add(getList(2),c);
        panel.add(getList(10),c);

        // Show content
        JFrame frame = new JFrame();
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    /**
     * Creates a JList
     * @param strLength The length of the String in the List
     * @return A JList with a String and JScrollPane
     */
    private static JScrollPane getList(int strLength){
        DefaultListModel<String> listModel = new DefaultListModel<String>();  
        JList<String> list = new JList<String>(listModel);

        String str = "";
        for(int i=0; i<strLength; i++)
            str += i;

        listModel.addElement(str);
        JScrollPane pane = new JScrollPane(list);
        return pane;
    }
}

1 个答案:

答案 0 :(得分:3)

使用