Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Main extends JFrame implements ListSelectionListener {
    public Main() {
        setLayout(new GridLayout(1, 2));
        String[] numbers = { "one", "two", "three", "four", "five", "six", "seven" };
        JList<String> list = new JList<>(numbers);
        list.setVisibleRowCount(1);
        list.addListSelectionListener(this);
        JScrollPane s = new JScrollPane(list);
        s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        add(s);
        list.setSelectedIndex(3);
    }

    @Override
    public void valueChanged(final ListSelectionEvent e) {
        JList list = (JList) e.getSource();
        list.ensureIndexIsVisible(list.getSelectedIndex());
    }

    public static void main(String[] args) {
        Main frame = new Main();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.pack();
        //frame.setBounds(20,20,300,300);
        frame.setVisible(true);
    }
}