0

I'm a Java beginner and I'm using Eclipse to create an simple app with a SpringLayout and a button inside. I call that button 'btnTABLE' and here is its actionPerformed code:

btnTABLE.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

        String[] columnNames = {"First Name",
                "Last Name",
                "Sport",
                "# of Years",
                "Vegetarian"};

        Object[][] data = {
                {"Kathy", "Smith",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"John", "Doe",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Sue", "Black",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Jane", "White",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Joe", "Brown",
                 "Pool", new Integer(10), new Boolean(false)}
            };

        JTable table = new JTable(data, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        table.setFillsViewportHeight(true);
    }
});

But when i click that button, the table doesn't show up.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Nhan
  • 456
  • 3
  • 12
  • 3
    Hm, do you add it to some frame/dialog? These components cannot appear on their own but within a container. – rlegendi Oct 21 '14 at 15:30
  • I think its container is JScrollPane, is it right ? I also add this at the end: frame.getContentPane().add(scrollPane); but nothing changes #.# – Nhan Oct 21 '14 at 15:50
  • *I think its container is JScrollPane, is it right ?* Yes it is, but this scroll pane is not added to any container so @rlegendi's point still valid. On the other hand while you can add components to containers dynamically (i.e.: by pressing a button), those are tipically placed *before* making the top-level container (window) visible. – dic19 Oct 21 '14 at 15:57
  • thanks for reply. i've found my problem, it's SpringLayout. i have a table added into a scrollpane, the table shows up when i put Scrollpane into frame but it doesn't when putting it to SpringLayout. I wonder why ... – Nhan Oct 21 '14 at 19:47

1 Answers1

2

simple app with a SpringLayout

A SpringLayout is a complicated layout manager. You can' just use simple code like:

frame.getContentPane().add(scrollPane); 

When using SpringLayout you need to specify a few constraints. Read the section from the Swing tutorial on How to Use SpringLayout for more information.

Also, if you are attempting to dynamically add a component to a visible GUI then the basic code is:

panel.add(...);
panel.revalidate();
panel.repaint();

I would suggest you should be using a different layout manager for the panel.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • thank so much, you answer is very useful. I wonder how to add a scrollpane into a SpringLayout. thanks – Nhan Oct 21 '14 at 19:58