Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 to add a title to JTable in Java Swing?
To display a title to the JTable, you can set a title for the JPanel, which already consists of a JTable.
Here, we are using createTitledBorder() for the JPanel to set the title for the panel border that would eventually work for table title.
Let’s say the following is the JPanel −
JPanel panel = new JPanel();
Now, use setBorder() and the BorderFactory class to set a title border for the panel that would be our table title as well −
panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "My Demo Table", TitledBorder.LEFT, TitledBorder.TOP));
The following is an example to add a title to a JTable −
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(), "My Demo Table", TitledBorder.LEFT,
TitledBorder.TOP));
String[][] rec = {
{ "001", "David", "AUS" },
{ "002", "Steve", "AUS" },
{ "003", "Yuvraj", "IND" },
{ "004", "Kane", "NZ" },
{ "005", "Ben", "ENG" },
{ "006", "Eion", "ENG" },
{ "007", "Miller", "SA" },
{ "008", "Rohit", "IND" }
};
String[] header = { "Id", "Player", "Team" };
JTable table = new JTable(rec, header);
panel.add(new JScrollPane(table));
frame.add(panel);
frame.setSize(550, 400);
frame.setVisible(true);
}
}
Output

Advertisements