How to add JTable to Panel in Java Swing?

Java 8Object Oriented ProgrammingProgrammingSwing

To add JTabel to Panel, let us first crerate a panel −

JPanel panel = new JPanel();

Now, create JTable and add rows and columns with the records −

String[][] rec = {
   { "1", "Steve", "AUS" },
   { "2", "Virat", "IND" },
   { "3", "Kane", "NZ" },
   { "4", "David", "AUS" },
   { "5", "Ben", "ENG" },
   { "6", "Eion", "ENG" },
};
String[] header = { "Rank", "Player", "Country" };
JTable table = new JTable(rec, header);

Add the above created table to panel −

panel.add(new JScrollPane(table));

The following is an example to add JTabel to Panel in Java Swing −

Example

package my;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel();
         panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "ODI Rankings", TitledBorder.CENTER, TitledBorder.TOP));
      String[][] rec = {
         { "1", "Steve", "AUS" },
         { "2", "Virat", "IND" },
         { "3", "Kane", "NZ" },
         { "4", "David", "AUS" },
         { "5", "Ben", "ENG" },
         { "6", "Eion", "ENG" },
      };
      String[] header = { "Rank", "Player", "Country" };
      JTable table = new JTable(rec, header);
      panel.add(new JScrollPane(table));
      frame.add(panel);
      frame.setSize(550, 400);
      frame.setVisible(true);
   }
}

This will produce the following output −

raja
Published on 03-Jun-2019 08:47:10
Advertisements