How to display row count in Java Swing JList

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 02-May-2019 12:26:37
Advertisements