Java Swing How to - Add rows of JTextFields to a JScrollPane








Question

We would like to know how to add rows of JTextFields to a JScrollPane.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
//  www  .  ja  v a2  s . com
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Main {
  public static void main(String[] args) {
    int ROW_HEIGHT = 40;
    String[] TABLE_COLUMNS = { "Foo", "Bar" };
    DefaultTableModel tableModel = new DefaultTableModel(TABLE_COLUMNS, 2);
    JTable table = new JTable(tableModel);
    table.setRowHeight(ROW_HEIGHT);
    JScrollPane scrollpane = new JScrollPane(table);
    JButton addRowBtn = new JButton(new AbstractAction("Add Row") {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        tableModel.addRow(new String[] {"", "" });
      }
    });
    JPanel btnPanel = new JPanel();
    btnPanel.add(addRowBtn);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(scrollpane, BorderLayout.CENTER);
    f.getContentPane().add(btnPanel, BorderLayout.PAGE_END);
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
  }
}