How to display a JTable in a JPanel with Java?
The JTable class is a part of Java Swing Package and is generally used to display or edit two-dimensional data that is having both rows and columns. It is similar to a spreadsheet.
Example of using JTable to display stock quotes 1 First we specify the column heading in the columns array. 2 Then we use two-dimensional array data to store stock quotes data. 3 Next we create an instance of JTable by passing table data and column heading to the constructor. 4 Finally we place the table JScrollPane and add it to the main frame.
The model is provided by an interface named TableModel. A default implementation is provided by the Swing API which is named as DefaultTableModel. This is internally used by JTable when we do not provide anything. This is exactly what happened in the above code.
Here, the JTable is the component which provides the view. The model is provided by an interface named TableModel. A default implementation is provided by the Swing API which is named as DefaultTableModel. This is internally used by JTable when we do not provide anything. This is exactly what happened in the above code.
Imports and table model left as an exercise to the user of this code. Also, the panel layout is arbitrarily chosen for simplicity.
public class JTableDisplay {
public JTableDisplay() {
JFrame frame = new JFrame("JTable Test Display");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JTable table = new JTable();
JScrollPane tableContainer = new JScrollPane(table);
panel.add(tableContainer, BorderLayout.CENTER);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new JTableDisplay();
}
}
The scroll pane is fairly important to note. Without it, your table won't have a header or scroll if the content becomes larger than the display.
JTable table = new JTable();
JScrollPane spTable = new JScrollPane(table);
JPanel panel = new JPanel();
panel.add(spTable);
There is a comphrensive guide about how to layout swing components, you should consider Pyrolistical link..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With