Rory Lester
Rory Lester

Reputation: 2918

Adding a component to jPanel java

i'm trying to add a jtable component to my jPanel but i am unable to see it. What am i doing wrong?.

table gui = new table(data,colum); 
mainPanel.add(gui.table);

class table extends JFrame
{
    public JTable table; 

    public table(Vector data, Vector colum)
    {
        setLayout(new FlowLayout()); 
        table = new JTable(data,colum);
        table.setPreferredScrollableViewportSize(new Dimension(900,10));
        table.setFillsViewportHeight(true);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane); 
    }

}

Upvotes: 0

Views: 1203

Answers (1)

Eric Grunzke
Eric Grunzke

Reputation: 1657

Extending JFrame seems odd; you don't use any of the top level container capabilities. Here's an example that extends JPanel, with a main() that drops the panel into a JFrame.

--Edited to accept an existing JPanel

public class TablePanel
{
  public static void addTableToPanel(JPanel jPanel, Vector rowData, Vector columnNames)
  {
    JTable jTable = new JTable(rowData, columnNames);
    jTable.setFillsViewportHeight(true);

    JScrollPane jScrollPane = new JScrollPane(jTable);
    jScrollPane.setPreferredSize(new Dimension(300, 50));

    jPanel.add(jScrollPane);
  }

  public static void main(String[] args) throws Exception
  {
    SwingUtilities.invokeAndWait(new Runnable()
    {
      @Override
      public void run()
      {
        Vector cols = new Vector();
        Vector rows = new Vector();
        Vector row1 = new Vector();

        cols.add("A");
        cols.add("B");
        cols.add("C");
        row1.add("1");
        row1.add("2");
        row1.add("3");
        rows.add(row1);
        rows.add(row1.clone());
        rows.add(row1.clone());
        rows.add(row1.clone());

        JFrame frame = new JFrame("TableTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel jPanel = new JPanel();
        jPanel.setLayout(new BorderLayout(0, 0));
        TablePanel.addTableToPanel(jPanel, rows, cols);

        frame.getContentPane().add(jPanel);
        frame.pack();
        frame.setVisible(true);
      }
    });
  }
}

Upvotes: 1

Related Questions