tags:

views:

31

answers:

2

I have a JTable in Java swing which needs to be bottom aligned.

As in normal tables when a row is added to the table it is placed on top, when the next row is added it is added under it and so on.

What I would like to do is place the new row at the bottom of the table. When a new row is added I would like the new row to be placed right at the bottom and the previous row to move up. This way the rows appear to move upward. Basically the rows should stick to the bottom.

Any ideas how to do this?

A: 

If @Geoffrey Zheng's assumption is correct, then you can create a table with n empty rows, (eg. a Vector of n null's), and then replace elements in the order you need.

tulskiy
A: 

The code below shows one way to do this with a JList. It will be a little more complicate for a JTable since you will need a second JPanel with a BorderLayout. You would add the table header to the North and the main panel to the Center. Then this panel would be added to the viewport or the scrollpane.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

public class ListBottom2 extends JFrame
{
    JList list;
    JTextField textField;

    public ListBottom2()
    {
        DefaultListModel model = new DefaultListModel();
        model.addElement("First");
        list = new JList(model);
        list.setVisibleRowCount(5);

        JPanel box = new JPanel( new BorderLayout() );
        box.setBackground( list.getBackground() );
        box.add(list, BorderLayout.SOUTH);

        JScrollPane scrollPane = new JScrollPane( box );
        scrollPane.setPreferredSize(new Dimension(200, 100));
        add( scrollPane );

        textField = new JTextField("Use Enter to Add");
        getContentPane().add(textField, BorderLayout.NORTH );
        textField.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                JTextField textField = (JTextField)e.getSource();
                DefaultListModel model = (DefaultListModel)list.getModel();
                model.addElement( textField.getText() );
                int size = model.getSize() - 1;
                list.scrollRectToVisible( list.getCellBounds(size, size) );
                textField.setText("");
            }
        });
    }

    public static void main(String[] args)
    {
        ListBottom2 frame = new ListBottom2();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }
}
camickr