
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I set a table in a JPanel in Java?
Let us first set rows and columns for our table −
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" };
Now, set the above in a table as rows and columns −
JTable table = new JTable(rec, header);
Add the table in the panel −
JPanel panel = new JPanel(); panel.add(new JScrollPane(table));
The following is an example to create a table in a panel −
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 −
- Related Questions & Answers
- How can we set the background color to a JPanel in Java?
- How can we implement a scrollable JPanel in Java?
- How can we implement the paintComponent() method of a JPanel in Java?
- How to center a JLabel in a JPanel with GridBagLayout in Java?
- How can I place a table on a plot in Matplotlib?
- How can we set time in a table in JDBC?
- How can I get the records from MySQL table in result set in a particular way?
- How can I create a table with borders in Android?
- How can I remove every column in a table in MySQL?
- How can I reverse a string in Java?
- How can I update a table using prepare statements?
- Java Program to center a JLabel in a JPanel with LayoutManager
- How can I set an EtchedBorder from BorderFactory class to a component in Java?
- How can I set scrollbars to never appear in Java?
- How I can reverse a Java Array?
Advertisements