Question

I have two JLists that should fill up equal amount of space in a JPanel with GridBagLayout. Currently it looks like this:

enter image description here

As the image illustrates the JList with most content are getting more space. Tried to give them equal space with:

bgConstraints.weightx = 0.5;

But dose not seems to work as I hoped. Any ideas how to make the two JLists have the same width independently on the content and JFrame size(and not wider then necessary)?

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;
    }
}
Was it helpful?

Solution

use

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top