Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a JTable in a JPanel with Java?

How to display a JTable in a JPanel with Java?

like image 820
Eddinho Avatar asked Apr 12 '10 17:04

Eddinho


People also ask

What is the use of JTable in 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.

How to display stock quotes using JTable in Java?

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.

How do I get the model of a JTable?

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.

Which component provides the view of the JTable?

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.


2 Answers

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.

like image 114
justkt Avatar answered Sep 22 '22 08:09

justkt


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..

like image 22
Jack Avatar answered Sep 22 '22 08:09

Jack