Search code examples
javaswingjtablejtextfieldlayout-manager

Adding rows of JTextFields to a JScrollPane


I need some advice on which Swing Components to choose in order to achieve the following:

I have something like a "table" structure, that every time that I click the "Add" button, another "row" should be inserted on the "table". Each row is composed of 2 JTextField. The problem I am having with the GridLayout (the layout used in the pictures below) is that if I add another row, then the heights of the text fields will be shortened and I don't want that (picture on the right), I want to preserve the same height for every row.

What I would like to happen is to have the extra row appear below the last one, so that I could use the JScrollPane and scroll to see it.

enter image description here

Should I use another layout rather than the GridLayout? Maybe the AbsoluteLayout or even using the Table Component?

Thanks.


Solution

  • I would use a JTable and set the row height to whatever you desire. For example:

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    
    public class TableEg {
       private static final int ROW_HEIGHT = 40;
       private static final String[] TABLE_COLUMNS = {"Foo", "Bar"};
    
       private static void createAndShowGui() {
          final 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 frame = new JFrame("TableEg");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(scrollpane, BorderLayout.CENTER);
          frame.getContentPane().add(btnPanel, BorderLayout.PAGE_END);
          frame.pack();
          frame.setLocationByPlatform(true);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }