I have this table here that should be displaying Integer.MAX_VALUE
many rows with scrolling functionality, but there is no scrollpane even though I added one. Can someone shed light on what needs to be changed/added?
import java.awt.*;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
class DynamicTableModel extends AbstractTableModel {
final static String[] headers = {"Seconds Since Epoch", "Formatted Timestamp"};
private static String getPrettyStringFromEpochSeconds(int seconds) {
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm:ss a EEEE, MMMM d, yyyy", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
return formattedDate;
}
@Override
public int getRowCount() {
return Integer.MAX_VALUE;
}
@Override
public int getColumnCount() {
return headers.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return (columnIndex == 0) ? rowIndex : getPrettyStringFromEpochSeconds(rowIndex);
}
}
public class GoodTable extends JPanel{
JTable jt;
public GoodTable(){
DynamicTableModel model = new DynamicTableModel();
JTable table = new JTable(model);
//table.setPreferredScrollableViewportSize(new Dimension(500,300));
table.setFillsViewportHeight(true);
JScrollPane js=new JScrollPane(table);
js.setVisible(true);
add(js);
}
public static void main(String[] args) {
JFrame jf=new JFrame();
GoodTable tab= new GoodTable();
jf.setTitle("Table");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
jf.setSize(screenSize.width, screenSize.height);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(tab);
}
}
There is a limitation when using Integer.MAX_VALUE.
Scrolling works when I use:
public int getRowCount() {
//return Integer.MAX_VALUE / 15; // doesn't work
return Integer.MAX_VALUE / 16;
}
I used 16 since that is the height of each row in the table.
So the maximum preferred size would be rows * 16, since the preferred height is also limited by an Integer value.