Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify Jlist width?

I want to specify fixed width of my JList

I followed example provided by Gilbert Le Blanc 22k

        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS));
        Panel panel = new JPanel();
        panel.setBackground(Color.WHITE);
        getContentPane().add(panel);

        String [] queries = {"a", "b", "a", "b" , "a", "b", "a", "b"};
        panel.setLayout(new BorderLayout());
        JList list = new JList(queries);
        list.setMaximumSize(new Dimension(200, 200));  // this line does not do the job
        list.setMinimumSize (new Dimension (200,200));
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setVisibleRowCount(5);
        JScrollPane scrollPane_1 = new JScrollPane(list);
        panel.add(scrollPane_1 , BorderLayout.CENTER);

But this does not force the size to be 200 200. I need the width of the JScrollPane to be 200

like image 678
Donotello Avatar asked Mar 27 '26 18:03

Donotello


2 Answers

No, don't set the size of the JList which is already added to JScrollpane. Because JList has an implemented function getPreferredScrollableViewportSize() which computes preferable viewport size by computing cell width and cell height it contains. Let the JScrollPane to handle that. If require, you try adding JScrollPane's dimension. However, to control the item display number and orientation, you can use:

  • setLayoutOrientation which lets the list display its data in multiple columns. The value:

    1. JList.HORIZONTAL_WRAP: specifies that the list should display its items from left to right before wrapping to a new row.
    2. JList.VERTICAL_WRAP: which specifies that the data be displayed from top to bottom (as usual) before wrapping to a new column.
  • setVisibleRowCount(-1) makes the list display the maximum number of items possible in the available space onscreen. Another common use of setVisibleRowCount is to specify to the lists's scroll pane how many rows the list prefers to display.

Check out: How to Use List for Demo and examples.

like image 80
Sage Avatar answered Mar 30 '26 06:03

Sage


The solution is to resize the JScrollPane. If I remember correctly, JList fill up the JScrollPane.

JScrollPane scrollPane_1 = new JScrollPane(list);
scrollPane_1.setMaximumSize(new Dimension(200, 200));
scrollPane_1.setMinimumSize (new Dimension (200,200));
panel.add(scrollPane_1 , BorderLayout.CENTER);
like image 38
Coneone Avatar answered Mar 30 '26 06:03

Coneone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!