Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.util.Arrays;

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

public class Main extends JPanel {

    JList list;

    public Main() {
        super(new BorderLayout());
        String[] data = { "Math", "Computer", "Physics", "Chemistry" };
        list = new JList(data);
        list.addListSelectionListener(new SelectionHandler());
        JScrollPane jsp = new JScrollPane(list);
        this.add(jsp, BorderLayout.CENTER);
    }

    private class SelectionHandler implements ListSelectionListener {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                System.out.println(Arrays.toString(list.getSelectedValues()));
            }
        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("ListPanel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new Main());
        f.pack();
        f.setVisible(true);

    }
}