How to display row count in Java Swing JList


Use JList getVisibleRowCount() method to display the row count in a JList:

String sports[]= {"Tennis", "Archery","Football","Fencing","Cricket","Squash","Hockey","Rugby"};

Jlist list = new JList(sports);
int rowCount = list.getVisibleRowCount();
System.out.println("Row Count = "+rowCount);

The following is an example to display row count in JList:

Example

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class SwingDemo extends JFrame {
   static JFrame frame;
   static JList list;
   public static void main(String[] args) {
      frame = new JFrame("JList Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      String sports[]= {"Tennis", Archery","Football","Fencing","Cricket","Squash","Hockey","Rugby"};
      list = new JList(sports);
      int rowCount = list.getVisibleRowCount();
      System.out.println("Row Count = "+rowCount);
      JScrollPane scrollPane = new JScrollPane(list);
      scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
      frame.add(scrollPane);
      frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
      frame.setSize(400,100);
      frame.setVisible(true);
   }
}

Output

The output in the console will display the total row count:

Row Count = 8

Updated on: 30-Jul-2019

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements