Skip to main content

Java Swing: JTabel, JList, JOptionPane, JScrollBar

Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and columns.

JTable class declaration

Let's see the declaration for javax.swing.JTable class.

Commonly used Constructors:

ConstructorDescription
JTable()Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns)Creates a table with the specified data.

Java JTable Example

  1. import javax.swing.*;    
  2. public class TableExample {    
  3.     JFrame f;    
  4.     TableExample(){    
  5.     f=new JFrame();    
  6.     String data[][]={ {"101","Amit","670000"},    
  7.                           {"102","Jai","780000"},    
  8.                           {"101","Sachin","700000"}};    
  9.     String column[]={"ID","NAME","SALARY"};         
  10.     JTable jt=new JTable(data,column);    
  11.     jt.setBounds(30,40,200,300);          
  12.     JScrollPane sp=new JScrollPane(jt);    
  13.     f.add(sp);          
  14.     f.setSize(300,400);    
  15.     f.setVisible(true);    
  16. }     
  17. public static void main(String[] args) {    
  18.     new TableExample();    
  19. }    
  20. }  

Output:

JAVA Jtable 1

Java JTable Example with ListSelectionListener

  1. import javax.swing.*;    
  2. import javax.swing.event.*;  
  3. public class TableExample {    
  4.       public static void main(String[] a) {  
  5.             JFrame f = new JFrame("Table Example");  
  6.             String data[][]={ {"101","Amit","670000"},    
  7.                                                                        {"102","Jai","780000"},    
  8.                                                                        {"101","Sachin","700000"}};    
  9.                             String column[]={"ID","NAME","SALARY"};         
  10.                             final JTable jt=new JTable(data,column);    
  11.             jt.setCellSelectionEnabled(true);  
  12.             ListSelectionModel select= jt.getSelectionModel();  
  13.             select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
  14.             select.addListSelectionListener(new ListSelectionListener() {  
  15.               public void valueChanged(ListSelectionEvent e) {  
  16.                 String Data = null;  
  17.                 int[] row = jt.getSelectedRows();  
  18.                 int[] columns = jt.getSelectedColumns();  
  19.                 for (int i = 0; i < row.length; i++) {  
  20.                   for (int j = 0; j < columns.length; j++) {  
  21.                     Data = (String) jt.getValueAt(row[i], columns[j]);  
  22.                   } }  
  23.                 System.out.println("Table element selected is: " + Data);    
  24.               }       
  25.             });  
  26.             JScrollPane sp=new JScrollPane(jt);    
  27.             f.add(sp);  
  28.             f.setSize(300200);  
  29.             f.setVisible(true);  
  30.           }  
  31.         }  

Output:

JAVA Jtable 2

If you select an element in column NAME, name of the element will be displayed on the console:

  1. Table element selected is: Sachin  

Java JList

The object of JList class represents a list of text items. The list of text items can be set up so that the user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration

Let's see the declaration for javax.swing.JList class.

  1. public class JList extends JComponent implements Scrollable, Accessible  

Commonly used Constructors:

ConstructorDescription
JList()Creates a JList with an empty, read-only, model.
JList(ary[] listData)Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> dataModel)Creates a JList that displays elements from the specified, non-null, model.

Commonly used Methods:

MethodsDescription
Void addListSelectionListener(ListSelectionListener listener)It is used to add a listener to the list, to be notified each time a change to the selection occurs.
int getSelectedIndex()It is used to return the smallest selected cell index.
ListModel getModel()It is used to return the data model that holds a list of items displayed by the JList component.
void setListData(Object[] listData)It is used to create a read-only ListModel from an array of objects.

Java JList Example

  1. import javax.swing.*;  
  2. public class ListExample  
  3. {  
  4.      ListExample(){  
  5.         JFrame f= new JFrame();  
  6.         DefaultListModel<String> l1 = new DefaultListModel<>();  
  7.           l1.addElement("Item1");  
  8.           l1.addElement("Item2");  
  9.           l1.addElement("Item3");  
  10.           l1.addElement("Item4");  
  11.           JList<String> list = new JList<>(l1);  
  12.           list.setBounds(100,10075,75);  
  13.           f.add(list);  
  14.           f.setSize(400,400);  
  15.           f.setLayout(null);  
  16.           f.setVisible(true);  
  17.      }  
  18. public static void main(String args[])  
  19.     {  
  20.    new ListExample();  
  21.     }}  

Output:

JAVA Jlist 1

Java JList Example with ActionListener

  1. import javax.swing.*;  
  2. import java.awt.event.*;  
  3. public class ListExample  
  4. {  
  5.      ListExample(){  
  6.         JFrame f= new JFrame();  
  7.         final JLabel label = new JLabel();          
  8.         label.setSize(500,100);  
  9.         JButton b=new JButton("Show");  
  10.         b.setBounds(200,150,80,30);  
  11.         final DefaultListModel<String> l1 = new DefaultListModel<>();  
  12.           l1.addElement("C");  
  13.           l1.addElement("C++");  
  14.           l1.addElement("Java");  
  15.           l1.addElement("PHP");  
  16.           final JList<String> list1 = new JList<>(l1);  
  17.           list1.setBounds(100,10075,75);  
  18.           DefaultListModel<String> l2 = new DefaultListModel<>();  
  19.           l2.addElement("Turbo C++");  
  20.           l2.addElement("Struts");  
  21.           l2.addElement("Spring");  
  22.           l2.addElement("YII");  
  23.           final JList<String> list2 = new JList<>(l2);  
  24.           list2.setBounds(100,20075,75);  
  25.           f.add(list1); f.add(list2); f.add(b); f.add(label);  
  26.           f.setSize(450,450);  
  27.           f.setLayout(null);  
  28.           f.setVisible(true);  
  29.           b.addActionListener(new ActionListener() {  
  30.               public void actionPerformed(ActionEvent e) {   
  31.                  String data = "";  
  32.                  if (list1.getSelectedIndex() != -1) {                       
  33.                     data = "Programming language Selected: " + list1.getSelectedValue();   
  34.                     label.setText(data);  
  35.                  }  
  36.                  if(list2.getSelectedIndex() != -1){  
  37.                     data += ", FrameWork Selected: ";  
  38.                     for(Object frame :list2.getSelectedValues()){  
  39.                        data += frame + " ";  
  40.                     }  
  41.                  }  
  42.                  label.setText(data);  
  43.               }  
  44.            });   
  45.      }  
  46. public static void main(String args[])  
  47.     {  
  48.    new ListExample();  
  49.     }}  

Output:

JAVA Jlist 2


Java JOptionPane

The JOptionPane class is used to provide standard dialog boxes such as message dialog box, confirm dialog box and input dialog box. These dialog boxes are used to display information or get input from the user. The JOptionPane class inherits JComponent class.

JOptionPane class declaration

  1. public class JOptionPane extends JComponent implements Accessible  

Common Constructors of JOptionPane class

ConstructorDescription
JOptionPane()It is used to create a JOptionPane with a test message.
JOptionPane(Object message)It is used to create an instance of JOptionPane to display a message.
JOptionPane(Object message, int messageTypeIt is used to create an instance of JOptionPane to display a message with specified message type and default options.

Common Methods of JOptionPane class

MethodsDescription
JDialog createDialog(String title)It is used to create and return a new parentless JDialog with the specified title.
static void showMessageDialog(Component parentComponent, Object message)It is used to create an information-message dialog titled "Message".
static void showMessageDialog(Component parentComponent, Object message, String title, int messageType)It is used to create a message dialog with given title and messageType.
static int showConfirmDialog(Component parentComponent, Object message)It is used to create a dialog with the options Yes, No and Cancel; with the title, Select an Option.
static String showInputDialog(Component parentComponent, Object message)It is used to show a question-message dialog requesting input from the user parented to parentComponent.
void setInputValue(Object newValue)It is used to set the input value that was selected or input by the user.

Java JOptionPane Example: showMessageDialog()

  1. import javax.swing.*;  
  2. public class OptionPaneExample {  
  3. JFrame f;  
  4. OptionPaneExample(){  
  5.     f=new JFrame();  
  6.     JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");  
  7. }  
  8. public static void main(String[] args) {  
  9.     new OptionPaneExample();  
  10. }  
  11. }  

Output:

Java Joptionpane 1

Java JOptionPane Example: showMessageDialog()

  1. import javax.swing.*;  
  2. public class OptionPaneExample {  
  3. JFrame f;  
  4. OptionPaneExample(){  
  5.     f=new JFrame();  
  6.     JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING_MESSAGE);     
  7. }  
  8. public static void main(String[] args) {  
  9.     new OptionPaneExample();  
  10. }  
  11. }  

Output:

Java Joptionpane 2

Java JOptionPane Example: showInputDialog()

  1. import javax.swing.*;  
  2. public class OptionPaneExample {  
  3. JFrame f;  
  4. OptionPaneExample(){  
  5.     f=new JFrame();   
  6.     String name=JOptionPane.showInputDialog(f,"Enter Name");      
  7. }  
  8. public static void main(String[] args) {  
  9.     new OptionPaneExample();  
  10. }  
  11. }  

Output:

Java Joptionpane 3

Java JOptionPane Example: showConfirmDialog()

  1. import javax.swing.*;  
  2. import java.awt.event.*;  
  3. public class OptionPaneExample extends WindowAdapter{  
  4. JFrame f;  
  5. OptionPaneExample(){  
  6.     f=new JFrame();   
  7.     f.addWindowListener(this);  
  8.     f.setSize(300300);  
  9.     f.setLayout(null);  
  10.     f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  
  11.     f.setVisible(true);  
  12. }  
  13. public void windowClosing(WindowEvent e) {  
  14.     int a=JOptionPane.showConfirmDialog(f,"Are you sure?");  
  15. if(a==JOptionPane.YES_OPTION){  
  16.     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  17. }  
  18. }  
  19. public static void main(String[] args) {  
  20.     new  OptionPaneExample();  
  21. }     
  22. }  

Output:

Java Joptionpane 4

Java JScrollBar

The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a scrollbar. It inherits JComponent class.

JScrollBar class declaration

Let's see the declaration for javax.swing.JScrollBar class.

  1. public class JScrollBar extends JComponent implements Adjustable, Accessible  

Commonly used Constructors:

ConstructorDescription
JScrollBar()Creates a vertical scrollbar with the initial values.
JScrollBar(int orientation)Creates a scrollbar with the specified orientation and the initial values.
JScrollBar(int orientation, int value, int extent, int min, int max)Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.

Java JScrollBar Example

  1. import javax.swing.*;  
  2. class ScrollBarExample  
  3. {  
  4. ScrollBarExample(){  
  5.     JFrame f= new JFrame("Scrollbar Example");  
  6.  JScrollBar s=new JScrollBar();  
  7. s.setBounds(100,10050,100);  
  8. f.add(s);  
  9. f.setSize(400,400);  
  10. f.setLayout(null);  
  11. f.setVisible(true);  
  12. }  
  13. public static void main(String args[])  
  14. {  
  15. new ScrollBarExample();  
  16. }}  

Output:

JAVA Jscrollbar 1

Java JScrollBar Example with AdjustmentListener

  1. import javax.swing.*;  
  2. import java.awt.event.*;  
  3. class ScrollBarExample  
  4. {  
  5. ScrollBarExample(){  
  6.     JFrame f= new JFrame("Scrollbar Example");  
  7.     final JLabel label = new JLabel();          
  8.     label.setHorizontalAlignment(JLabel.CENTER);    
  9.     label.setSize(400,100);  
  10.     final JScrollBar s=new JScrollBar();  
  11.     s.setBounds(100,10050,100);  
  12.     f.add(s); f.add(label);  
  13.     f.setSize(400,400);  
  14.    f.setLayout(null);  
  15.    f.setVisible(true);  
  16.    s.addAdjustmentListener(new AdjustmentListener() {  
  17.     public void adjustmentValueChanged(AdjustmentEvent e) {  
  18.        label.setText("Vertical Scrollbar value is:"+ s.getValue());  
  19.     }  
  20.  });  
  21. }  
  22. public static void main(String args[])  
  23. {  
  24.    new ScrollBarExample();  
  25. }}  

Output:

JAVA Jscrollbar 2
Anurag Rana Educator CSE/IT

Comments

Popular posts from this blog

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are following header files important to C++ pro