Thursday 8 August 2013

Top Most Java swing tutorial: Learning JList with code example

In this java swing JList tutorial we will learn important properties and function of JList while working on task with examples. In my opinion best way to learn swing is to actually doing task and so I designed this tutorial around task. We will start with simple example and proceed with more  complex one step by step adding new functionality and in the course we will learn JList both concept and API. In this first example we need to implement a list which shows names of companies in sorted order. Before start coding let's see some fundamentals of JList:

1) JList is a GUI element available in javax.swing package which allows selection of one more element. Internally JList is backed up by two models: ListModel for holding data and ListSelectionModel for handling selection. JList also allows custom rendering via ListCellRenderer which can be used to draw a specific cell in customize manner.


2) JList elements are uneditable, JList does not supporty any rendering.


3) There are two ways to set model of JList either using JList.setModel() or JList.setListData().


4) JList implements Scrollable interface and can be put on Scrollpane. JList also supports auto-scrolling. visibleRowCount property of JList is used to dispaly number of rows when a JList is placed on Scrollpane.you can change it by using method setVisibleRowCount().


5) JList cell's width and height is determined by width of widest element and height of highest element but you can also customize it using methods setFixedCellWidh() and setFixedCellHeight().




JList example in Java Swing

Task: Implement JList which display list of electronic trading in sorted ascending order.


Let's see an example of dispalying JList in Swing:


Showing JList in Swing is very easy what you need to do is: create a JList, set its model, put the JList in Panel and done. For creating model for JList you can extend AbstractListModel class which implements ListModel and you can store your data inside this class in either Array or Collection classes as shwon in below example of JList:

public class JListCodeDemo {

      public static void main(String args[]){
      JFrame listFrame = new JFrame();
      JPanel contentPane = (JPanel) listFrame.getContentPane();
      JList list = new JList(new AbstractListModel() {

      String[] companies = {"Stock trading", "Futures trading", "Options trading"};
      @Override
      public int getSize() {
      return companies.length;
      }

      @Override
      public Object getElementAt(int index) {
      return companies[index];
      }
      });
      contentPane.add(list);
      listFrame.pack();
      listFrame.setVisible(true);
      listFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      }
}


Now to display elements in Sorted Order we need to sort the data which we are going to show in JList. For this purpose we will create our own custom ListModel and store our data in List and then sort this list using Collections.sort() method which will sort Strings on there natural order. Here is the code:

class ElectronicTradingListModel extends AbstractListModel{

      private List electronic_trading_list = new ArrayList();

      public ElectronicTradingListModel(){
      electronic_trading_list.add("Equity Trading");
      electronic_trading_list.add("Futures Trading");
      electronic_trading_list.add("Options Trading");
      electronic_trading_list.add("Currency trading");
      Collections.sort(electronic_trading_list);

      }

      @Override
      public int getSize() {
      return electronic_trading_list.size();
      }

      @Override
      public Object getElementAt(int index) {
      return electronic_trading_list.get(index);
      }

}


Now just set this model as your list model by adding following line of code:


list.setModel(new ElectronicTradingListModel());


Let me know how you find this example of JList in Swing, how is my idea of having task based tutorial. To be frank I really liked this thought because it provides you a focus which is quite important otherwise you will lose in this huge API. So focus here is to learn fundamentals of JList and Swing by doing actual real world task. In the next JList tutorial we will see how to implement custom rendering on JList by our next task: Display currency trading in yellow color and Stock trading on red color


Here are some of my favorite java tutorial you may find interesting

LinkWithin

Related Posts Plugin for WordPress, Blogger...

Labels

Core Java programming core java interview question Core Java Faq's Servlets coding database jsp-servlet spring Java linux unix interview questions java investment bank Web Services Interview investment bank mysql Senior java developer interviews best practices java collection tutorial RMI SQL Eclipse FIX protocol tutorial tibco J2EE groovy java questions SCJP grails java 5 tutorial jdbc beginner error and exception Design Patterns Java Programming Tutorials fundamentals general object oriented programming xml Java Programs Hibernate Examples Flex JAMon Java xml tutorial logging Jsp Struts 2.0 Sybase and SQL Server debugging java interviews performance FIX Protocol interview questions JUnit testing WebSphere date and time tutorial experienced java IO tutorial java concurrency thread Ejb Freshers Papers IT Management Java Exapmle Java Script SQL and database tutorial examples Scwcd ant tutorials concurrency example and tutorial future state homework java changes java threading tricky Agile Business of IT Development JSTL Java JSON tutorial Java multithreading Tutorials PM Scrum data structure and algorithm java puzzles java tips testing tips windows 8 5 way to create Singleton Object Architect Interview Questions and Answers Architecture Architecure Bluetooth server as swing application that searches bluetooth device in 10 meter circle and show all devices. You can send file to any bluetooth device. C Programming CIO Callable Statement in Java Circular dependency of Objects in Java Comparable Example in Collection Custom annotation in Java Developer Interview Divide and rule example in java Drupal Example of Singleton Pattern FIX protocol ForkJoin Example in Java 7 Get data from dynamic table with Java Script Git HTML and JavaScript Health Hello World TCP Client Server Networking Program Hibernate Basics Hibernate Interview Question Answer J2EE Interview Question And Answers J2ME GUI Program JEE Interview QA JMS interview question Java J2EE Hibernate Spring Struts Interview Question Java System Property Java Threads Manager Portlets Provident Fund Read data from any file in same location and give the required result. Reading Properties File in Java Redpoint Rest WebService Client Rest Webservice Test SAL join with ven diagram SCP UNIX COMMAND SSL Singleton Pattern in Java Spring Bean Initialization methods and their order Spring Interview Questions Struts Struts 2.0 Basics Struts 2.0 Design Pattern Submit Html Form With Java Script On The Fly Unix executable For Java Program XOM DOM SAX XP books computers core java; core java; object oriented programming data structure; java investment bank; design pattern dtd duplicate rows in table get browser name with jquery grails podcast inner class java beginners tutorial java cache java networking tutorial java spring java util; java collections; java questions java.java1.5 linked list mailto function with all browser oracle database oracle duplicate rows orm schema social spring mvc questions struts transaction tricks tweet windows xslt