Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Program to implement List on a Frame using Java Swing API

A Simple program demonstrating the working of JList list in Java using Swing framework.

package com.hubberspot.swing.example;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListDemo extends JFrame {
  private String[] ipl = {
  "Deccan Chargers", "Kolkata Night Riders", 
  "Mumbai Indians", "Chennai Super Kings", 
  "Rajasthan Royals", "Royal Challengers Bangalore",
  "Kings XI Punjab", "Pune Warriors India",
  "Delhi Daredevils"
  };
  private int counter = 0;
  private DefaultListModel model = new DefaultListModel();
  private JList list = new JList(model);
  private JTextArea textarea = new JTextArea(ipl.length, 20);
  private JButton button = new JButton("Add Team");
  private ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      if(counter < ipl.length) {
 model.add(0, ipl[counter++]);
      } else {
   button.setEnabled(false);
 }
    }
  };
  
  private ListSelectionListener lstlistener =
     new ListSelectionListener() {
 public void valueChanged(ListSelectionEvent e) {
    if(e.getValueIsAdjusting()) return;
    textarea.setText("");
    for(Object item : list.getSelectedValues())
      textarea.append(item + "\n");
        }
  };

  public ListDemo() {
    textarea.setEditable(false);
    setLayout(new FlowLayout());
    for(int i = 0; i < 4; i++)
      model.addElement(ipl[counter++]);
    add(textarea);
    add(list);
    add(button);
    list.addListSelectionListener(lstlistener);
    button.addActionListener(listener);
  }

  public static void main(String[] args) {
    setFrame(new ListDemo(), 300, 450);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
       public void run() {
  frame.setTitle(frame.getClass().getSimpleName());
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(width, height);
  frame.setVisible(true);
       }
    });
  }
} 

Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot