Java Swing How to - Set JList orientation








Question

We would like to know how to set JList orientation.

Answer

import java.awt.Dimension;
//from ww  w  .jav a 2 s. c om
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

public class Main {

  public static void main(String[] args) {
    JPanel panel = new JPanel();
    panel.setPreferredSize(new Dimension(800, 600));

    String test[] = { "alpha", "bravo", "charlie", "delta", "echo", "omega",
        "zeta" };
    JList<String> list = new JList<>(test);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setLayoutOrientation(JList.VERTICAL);
    list.setVisibleRowCount(5);
    list.setBounds(50, 150, 75, 90);

    JScrollPane jScrollPane1 = new JScrollPane();
    jScrollPane1.setViewportView(list);

    panel.add(jScrollPane1);

    JFrame f = new JFrame();
    f.add(panel);
    f.pack();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setResizable(false);
    f.setFocusable(true);
  }

}