Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with JTable in IntelliJ IDEA


I created a jtable in gui form in intellij and I dont see any data. The strangest thing is that when I am using it with out creating a form in intellij the code works.
i used the most common example
String[] columnNames = {"First Name", "Last Name"};
Object[][] data = {{"Kathy", "Smith"},{"John", "Doe"}
and then
JTable table = new JTable(data, columnNames);
But I get no data.
Is this because of the layout manager?
any help in continue working with intellij gui and jtable?
any good jtable+gui form intellij example?

like image 404
Bick Avatar asked Dec 07 '22 00:12

Bick


2 Answers

When using IDEA GUI Designer, JTable is created for you automatically, if you have new JTable(...) in your code it overrides the table object created by IDEA and all the properties configured for the table in the Designer will be lost.

So, you have 2 approaches here. One is to rely on IDEA to create the table and set its properties, then use table.setModel(dataModel); to provide data to your table from the dataModel.

Second approach is to create the table dynamically from your code and then add this table into the existing JScrollPane or other panel on the form via scrollPane.setViewportView(myTable);.

IDEA also has more advanced approach called Custom Create. If you enable this checkbox for the JTable on the form, IDEA adds createUIComponents() method to the bound class where you create this component manually like ... = new JTable(...).

You can download the complete sample project and experiment with different approaches.

like image 129
CrazyCoder Avatar answered Jan 01 '23 16:01

CrazyCoder


This works in IntelliJ for me:

package swing;

import javax.swing.*;

/**
 * JTableTest
 * User: Michael
 * Date: 11/7/10
 * Time: 4:49 PM
 */
public class JTableTest
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame("JTable Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTable table = createTable();
        JScrollPane scrollPane = new JScrollPane(table);
        frame.getContentPane().add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static JTable createTable()
    {
        String[] columnNames = {"First Name", "Last Name"};
        Object[][] data = {{"Kathy", "Smith"},{"John", "Doe"}};
        JTable table = new JTable(data, columnNames);
        table.setFillsViewportHeight(true);

        return table;
    }
}
like image 30
duffymo Avatar answered Jan 01 '23 17:01

duffymo