I have a row header inside a JScrollPane of which I should set the width according to the maximum width that the text takes. I managed to do so but I have to add 1 in my call to setPreferredScrollableViewportSize in order to display the full text. Did I get the measurement wrong? Or is this quantity fixed?
This is the main class.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
public class Example {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
JTable table = new JTable(5, 3);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
HeaderColumn ch = new HeaderColumn(5, 1);
JFrame frame = new JFrame();
JScrollPane sp = new JScrollPane(table);
sp.setRowHeaderView(ch);
frame.add(sp);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
ch.adjustSize();
}
});
}
}
This is the header class. Please look at adjustSize()
.
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import javax.swing.BorderFactory;
import javax.swing.JTable;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class HeaderColumn extends JTable{
private final int INSET = 2;
public HeaderColumn(int r, int c){
super(r,c);
}
@Override
public void columnAdded(TableColumnModelEvent e){
DefaultTableModel m = (DefaultTableModel)getModel();
int rowCount = m.getRowCount();
for(int i = 0; i < rowCount; i++){
m.setValueAt("#" + Integer.toString(i+1), i, 0);
}
TableColumn tc = getColumnModel().getColumn(e.getToIndex());
tc.setCellRenderer(new DefaultTableCellRenderer(){
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
setText((value == null) ? "" : value.toString());
setBorder(BorderFactory.createEmptyBorder(0, INSET, 0, INSET));
return this;
}
});
}
public void adjustSize(){
FontMetrics fm = getGraphics().getFontMetrics(getTableHeader().getFont());
int maxTextWidth = 0;
DefaultTableModel m = (DefaultTableModel)getModel();
int rowCount = m.getRowCount();
for(int i = 0; i < rowCount; i ++){
int width = fm.stringWidth(m.getValueAt(i, 0).toString());
if(width > maxTextWidth){
maxTextWidth = width;
}
}
setPreferredScrollableViewportSize(new Dimension(maxTextWidth+INSET*2+1, 0));
}
}
I managed to do so but I have to add 1 in my call to setPreferredScrollableViewportSize in order to display the full text. Did I get the measurement wrong? Or is this quantity fixed?
I think you need to include the getIntercellSpacing()
value returned from the table.
Check out Table Column Adjuster for more information and example code for determining the column width.